2011-12-28 98 views
0

編輯:請注意:我完全重新解釋了我的問題。Android:點擊通知時始終啓動頂部活動

我有應用具有兩個ActivitesActivityAMAIN。因此,應用程序啓動,屏幕上將出現A。用戶按下它上面的按鈕,屏幕上將出現新的ActivityB

因此,在我的「後退堆棧」中現在有2項活動:AB

現在我按下「Home」鍵,然後點擊我的應用程序的圖標啓動程序:Activity出現在屏幕(不是A)上,就因爲它是在我的任務頂。

現在的問題:我怎樣才能讓Intent以同樣打開我的任務目前頂部Activity

我需要它在Notification中使用:當用戶點擊我的Notification時,此任務的頂部Activity應該出現在屏幕上,而不是指定的一個。

我嘗試了很多Intent標誌,例如SINGLE_TOP和其他,但我仍然無法得到我需要的東西。

有誰知道解決方案?

回答

7

好,花好幾個小時了幾天後,我找到了解決辦法:

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

0

你可以使用android:launchMode =「singleInstance」。 這可能會工作。

+0

不,當然,我試過了,但它不工作,因爲我需要它的工作(看我的場景) – 2011-12-28 11:41:00

1

我用這個。

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); 

}