最近开发中使用到了通知栏,产品需要统计通知栏的的展示和点击。展示比较方便,直接在通知栏 notify() 时进行上传统计即可;点击使用到了Intent 传递参数,然后在 MainActivity 的 onNewIntent() 中读取 Intent,再上传统计即可。
public PendingIntent getPendingIntent() {
Intent intent = new Intent(App.getInstance(), MainActivity.class);
int entrance = PushManger.getInstance(App.getInstance()).getEntrance();
intent.putExtra(PushManger.ENTRANCE, entrance);
return PendingIntent.getActivity(App.getInstance(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
由于点击通知栏打开的是同一个 Activity,仅通知 id 不一样,发现同时弹出多个通知时,最后一个通知的 Intent 会覆盖之前通知的 Intent。content 参数是固定的,intent 参数的 Extra 已经不同了,修改 PendingIntent.getActivity() 的 Flags 参数也没用,剩下唯一相同的参数就是 requestCode 参数了,最后尝试修改 requestCode 参数,竟然神奇的解决了问题。但关于这个参数,Google 并没有给出更多的解释,这里权且记录下问题的解决,原理还有待挖掘。
/**
* Retrieve a PendingIntent that will start a new activity, like calling
* {@link Context#startActivity(Intent) Context.startActivity(Intent)}.
* Note that the activity will be started outside of the context of an
* existing activity, so you must use the {@link Intent#FLAG_ACTIVITY_NEW_TASK
* Intent.FLAG_ACTIVITY_NEW_TASK} launch flag in the Intent.
*
* <p class="note">For security reasons, the {@link android.content.Intent}
* you supply here should almost always be an <em>explicit intent</em>,
* that is specify an explicit component to be delivered to through
* {@link Intent#setClass(android.content.Context, Class) Intent.setClass}</p>
*
* @param context The Context in which this PendingIntent should start
* the activity.
* @param requestCode Private request code for the sender
* @param intent Intent of the activity to be launched.
* @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE},
* {@link #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT},
* or any of the flags as supported by
* {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
* of the intent that can be supplied when the actual send happens.
*
* @return Returns an existing or new PendingIntent matching the given
* parameters. May return null only if {@link #FLAG_NO_CREATE} has been
* supplied.
*/
public static PendingIntent getActivity(Context context, int requestCode,
Intent intent, @Flags int flags) {
return getActivity(context, requestCode, intent, flags, null);
}
public PendingIntent getPendingIntent() {
Intent intent = new Intent(App.getInstance(), MainActivity.class);
int entrance = PushManger.getInstance(App.getInstance()).getEntrance();
intent.putExtra(PushManger.ENTRANCE, entrance);
return PendingIntent.getActivity(App.getInstance(), entrance, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}