Android:如何避免点击通知时调用onCreate()方法

18
在我的应用程序中,如果发生特殊事件,我会通过通知来告知用户:
public void triggerNotification(String msg) {
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent contentIntent = new Intent(this, ABC.class);
        Notification notification = new Notification(R.drawable.icon, msg, System.currentTimeMillis());
        notification.setLatestEventInfo(this, "ABC", msg, PendingIntent.getActivity(this.getBaseContext(), 0, contentIntent, PendingIntent.FLAG_CANCEL_CURRENT));
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(notificationCounter, notification);
        notificationCounter++;
}
如果用户点击通知,则会调用onCreate()方法。但我希望调用我的应用程序中的特定方法,或者如果应用程序不在前台,则将其带回到前台。
我知道有很多教程可以解释如何处理通知,但我只是不完全理解它们,并且从未能够像我想要的那样实现这些东西。
3个回答

18

如果您的应用程序已经在运行中,想要将其带到前台,则需要在意图上设置不同的标志:

contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

如果要运行特定的方法,您可以在意图中传递额外的信息,并在应用程序中进行解释,以决定要运行哪个方法。


是的,我在我的Intent中添加了一些额外的内容。但是我在哪里可以提取这些额外的信息呢?根据你的版本,onCreate()没有被调用。 - RoflcoptrException
3
好的,我找到了答案:会调用Activity#onNewIntent(Intent intent)方法。 - RoflcoptrException

10

推荐使用FLAG_ACTIVITY_CLEAR_TOP和FLAG_ACTIVITY_SINGLE_TOP只能部分地解决问题。 Android清单中的活动还应具有这些设置,以便从主屏幕启动活动具有相同的行为。如果没有这些属性,则可能会启动多个活动实例。

<activity android:name="foo"
          android:clearTaskOnLaunch="true"
          android:launchMode="singleTop"
          android:label="@string/app_name">

1
对我来说,stealthcopter提供的解决方案在没有添加这些行的情况下无法正常工作... - Florian Loch

0
我发现如果你使用 Intent contentIntent = new Intent(this, ABC.class);,无论设置了什么标志,都会调用 onCreate();

使用 Intent contentIntent = getIntent(); 跳过 onCreate();,直接进入 onStart();

我似乎找不到在FirebaseMessagingService中获取Activity上下文的方法,以便调用getIntent()。 - Donki

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