您的位置:首页 > 移动开发 > Android开发

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

2015-12-21 17:06 435 查看
我们在使用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,因此将这个值改为每条信息都不一样的值,问题就解决了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android