android Notification不会触发BroadcastReceiver的onReceive

前端之家收集整理的这篇文章主要介绍了android Notification不会触发BroadcastReceiver的onReceive前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有可能通知开始广播接收者吗?

我试过这个代码,但它没有工作.

通知是创建的,但是当我点击它没有任何反应.

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

通知创建:

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,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" />

解决方法

从你的代码
PendingIntent contentIntent = PendingIntent.getActivity(context,0);

当创建一个定向BroadcastReceiver的PendingIntent时,必须使用getBroadcast(…)而不是getActivity(…).

PendingIntent.getBroadcast(Context context,int requestCode,Intent intent,int flags)

另外,不要这样创建你的意图…

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

这是一个明确的Intent,它定位一个特定的类(通常用于启动一个特定的Activity类).

相反,创建一个’广播’意图与’动作’,如…

Intent notificationIntent = new Intent(MyApp.ACTION_DO_SOMETHING);

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

猜你在找的Android相关文章