问题 Android - 使用标记活动单击推送通知后打开或重新启动应用程序


我在Android中使用推送通知。当我收到推送通知时,我想打开应用程序,如果它仍在运行,否则它应该打开它的新实例。

我在用

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 
    Intent.FLAG_ACTIVITY_CLEAR_TOP | 
    Intent.FLAG_ACTIVITY_SINGLE_TOP | 
    Intent.FLAG_ACTIVITY_NEW_TASK);

但是当我现在收到推送通知并点击它时,没有任何反应。

我怎样才能通过使用flagIntents实现这一目标?


7108
2017-11-27 09:57


起源



答案:


你需要在上面设置Intent标志 Intent。您在调用中指定了它们以获取a PendingIntent。尝试这个:

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
    Intent.FLAG_ACTIVITY_SINGLE_TOP | 
    Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
    notificationIntent, 0);

14
2017-11-27 10:10



是的,这很有效。 Ecpet现在我有另一个问题。有没有办法在onCreate()中使用execure te代码,因为它包含推送通知必须执行的相同代码。现在没有调用onCreate,因此代码没有被执行。 - DijkeMark
如果你没有设置标志 Intent.FLAG_ACTIVITY_SINGLE_TOP,然后将销毁活动的当前实例并创建一个新实例(从而调用 onCreate())。 - David Wasser
它现在正如我所愿。谢谢 - DijkeMark
这对我不起作用...你是否必须在此活动的清单中设置特定的启动模式? - Tooroop
看起来我解决了它。如果我同时设置Intent.Intent.FLAG_ACTIVITY_SINGLE_TOP或launchMode =“singleTop”甚至btoh,则不会调用我的onNewIntent()方法。我补充说:Intent intent = new Intent(this,MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);并在清单中我设置launchMode =“singleTask”。现在它按预期工作 - Tooroop


答案:


你需要在上面设置Intent标志 Intent。您在调用中指定了它们以获取a PendingIntent。尝试这个:

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
    Intent.FLAG_ACTIVITY_SINGLE_TOP | 
    Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
    notificationIntent, 0);

14
2017-11-27 10:10



是的,这很有效。 Ecpet现在我有另一个问题。有没有办法在onCreate()中使用execure te代码,因为它包含推送通知必须执行的相同代码。现在没有调用onCreate,因此代码没有被执行。 - DijkeMark
如果你没有设置标志 Intent.FLAG_ACTIVITY_SINGLE_TOP,然后将销毁活动的当前实例并创建一个新实例(从而调用 onCreate())。 - David Wasser
它现在正如我所愿。谢谢 - DijkeMark
这对我不起作用...你是否必须在此活动的清单中设置特定的启动模式? - Tooroop
看起来我解决了它。如果我同时设置Intent.Intent.FLAG_ACTIVITY_SINGLE_TOP或launchMode =“singleTop”甚至btoh,则不会调用我的onNewIntent()方法。我补充说:Intent intent = new Intent(this,MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);并在清单中我设置launchMode =“singleTask”。现在它按预期工作 - Tooroop


在Android Mainfest文件中设置以下内容

android:noHistory="true"
 android:launchMode = "singleTop"

1
2018-03-06 19:36



为什么 android:noHistory="true" 和 android:launchMode = "singleTop" ? - Yousha Aleayoub