如果我有一个用户关闭的活动(用户在家中按下,那么该应用仍然在应用堆栈中) 然后他收到通知,当他按下它时,我开始一项活动 现在相同的活动被打开两次。 我怎样才能防止这种情况发生?
我的代码:
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Title")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setAutoCancel(true)
.setLights(GCMSIntentService.PURPLE, 500, 500)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(1, mBuilder.build());
答案 0 :(得分:3)
android:launchMode="singleTask"
清单中的或者, 用它作为你意图的标志。
答案 1 :(得分:1)
by android:launchMode="singleTask"
,如果活动的实例已存在于单独的任务中,系统会通过调用其onNewIntent()
方法将意图路由到现有实例,而不是创建新实例并为意图添加标志
FLAG_ACTIVITY_NEW_TASK,FLAG_ACTIVITY_CLEAR_TOP,FLAG_ACTIVITY_SINGLE_TOP
答案 2 :(得分:1)
您需要在通知意图中添加FLAG_ACTIVITY_CLEAR_TOP,FLAG_ACTIVITY_SINGLE_TOP,FLAG_ACTIVITY_NEW_TASK标记。如需更改
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
到
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
答案 3 :(得分:0)
这是错误。
通知函数id必须每次都更改。你每次都给它1。这就是错误。
mNotificationManager.notify(1,mBuilder.build());
每次都提供不同的ID。它会像魅力一样发挥作用。
例如,每次都使用sharedPrefences提供不同的id。
检查一下,
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Title")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setAutoCancel(true)
.setLights(GCMSIntentService.PURPLE, 500, 500)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
SharedPreferences sp = context.getSharedPreferences("randomidfornotification", Activity.MODE_PRIVATE);
myIntValue = sp.getInt("notificationid", 0);
mNotificationManager.notify(1, mBuilder.build());
SharedPreferences sp1 = context.getSharedPreferences("randomidfornotification", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("notificationid", myIntValue+1);
editor.apply();