android通知不会触发BroadcastReceiver的onReceive

是否有可能通知开始广播接收机?

我试过这个代码,但它不工作。

通知创build,但是当我点击它时,什么也没有发生。

注意:当我更改notificationIntent从MyBroadcastReceiver.class指向一个活动(如MainActivity.class)它工作正常。

通知创build:

NotificationManager notificationManager = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE); int notificationIconId = XXXXXX Notification notification = new Notification( notificationIconId, XXXXXX, System.currentTimeMillis() ); CharSequence contentTitle = XXXXXXX CharSequence contentText = XXXXXX Intent notificationIntent = new Intent(context,MyBroadcastReceiver.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); notificationManager.notify(1,notification); 

这是BroadcastReceiver

 public static class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { /* */ } } 

在AndroidManifest.xml里面

 <receiver android:name=".MyBroadcastReceiver" /> 

Solutions Collecting From Web of "android通知不会触发BroadcastReceiver的onReceive"

从你的代码…

 PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); 

当创build一个定位到BroadcastReceiverPendingIntent ,你必须使用getBroadcast(...)而不是getActivity(...)

请参阅PendingIntent.getBroadcast(上下文上下文,int requestCode,Intent intent,int标志)

另外,不要像这样创build你的Intent

 Intent notificationIntent = new Intent(context,MyBroadcastReceiver.class); 

这是一个明确的Intent ,其目标是一个特定的类(通常用于启动一个特定的Activity类)。

相反,创build一个“广播” Intent与“行动”,如…

 Intent notificationIntent = new Intent(MyApp.ACTION_DO_SOMETHING); 

您还需要为清单中的<receiver android:name=".MyBroadcastReceiver" />部分指定<intent-filter>部分。