0
發出的廣播我已經從Service
,我發送一個廣播intent
到BroadcastReceiver
,然後這個廣播接收器發送回的Service
內指定的BroadcastReceiver
。廣播接收器的的onReceive()未能接收由另一廣播接收器
下面的代碼:
private Notification getNotificationAU() {
mBuilder =
new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.mipmap.app_icon_1)
.setContentTitle("title")
.setContentText(***);
// for action button
Intent actionIntent = new Intent(getBaseContext(), BroadcastSender.class);
PendingIntent actionPendingIntent = PendingIntent
.getBroadcast(getBaseContext(),
0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setAutoCancel(true);
mBuilder.addAction(***, "***", actionPendingIntent);
return mBuilder.build();
}
這裏的BroadcastSender.class
代碼:
public class BroadcastSender extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast Received by BroadcastSender", Toast.LENGTH_SHORT).show();
// send back to your class
Intent newIntent = new Intent();
newIntent.setAction(context.getString(R.string.broadcast_id));
context.sendBroadcast(newIntent);
context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
Toast.makeText(context, "Broadcast sent back.", Toast.LENGTH_SHORT).show();
}
}
兩者的Toasts
以上是越來越所示。
這裏的BroadcastReceiver
的Service
內:
public class MyBroadcastReceiver extends BroadcastReceiver {
public MyBroadcastReceiver(){
super();
}
@Override public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "onReceive() in service called", Toast.LENGTH_SHORT).show();
if (intent.getAction() != null && intent.getAction().equals(getString(R.string.broadcast_id_2))) {
...
...
...
} else if (intent.getAction() != null && intent.getAction().equals(getString(R.string.broadcast_id))) {
// perform the task
} else {
Toast.makeText(context, "Intent is null.", Toast.LENGTH_SHORT).show();
}
}
}
這裏是strings.xml
:
<string name="broadcast_id">***</string>
這裏的AndroidManifest.xml
:
<receiver android:name=".BroadcastSender"/>
的問題是是MyBroadcastReceiver
即使在兩個節點都具有相同的廣播ID R.string.broadcast_id
時也沒有收到任何廣播。
爲什麼它沒有收到BroadcastSender.class
發送的廣播?
請讓我知道。
如何註冊和取消註冊廣播接收器?您是否可以顯示代碼 –
您是否也可以將註冊了MyBroadcastReceiver的代碼粘貼到您的服務中? –
感謝您找出這個愚蠢的錯誤!我忘了在註冊廣播接收器時添加'myIntentFilter.addAction(getString(R.string.broadcast_id));'。它現在有效! –