21

嗨,我已经能够获得为我的活动显示的通知,并且当用户单击通知时,应用程序会重新启动。但是我只是希望它重新出现而不是重新启动。例如。它是一个网络应用程序,我希望它在用户选择通知时出现在前面。但不刷新网页。我可以捕获这个意图还是我发送了错误的意图?通常,如果我按下主页按钮并单击应用程序图标,应用程序就会出现并且不会刷新/重新启动。所以这就是我想要的行为。有任何想法吗 ?

 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);
4

6 回答 6

33

我把它放在清单中

android:launchMode="singleInstance"

这解决了我的问题。这个我还没有尝试过的答案也暗示了其他有趣的事情。

于 2011-04-11T13:14:09.493 回答
13

如果您必须避免将活动设置为“singleInstance”,请按如下方式设置通知的意图:

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
于 2011-10-10T16:28:46.203 回答
5

你可以试试这个 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);
于 2011-04-09T13:28:37.880 回答
0

我建议为这种特殊情况设置标志 Intent.FLAG_ACTIVITY_SINGLE_TOP,如果您使用 android:launchMode="singleInstance" 它会影响您在应用程序中调用其他意图时的行为,例如使用 facebook sdk、paypal sdk 等。

这里的解释很简单: 链接

于 2017-02-22T15:41:56.547 回答
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
于 2019-01-15T12:21:13.420 回答
0

如果您有它,请从 .MainActivity 活动部分的清单中删除它:

android:noHistory="true"

这对于无法在 Android 7 之后的三星设备(和其他设备)上恢复应用程序是致命的

于 2019-05-18T20:30:19.667 回答