19

我正在開發一個應用程序,向用戶顯示通知。通知的目標是讓用戶在用戶處於其他活動時輕鬆返回活動。我在我的應用程序中使用此代碼來創建並顯示通知。意圖恢復以前暫停的活動(從通知中調用)

    notification = new Notification(R.drawable.icon, 
          "Notify", 
          System.currentTimeMillis()); 
        notification.setLatestEventInfo(this, "App name", 
          "App message", 
          PendingIntent.getActivity(
            this, 0, 
            new Intent(this, Main.class), 
            PendingIntent.FLAG_CANCEL_CURRENT)); 
        notification.flags |= Notification.FLAG_ONGOING_EVENT; 
        nManager.notify(0, notification); 

但是,當用戶點擊通知時,會啓動同一活動的新實例,而不是用戶之前使用的實例。

我認爲這與PendingIntent有關,但我找不到如何使Intent恢復以前暫停的活動實例,而不是創建新的實例。

謝謝。

+1

你找到一個解決這個問題?我發現的是一種解決方法:所有活動都擴展一個基本活動來存儲活動活動的數量(onCreate爲+1,onDestroy爲-1),並且通知開始一個假活動,該活動在新任務上運行,正在運行的活動的數量,如果它大於0,它就會自行關閉,如果它是== 0,它會啓動第一個活動。 – 2013-01-12 19:22:24

回答

21

我發現瞭如何做到這一點。我添加以下代碼:

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

現在我的代碼如下所示:

notification = new Notification(R.drawable.icon, 
      "Notify", System.currentTimeMillis()); 
    notification.setLatestEventInfo(this, "App name", 
      "App message", PendingIntent.getActivity(this, 
        0, new Intent(this, Main.class) 
          .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP 
            | Intent.FLAG_ACTIVITY_SINGLE_TOP), 
        PendingIntent.FLAG_CANCEL_CURRENT)); 
    notification.flags |= Notification.FLAG_ONGOING_EVENT; 
+0

Jimix,我試着用你的代碼,但沒有在我的情況下工作,這打開MainActivity而不是最後一個焦點。可能我的錯誤在於清單中,你如何確定主要活動? – Giuseppe 2012-05-14 11:45:24

+0

這些代碼應該可以工作。檢查同一個任務堆棧中的其他活動。他們可能涉及任務訂單。 – Kislingk 2014-02-13 17:04:55

6

這有助於我android:launchMode="singleInstance"

<activity 
     android:name="com.mosis.automatskidnevnik.MainActivity" 
     android:launchMode="singleInstance" 
     android:label="@string/app_name" > 
     ... 
0

我通過設置

android:launchMode="singleTask" 
解決同樣的問題
0

A部分來自@Jimix的正確答案我會將PendingIntentrequestCode從0更改爲非零的值,如另一個answer所評論的值。另一方面,在以前的Android版本中有一個known bug,讓我花了幾個小時。提出有解決方案工作得很好,我取消PendingIntent之前發送的通知:

if (Build.VERSION.SDK_INT == 19) { 
    getNotificationPendingIntent().cancel(); 
}