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

时间:2010-07-31 13:00:43

标签: java android user-interface notifications

在我的应用程序中,如果发生特殊情况,我会通知用户:

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

如果用户点击Notification,则会调用onCreate()方法。但是我希望调用我的应用程序中的特定方法,或者如果应用程序不在前台,它会被带回到前台。

我知道有很多教程可以解释如何处理通知,但我完全不理解它们,并且无法实现我想要的东西。

3 个答案:

答案 0 :(得分:15)

如果您的应用程序已经运行,请将其置于前台,您需要在意图上设置不同的标记:

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

对于运行特定方法,您可以只传递额外信息和意图,并在应用程序中解释它以决定运行哪种方法。

答案 1 :(得分:6)

使用FLAG_ACTIVITY_CLEAR_TOP和FLAG_ACTIVITY_SINGLE_TOP的建议仅部分解决了问题。 Android清单中的活动也应该应用这些设置,以便从主屏幕启动活动具有相同的行为。如果没有这些属性,可以启动多个活动实例。

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

答案 2 :(得分:0)

我发现如果您使用Intent contentIntent = new Intent(this, ABC.class);,则无论设置了哪个标记,都会调用onCreate();

使用Intent contentIntent = getIntent();跳过onCreate();,然后移至onStart();