使addAction适用于android通知

时间:2016-04-20 20:06:31

标签: android android-intent notifications android-service android-pendingintent

当用户点击通知中的操作按钮时,我尝试做某事。显示带有操作按钮的通知。但出于某种原因,行动并没有解决;接收者没有得到消息。事实上,两个接收者都没有获得意图 - 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());
            }
    }

我一直在墙上撞了几天,看不出有什么不对。

1 个答案:

答案 0 :(得分:0)

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

Intent intent = new Intent("snooze");

使用:

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