【问题标题】:Android notification addAction not launching broadcastAndroid通知addAction未启动广播
【发布时间】:2016-08-24 23:54:14
【问题描述】:

创建通知:

PendingIntent pIntent = PendingIntent.getActivity(context, (int) taskId, intent, 0);
intent.setAction(Utils.MARK_AS_DONE);

PendingIntent pIntentMarkAsDone = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
        .setTicker(ticker)
        .setContentTitle(title)
        .setContentText(description)
        .setSmallIcon(getAlarmIcon(type))
        .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher))
        .setContentIntent(pIntent)
        .addAction(0, context.getString(R.string.mark_as_done), pIntentMarkAsDone);

Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) taskId, notification);

我使用带有 getBroadcast 的挂起意图添加了添加。

接收者:

public class NotificationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Log to check
    }
}

这个类应该“接收”这个动作。我还添加了清单

清单:

<receiver android:name=".NotificationReceiver">
    <intent-filter>
        <action android:name="<package_name>.MARK_AS_DONE"/>
    </intent-filter>
</receiver>

好吧,onReceive 没有接收。我做错了什么?

【问题讨论】:

    标签: android android-intent notifications broadcastreceiver action


    【解决方案1】:

    TL;DR:创建一个新的Intent,而不是重复使用intent 中的那个,并从&lt;receiver&gt; 中删除&lt;intent-filter&gt;


    你的第一行是:

    PendingIntent pIntent = PendingIntent.getActivity(context, (int) taskId, intent, 0);
    

    这意味着intent 标识了一些活动。如果您是通过new Intent(context, YourActivityClass.class) 创建的,那么它内部会设置一个ComponentName,用于标识您的活动。

    然后,您在intent 上调用setAction() 并将其与getBroadcast() 一起使用。但是,除了设置(或替换)操作之外,intent 中的其他所有内容都与以前相同。特别是,标识活动的ComponentName 仍然存在。因此,当发送广播时,Android 无法传递它,因为组件无效(活动不能直接接收广播),并且操作字符串被忽略(因为一旦在 Intent 上设置了 ComponentName,事情like 动作和类别不再计入路由)。

    所以,我建议您创建两个Intent 对象,一个用于活动,一个用于接收者。

    请注意,您不需要接收者的操作字符串。您可以使用显式 Intent 构造函数 (new Intent(context, NotificationReceiver.class))。事实上,在接收器上有操作字符串对安全性不利,因为现在 任何 应用程序都可以向您发送该广播。因此,我建议删除&lt;intent-filter&gt; 并使用显式Intent 来创建您的广播PendingIntent

    【讨论】:

    • 解决了!谢谢!问题确实是:new Intent(context, NotificationReceiver.class)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多