简体   繁体   English

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

[英]Android: How to avoid that clicking on a Notification calls onCreate()

In my application I notify the user with notifications, if something special happens: 在我的应用程序中,如果发生特殊情况,我会通知用户通知:

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++;
}

If the user clicks on the Notification, the onCreate() method is called. 如果用户单击Notification,则调用onCreate()方法。 But I want that a specific method in my app is called, or if the app is not in the foreground, that it is brought back to the foreground. 但我想要调用我的应用程序中的特定方法,或者如果应用程序不在前台,则将其带回前台。

I know there are lots of tutorials that explain how to handle notifications, but I just don't understand them completely and wasn't ever able to implement the things like I'd like to. 我知道有很多教程可以解释如何处理通知,但我完全不理解它们,并且无法实现我想要的东西。

To bring your app to the foreground if it is running already you need to set different flags on your intent: 要将应用程序置于前台(如果它已在运行),您需要在意图上设置不同的标记:

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

For running a specific method you could just pass extra information along with the intent and interpret it in your application to decide which method to run. 要运行特定方法,您可以只传递额外信息和意图,并在应用程序中解释它以决定运行哪种方法。

The recommendation to use FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP only partially solves the problem. 使用FLAG_ACTIVITY_CLEAR_TOP和FLAG_ACTIVITY_SINGLE_TOP的建议仅部分解决了问题。 The activity in the Android manifest should also have these settings applied so that launching the activity from the home screen has the same behavior. Android清单中的活动也应该应用这些设置,以便从主屏幕启动活动具有相同的行为。 Without these properties multiple instances of the activity can be launched. 如果没有这些属性,可以启动多个活动实例。

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

I've discovered that if you use Intent contentIntent = new Intent(this, ABC.class); 我发现如果你使用Intent contentIntent = new Intent(this, ABC.class); this calls onCreate(); 这调用onCreate(); regardless of the flags set. 无论标志设置如何。

Use Intent contentIntent = getIntent(); 使用Intent contentIntent = getIntent(); to skip onCreate(); 跳过onCreate(); and that moves to onStart(); 并转移到onStart();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM