关于多个notification时,其他notification点击无效的解决办法

我们在使用android的通知栏(Notification)时,需要新建一个PendingIntent对象用于处理点击该通知之后的事件。

PendingIntent需要传入一个Intent对象,用于打开Activity、Broadcast或是Service。

PendingIntent.getActivity可以将intent对象与notification对象关联起来,示例如下:

Intent intent = new Intent(context, Activity.class);
notification.contentIntent = PendingIntent.getActivity(context, requestCode, intent, flags);

这样的话,点击notification时,就会启动相应的activity,并通过Intent将相应的参数传递过去。

之前的写法是这样的:

notification.contentIntent = PendingIntent.getBroadcast(appContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

当我在发送两条以上的notification时,最新发送的notification点击后可以正常跳转Activity,但是之前发送的点击之后都没有反应。我一直以为是flags参数的问题,就把PendingIntent.FLAG_CANCEL_CURRENT(表示有变动时更新Intent里Extras的值)改成了PendingIntent.FLAG_UPDATE_CURRENT(表示清除前面的Intent重新new一个),发现问题依然没有解决。

然后我去看了下源码里面对getActivity(context, requestCode, intent, flags)方法参数的注释:

context 
    The Context in which this PendingIntent should start the activity.
requestCode 
    Private request code for the sender
intent  
    Intent of the activity to be launched.  
flags   
    May be FLAG_ONE_SHOT, FLAG_NO_CREATE, FLAG_CANCEL_CURRENT,FLAG_UPDATE_CURRENT, or any of the flags as supported by Intent.fillIn() to control which unspecified parts of the intent that can be supplied when the actual send happens.

context intent这两个参数就不用解释了,刚才试过了,跟flags的值也没有关系,那就只剩下requestCode这个值了,看了下PendingIntent的相关源码:

    public static PendingIntent getActivity(Context context, int requestCode,
            @NonNull Intent intent, @Flags int flags, @Nullable Bundle options) {
        String packageName = context.getPackageName();
        String resolvedType = intent != null ? intent.resolveTypeIfNeeded(
                context.getContentResolver()) : null;
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess();
            IIntentSender target =
                ActivityManagerNative.getDefault().getIntentSender(
                    ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
                    null, null, requestCode, new Intent[] { intent },
                    resolvedType != null ? new String[] { resolvedType } : null,
                    flags, options, UserHandle.myUserId());
            return target != null ? new PendingIntent(target) : null;
        } catch (RemoteException e) {
        }
        return null;
    }

可以注意到,在调用getActivity方法时,源码里将requestCode这个值传入到新的IIententSender对象里面了,猜测应该是sender用requestCode来区分不同的PendingIntent对象,在看之前有问题的代码,所有的requestCode的值都为0,因此将这个值改为每条信息都不一样的值,问题就解决了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值