Android:点击通知时始终启动顶部活动

问题描述:

编辑:请注意:我完全重新解释了我的问题。Android:点击通知时始终启动顶部活动

我有应用具有两个ActivitesActivityAMAIN。因此,应用程序启动,屏幕上将出现A。用户按下它上面的按钮,屏幕上将出现新的ActivityB

因此,在我的“后退堆栈”中现在有2项活动:AB

现在我按下“Home”键,然后点击我的应用程序的图标启动程序:Activity出现在屏幕(不是A)上,就因为它是在我的任务顶。

现在的问题:我怎样才能让Intent以同样打开我的任务目前顶部Activity

我需要它在Notification中使用:当用户点击我的Notification时,此任务的顶部Activity应该出现在屏幕上,而不是指定的一个。

我尝试了很多Intent标志,例如SINGLE_TOP和其他,但我仍然无法得到我需要的东西。

有谁知道解决方案?

好,花好几个小时了几天后,我找到了解决办法:

Intent notificationIntent = new Intent(this, MainActivity.class); 
notificationIntent.setAction(Intent.ACTION_MAIN); 
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER); 
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 

这是该发射器启动应用程序的方式,它适用于通知意向环境也不错。

+0

工程就像一个魅力! – Defuera 2014-12-29 10:08:51

你可以使用android:launchMode =“singleInstance”。 这可能会工作。

+0

不,当然,我试过了,但它不工作,因为我需要它的工作(看我的场景) – 2011-12-28 11:41:00

我用这个。

private void notifyUser(Context context) { 

    notificationManager = (NotificationManager) context 
      .getSystemService(Context.NOTIFICATION_SERVICE); 
    CharSequence text = "Test Notification"; 
    Notification notification = new Notification(R.drawable.icon, text, 
      System.currentTimeMillis()); 

    Intent resultIntent = new Intent(context, StartActivity.class); 
    resultIntent.setAction(Intent.ACTION_MAIN); 
    resultIntent.addCategory(Intent.CATEGORY_LAUNCHER); 
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
      | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); 
    // Adds the back stack for the Intent (but not the Intent itself) 
    stackBuilder.addParentStack(GeneralSettingsActivity.class); 
    // Adds the Intent that starts the Activity to the top of the stack 
    stackBuilder.addNextIntent(resultIntent); 
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, 
      PendingIntent.FLAG_UPDATE_CURRENT); 

    notification.flags = Notification.FLAG_AUTO_CANCEL; 
    notification.setLatestEventInfo(context, "Title", text, 
      resultPendingIntent); 
    notificationManager.notify(AUTOSYNC_COMPLETED_NOTIFICATION, 
      notification); 

}