我想防止系统在用户单击通知且应用程序处于前台时重新启动我的应用程序。
我的测试:
1) adding android:launchMode="singleInstance"
2) adding intent.setAction(Intent.ACTION_MAIN)
3) Modifying flags using Intent.FLAG_ACTIVITY_SINGLE_TOP, or FLAG_ACTIVITY_REORDER_TO_FRONT, or FLAG_ACTIVITY_CLEAR_TOP
4) changing PendingIntent.FLAG_UPDATE_CURRENT to 0 (zero)
没事。每次我单击通知应用程序重新启动。但是我想在应用程序中阻止它。
这里是我的代码:
Intent intent = new Intent(service, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pending = PendingIntent.getActivity(
context,
aggregation,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
manager.notify(
aggregation,
new NotificationCompat.Builder(
service,
Type.isMessage(push.getEnumType())
/*mycode*/
.setCategory(category)
.setWhen(push.getWhen())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pending)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE)
.setNumber(number)
.setStyle(style)
.setAutoCancel(true)
.build());
好,我知道了。
[PendingIntent
一旦创建,将保留在系统中,直到您重新引导系统(我不确定这种情况)或卸载应用程序。
您的情况下,简单的解决方案约为两个步骤:
1)正如我说过的,您应该删除以下代码行:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
并通过清单定义此行为:
android:launchMode="singleInstance"
2)每次调用PendingIntent.FLAG_UPDATE_CURRENT
的构造函数时,都将PendingIntent.FLAG_CANCEL_CURRENT
替换为PendingIntent
。
重要提示:建议您阅读PendingIntent
文档以详细了解其工作原理。