让 addAction 为 android 通知工作

Make addAction work for android notification

我正在尝试在用户点击通知中的操作按钮时执行某些操作。通知显示时带有操作按钮。然而出于某种原因,行动并没有开火;接收者没有收到消息。事实上,两个接收器都没有得到意图 - WakefulBroadcastReceiver(用于警报),BootReceiver(用于在启动时设置警报)。

代码如下:

public class OSService extends IntentService {

        // Call this method from onHandleIntent
        private void createNotification(OrderSearch search)
            {
                String name = search.getName();
                NumberFormat df = NumberFormat.getIntegerInstance();
                Context context = getApplicationContext();

                Intent intent = new Intent("snooze");
                PendingIntent snoozer = PendingIntent.getBroadcast(context, 12345, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_stat_notify)
                        .setContentTitle(df.format(search.getOrderCount()) + " orders")
                        .setAutoCancel(true)
                        .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notify2))
                        .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
                        .addAction(R.drawable.ic_alarm_off_black_18dp, "for today", snoozer)
                        .setContentText(name);


                NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                manager.notify(1, builder.build());
            }
}

在清单文件中:

<application ...>
   <receiver a:name=".ActionReceiver"/>
</application>

动作接受者:

public class ActionReceiver extends BroadcastReceiver
    {
        public void onReceive(Context context, Intent intent)
            {
                Log.i(getClass().getSimpleName(), "Action: " + intent.getAction());
            }
    }

这几天一直在用头撞墙,看不出有什么问题。

您的 Intent 用于 "snooze" 的操作。您的 <receiver> 没有 <intent-filter>,更不用说 "snooze" 了。如果您打算为 Notification 操作调用 ActionReceiver,请替换:

Intent intent = new Intent("snooze");

与:

Intent intent = new Intent(context, ActionReceiver.class);