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

来源:互联网 发布:玩游戏 手机 知乎 编辑:程序博客网 时间:2024/06/06 01:12

我们在使用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 senderintent      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,因此将这个值改为每条信息都不一样的值,问题就解决了。

0 0
原创粉丝点击