android Intent.getIntExtra()正在生成意外结果

9rbhqvlz  于 2023-03-21  发布在  Android
关注(0)|答案(2)|浏览(155)

我正在使用NotificationCompat.Builder类发布通知,并向其添加名为 Cancel 的操作按钮
我希望通过单击此操作按钮可以解除通知。为此,我发送了一个广播,并通过在Intent上调用putExtra(String, int)将通知ID附加到Intent对象
BroadcastReceiver通过调用getIntExtra(String, int)接收通知的id,通过调用NotificationManagerCompat.cancel(id)取消通知
但是,每次我尝试时,BroadcastReceiver收到的id的值都是8。因此,我无法取消通知。
下面是我的代码,它将操作按钮添加到通知,

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);

广播接收器类

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 ....:
            ....
        }
    }
 }

日志目录始终报告BroadcastReciver获取的通知id值为8

bihw5rsg

bihw5rsg1#

我正在做同样的事情,并得到正确的输出:

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);

在广播接收端:

if(intent != null){
            if(intent.getExtras() != null){
                notificationId = intent.getExtras().getInt("notification_id",0);
            }
        }

尝试将挂起意向标志0更改为PendingIntent.FLAG_UPDATE_CURRENT

tez616oj

tez616oj2#

构建PendingIntentPendingIntent.getBroadcast()调用的第4个参数)时,需要使用以下标志之一:

  • FLAG_UPDATE_CURRENT,保留PendingIntent(如果存在),但将其额外数据替换为新Intent中的数据
  • FLAG_CANCEL_CURRENT,用于在创建新PendingIntent之前取消现有PendingIntent(如果有)。

默认行为是,如果PendingIntent已经存在,则不替换(!!)额外数据。

相关问题