嗨,我已经能够得到一个通知显示我的活动,当用户点击应用程序重启的通知。然而,我只是希望它重新出现,而不是重新启动。如。这是一个web应用程序,我希望它来到前面,当用户选择通知…但不刷新网页。我是否可以捕获这个意图,或者我是否发送了错误的意图?通常情况下,如果我按下home键并点击应用程序图标,应用程序会出现在前面,不会刷新/重启。这就是我想要的行为。有什么想法吗?
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns);
//2.Instantiate the Notification
int icon = R.drawable.notification_icon;
CharSequence tickerText = "My App"; // temp msg on status line
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
//3.Define the Notification's expanded message and Intent:
Context context = getApplicationContext();
CharSequence contentTitle = "Notification";
CharSequence contentText = "My app!"; // message to user
Intent notificationIntent = new Intent(this, HelloAndroid2.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
//4.Pass the Notification to the NotificationManager:
final int NOTIFICATION_ICON_ID = 1;
mNotificationManager.notify(NOTIFICATION_ICON_ID, notification);
我把它放在manifest
android:launchMode="singleInstance"
这为我解决了这个问题。还有这个答案,我还没有试过,它暗示了其他有趣的事情。
如果你必须避免设置你的活动为"singleInstance",那么设置通知的意图如下:
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
您可以尝试这个FLAG_ACTIVITY_REORDER_TO_FRONT(文档准确地描述了您想要的内容)
http://developer.android.com/reference/android/content/Intent.html FLAG_ACTIVITY_REORDER_TO_FRONT
Intent notificationIntent = new Intent(this, HelloAndroid2.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
我有另一个解决方案:
//Resume or restart the app (same as the launcher click)
val resultIntent = Intent(context, MyLauncherActivity::class.java)
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER)
resultIntent.setAction(Intent.ACTION_MAIN)
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val pendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(pendingIntent) //builder is the notificationBuilder
我建议设置Intent标志。FLAG_ACTIVITY_SINGLE_TOP对于这种特殊情况,如果你使用android:launchMode="singleInstance",它会影响你在应用程序中调用其他意图时的行为,例如使用facebook sdk, paypal sdk等。
这里的解释很简单:链接
从manifest中删除。mainactivity activity部分:
android:noHistory="true"
这是致命的,无法恢复应用程序在三星设备(和其他)的Android更新到7