【问题标题】:Make addAction work for android notification使 addAction 适用于 android 通知
【发布时间】:2016-04-20 20:06:31
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    Intent intent = new Intent("snooze");
    

    与:

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

    【讨论】:

    • 这完全符合需要!没有 的原因是我想利用静态最终字段。但是没有像这样构建 Intent ......好吧,让我觉得很愚蠢。感谢您指出疏忽。
    猜你喜欢
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    相关资源
    最近更新 更多