Android通知导致应用程序重新启动,但希望恢复应用程序。

22

您好,我已经成功地在我的应用中显示了通知,但当用户点击通知时,应用程序会重新启动。然而,我只想让它重新出现而不是重新启动。例如,它是一个Web应用程序,当用户选择通知时,我希望它出现在前面,但不要刷新Web页面。我是否可以捕捉此意图,或者我发送了错误的意图?通常,如果我按下主页按钮并单击应用程序图标,应用程序会出现在前面,而不会刷新/重新启动。所以这就是我想要的行为。有什么建议吗?

 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);
6个回答

33

我将这个放在清单文件中。

android:launchMode="singleInstance"

这个方法解决了我的问题。还有这个答案,虽然我没有尝试,但提到了其他很有意思的东西。


1
这个属性导致了另一个问题吗?谢谢。 - famfamfam

13

如果你必须避免将你的activity设置为"singleInstance",那么请按以下方式设置通知的意图:

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

5

2
嗨,感谢您的回答。我在清单中加入了android:launchMode="singleInstance",这为我解决了问题。此外,这些答案还涉及其他有趣的内容... https://dev59.com/sW855IYBdhLWcg3w_5cQ 和 https://dev59.com/sW855IYBdhLWcg3w_5cQ - ozmike

1
我这里有另一个解决方案正在运行:
    //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

0
我建议在这种特定情况下设置 Intent.FLAG_ACTIVITY_SINGLE_TOP 标志,如果您使用 android:launchMode="singleInstance",它会影响您调用应用程序中的其他意图时的行为,例如使用 Facebook SDK、Paypal SDK 等等。
说明在这里很简单: link

FLAG_ACTIVITY_SINGLE_TOP已经被列为答案了 - 非常感谢。 - ozmike

0
如果你在 .MainActivity 的部分中有这个,请从清单中删除它:
android:noHistory="true"

这对于无法在安卓7及以上版本的三星设备(和其他设备)上恢复应用程序来说是致命的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接