我使用pyplot
类发布通知,并为其添加一个名为取消的操作按钮。我希望通过单击此操作按钮来解除通知。为此,我通过致电NotificationCompat.Builder
上的Intent
发送广播并将通知ID附加到putExtra(String, int)
对象
Intent
通过致电BroadcastReceiver
收到通知ID,并通过致电getIntExtra(String, int)
取消通知。
但是,每次尝试时,NotificationManagerCompat.cancel(id)
收到的id
的值为8.因此,我无法取消通知。
这是我的代码,它将动作按钮添加到通知中,
BroadcastReceiver
BroadcastReceiver类
Intent cancelIntent = new Intent(this, NotificationActionReceiver.class);
cancelIntent.putExtra(EXTRA_NOTIFICATION_ID, id);
cancelIntent.setAction(ACTION_DISMISS);
if (BuildConfig.DEBUG)
Log.d(TAG, "Sent id: "+id);
PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(this, 0, cancelIntent, 0);
builder.addAction(R.drawable.ic_dismiss, "Cancel", pendingCancelIntent);
log cat始终报告 public class NotificationActionReceiver extends BroadcastReceiver {
private final static String TAG = NotificationActionReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive(), getAction == "+intent.getAction());
switch (intent.getAction()){
case MyActivity.ACTION_DISMISS:
int id = intent.getIntExtra(MyActivity.EXTRA_NOTIFICATION_ID, -1);
if (BuildConfig.DEBUG)
Log.d(TAG, "Notification id received: "+id);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.cancel(id);
break;
case ....:
....
}
}
}
获取通知ID的值为8
答案 0 :(得分:1)
我正在做同样的事情,我得到了正确的输出:
ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Log.v(TAG," Notification id:" + model.getNotificationIdForLocalDB());
Intent intent1 = new Intent(context, AlarmReceiver.class);
intent1.putExtra("notification_id", model.getNotificationIdForLocalDB());
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, model.getNotificationIdForLocalDB(), intent1, PendingIntent.FLAG_UPDATE_CURRENT);
在BroadcastReceiver结束时:
if(intent != null){
if(intent.getExtras() != null){
notificationId = intent.getExtras().getInt("notification_id",0);
}
}
尝试将待定意图标记0
更改为PendingIntent.FLAG_UPDATE_CURRENT