Activity 从服务接收参数
Activity receive params from service
我编写了一个向 activity 发送广播消息的服务,但在 activity 中我总是得到空结果(broadcastMessage 为空)。请参阅下面的代码。
服务代码
Intent i = new Intent("MessageBroadcast");
i.putExtra("HuaeState", 200);
sendBroadcast(i);
Activity 代码:当我在调试模式下放置一个断行时,我可以看到值 broadcastMessage 为 null
public void onReceive(Context context, Intent intent) {
String broadcastMessage = intent.getExtras().getString("HuaeState");
}
像这样修改您在服务中的代码:
Intent i = new Intent("MessageBroadcast");
Bundle bundle=new Bundle();
bundle.putInt("HuaeState", 200);
sendBroadcast(i);
接收者喜欢:
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
int value = bundle.getInt("HuaeState");
}
您犯的错误是您将值设置为 intent 并从 bundle 中获取值。
原因是您将整数值添加到 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
我编写了一个向 activity 发送广播消息的服务,但在 activity 中我总是得到空结果(broadcastMessage 为空)。请参阅下面的代码。
服务代码
Intent i = new Intent("MessageBroadcast");
i.putExtra("HuaeState", 200);
sendBroadcast(i);
Activity 代码:当我在调试模式下放置一个断行时,我可以看到值 broadcastMessage 为 null
public void onReceive(Context context, Intent intent) {
String broadcastMessage = intent.getExtras().getString("HuaeState");
}
像这样修改您在服务中的代码:
Intent i = new Intent("MessageBroadcast");
Bundle bundle=new Bundle();
bundle.putInt("HuaeState", 200);
sendBroadcast(i);
接收者喜欢:
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
int value = bundle.getInt("HuaeState");
}
您犯的错误是您将值设置为 intent 并从 bundle 中获取值。
原因是您将整数值添加到 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