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

17 java user-interface notifications android

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

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++;
}
Run Code Online (Sandbox Code Playgroud)

如果用户单击Notification,则调用onCreate()方法.但我想要调用我的应用程序中的特定方法,或者如果应用程序不在前台,则将其带回前台.

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

ste*_*ter 16

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

contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Run Code Online (Sandbox Code Playgroud)

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

  • 好的我找到了答案:调用Activity#onNewIntent(Intent intent). (3认同)

小智 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">
Run Code Online (Sandbox Code Playgroud)