所以我在android中学习了BroadcastReceiver。 BroadcastReceivers基于观察者设计模式(这使得它们非常有趣) 所以我想要实现的是广播我的消息,并在同一活动内我希望收到消息(仅用于测试目的)。 这是代码段
Log.d("ABC", "sending");
Intent intent = new Intent("com.yourcompany.testIntent");
intent.putExtra("value", "test");
sendBroadcast(intent);
Log.d("ABC", "sent");
IntentFilter filter = new IntentFilter("com.yourcompany.testIntent");
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("ABC","INSIDE ");
String value = intent.getExtras().getString("value");
}
};
Log.d("ABC", "receiving");
registerReceiver(receiver, filter);
Log.d("ABC", "received");
这是调试输出
04-06 20:40:52.446 20149-20149 / com.example.illuminati.broadcastreceiver D / ABC:发送 04-06 20:40:52.447 20149-20149 / com.example.illuminati.broadcastreceiver D / ABC:04-06发送 20:40:52.448 20149-20149 / com.example.illuminati.broadcastreceiver D / ABC:收到04-06 20:40:52.453 20149-20149 / com.example.illuminati.broadcastreceiver D / ABC:收到
为什么它没有进入onReceive()方法
我在这里失踪了什么
有什么帮助吗?
答案 0 :(得分:3)
您在注册广播接收器之前发送广播消息。尝试按以下方式进行,它将起作用:
IntentFilter filter = new IntentFilter("com.yourcompany.testIntent");
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("ABC", "INSIDE ");
String value = intent.getExtras().getString("value");
}
};
registerReceiver(receiver, filter);
Intent intent = new Intent("com.yourcompany.testIntent");
intent.putExtra("value", "test");
sendBroadcast(intent);
答案 1 :(得分:0)
如果您想在应用内广播消息(而不是每个安装的应用),您还应该考虑使用LocalBroadcastManager。见https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html