Android - 在点击推送通知后使用活动标志打开或重新启动应用程序

11

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

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

但是现在当我收到推送通知并点击它时,什么也不会发生。

我如何通过使用flagIntents来实现这一点呢?

3个回答

17

您需要在 Intent 上设置 Intent 标志。您之前是在调用获取 PendingIntent 的时候指定了这些标志。请尝试以下操作:

// 构建 Intent 并设置标志
Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

// 获取 PendingIntent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
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);

是的,这个可以工作。但现在我有另一个问题。有没有办法执行我在onCreate()中的代码,因为它包含了推送通知所需执行的相同代码。现在onCreate()没有被调用,因此代码没有被执行。 - DijkeMark
3
如果您不设置标志Intent.FLAG_ACTIVITY_SINGLE_TOP,那么当前的Activity实例会被销毁并创建一个新的实例(从而调用onCreate())。 - David Wasser
这对我没有用...你必须在清单文件中为此活动设置特定的启动模式吗? - Tooroop
2
看起来我解决了它。如果我设置Intent.Intent.FLAG_ACTIVITY_SINGLE_TOP或launchMode="singleTop",甚至同时设置两者,我的onNewIntent()方法将不会被调用。 我添加了以下内容: Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 并在清单文件中设置了launchMode="singleTask"。现在它按预期工作了。 - Tooroop
解决这个谜团 https://dev59.com/IG_Xa4cB1Zd3GeqPyz_p @Tooroop - Renan Franca
显示剩余5条评论

1

在您的Android清单文件中设置以下内容

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

1
为什么要使用 android:noHistory="true"android:launchMode = "singleTop" - Yousha Aleayoub

0
在我的情况下,每次我点击推送通知时,一个正在运行的应用程序都会重新启动。但我不想重新启动应用程序。
PendingIntent中,我有一个意图需要调用Activity2的Activity1。这些代码中存在一个错误:
val intent = Intent(context, Activity2::class.java)
// Remove this line:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(intent)

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