android Notification 不会触发 BroadcastReceiver 的 onReceive [英] android Notification doesnt trigger BroadcastReceiver's onReceive

查看:47
本文介绍了android Notification 不会触发 BroadcastReceiver 的 onReceive的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to have a notification start a broadcast receiver?

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

I tried this code but it doesnt work.

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

Notification is created but when I click on it nothing happens.

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

NOTE: When I change the notificationIntent to point from MyBroadcastReceiver.class to an activity (like MainActivity.class) it works fine.

通知创建:

    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 内部

Inside AndroidManifest.xml

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

推荐答案

从你的代码...

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

在创建针对 BroadcastReceiverPendingIntent 时,您必须使用 getBroadcast(...) 而不是 getActivity(...).

When creating a PendingIntent targetting a BroadcastReceiver, you have to use getBroadcast(...) and not getActivity(...).

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

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

Also, don't create your Intent like this...

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

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

That is an explicit Intent which targets a specific class (used for starting a specific Activity class usually).

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

Instead create a 'broadcast' Intent with an 'action' such as...

Intent notificationIntent = new Intent(MyApp.ACTION_DO_SOMETHING);

您还需要为 <receiver android:name=".MyBroadcastReceiver"/> 部分指定 部分你的清单.

You'll also need to specify a <intent-filter> section for the <receiver android:name=".MyBroadcastReceiver" /> section of your manifest.

这篇关于android Notification 不会触发 BroadcastReceiver 的 onReceive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆