我正在尝试从IntentService发送广播,但我没有运气。
MainActivity
private void registerBroadcastReceiver() {
Context context = this;
IntentFilter filter = new IntentFilter();
filter.addAction("io.a.spike");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("******* received broadcast *******");
}
};
registerReceiver(receiver, filter);
}
IntentService
@Override
protected void onHandleIntent(Intent intent) {
System.out.println("send broadcast");
Intent notificationIntent = new Intent();
notificationIntent.setClass(this, MainActivity.class);
notificationIntent.setAction("io.a.spike");
sendBroadcast(notificationIntent);
}
我没有进入registerBroadcastReceiver方法中的 onReceive 方法。任何指导将不胜感激。
谢谢。
答案 0 :(得分:0)
要调用您的onReceive()
,您必须添加这些-
将您的BroadcastReceiver添加到清单中,通过这种方式-
<receiver android:name="YourReceiver"> <intent-filter> <action android:name="YourAction" /> </intent-filter> </receiver>
在您的活动中致电registerReceiver()
。
另外,不要忘记致电unegisterReceiver()
以避免泄漏。
答案 1 :(得分:0)
您可以使用LocalBroadcastManager
创建实例
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
注册接收人
localBroadcastManager.registerReceiver(new YourReceiver(),新 IntentFilter(“ YourAction”));
发送广播
localBroadcastManager.sendBroadcast(intent);
取消注册接收者
localBroadcastManager.unregisterReceiver(mybroadcast);