【问题标题】:android Notification doesnt trigger BroadcastReceiver's onReceiveandroid Notification不会触发BroadcastReceiver onReceive
【发布时间】:2012-06-07 23:02:35
【问题描述】:

是否可以让通知启动广播接收器?

我试过这段代码,但它不起作用。

通知已创建,但当我点击它时没有任何反应。

注意:当我将 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, 0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    notificationManager.notify(1,notification);

这是广播接收器

public static class MyBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
   /*
          */

 }
}

AndroidManifest.xml 内部

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

【问题讨论】:

    标签: android android-intent android-notifications


    【解决方案1】:

    根据您的代码...

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

    在创建以BroadcastReceiver 为目标的PendingIntent 时,您必须使用getBroadcast(...) 而不是getActivity(...)

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

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

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

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

    而是创建一个“广播”Intent,并带有一个“动作”,例如...

    Intent notificationIntent = new Intent(MyApp.ACTION_DO_SOMETHING);
    

    您还需要为清单的 &lt;receiver android:name=".MyBroadcastReceiver" /&gt; 部分指定 &lt;intent-filter&gt; 部分。

    【讨论】:

    • @Abhishek:没问题。当我第一次使用通知时,当我实际上想启动一个Service(它使用getService)时,我陷入了使用getActivity 作为PendingIntent 的同一个陷阱。很好的一课。 :)
    • @Abhishek 你忘了为 notificationIntent 提及 setClass notificationIntent.setClass(context, MyBroadcastReceiver.class);
    • 请注意,此答案的第二部分并不正确。对于清单注册的接收器,显式的Intent 非常好,当然也是首选。实际上,从 API 级别 26 开始,对于针对该版本及更高版本的应用程序,隐式 Intents 不再适用于在清单中注册的接收器 except for a few specific system broadcasts。您仍然可以在Intent 上设置操作,以识别接收器中的不同广播,但您不需要&lt;receiver&gt; 上的&lt;intent-filter&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    相关资源
    最近更新 更多