活动从服务中接收参数

时间:2015-01-13 10:02:14

标签: android broadcastreceiver

我编写了一个向活动发送广播消息的服务,但在活动中我总是得到null结果(broadcastMessage为null)。请参阅下面的代码。

服务代码

        Intent i = new Intent("MessageBroadcast");
        i.putExtra("HuaeState", 200);
        sendBroadcast(i);

活动代码:当我在调试模式下面放置一个断行时,我可以看到值broadcastMessage为空

         public void onReceive(Context context, Intent intent) {
                String broadcastMessage = intent.getExtras().getString("HuaeState");

         }

2 个答案:

答案 0 :(得分:1)

修改服务中的代码,如下所示:

    Intent i = new Intent("MessageBroadcast");
    Bundle bundle=new Bundle();
    bundle.putInt("HuaeState", 200);
    sendBroadcast(i);

和Receiver赞:

  public void onReceive(Context context, Intent intent) {
              Bundle bundle = intent.getExtras();
              int value = bundle.getInt("HuaeState");

       }

您所做的错误是您将值设置为intent并从bundle获取值。

答案 1 :(得分:1)

原因是您要将整数值添加到intent中并以字符串形式获取。

使用 getint()

String broadcastMessage = String.valueOf(intent.getExtras().getInt("HuaeState"));

String broadcastMessage = String.valueOf(intent.getIntExtra("HuaeState", -1)); // Where -1 is default value to indicate that there is something wrong while reading value from intent