2014-11-25 42 views
1

我有一個包含通知的應用程序。我想在選擇通知後設置「返回」導航行爲。我有兩個活動:MainActivity和GoogleFormActivity。通知啓動GoogleFormActivity,我希望後退按鈕返回到MainActivity。我試圖this無濟於事。這裏是我的代碼:通知後的後退導航

的Manifest.xml:

<activity 
     android:name="com.ican.activities.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

<activity 
     android:name="com.ican.activities.GoogleFormActivity" 
     android:label="@string/title_activity_google_form" 
     android:parentActivityName="com.ican.activities.MainActivity" > 
     <!-- Parent activity meta-data to support 4.0 and lower --> 
     <meta-data 
      android:name="android.support.PARENT_ACTIVITY" 
      android:value="com.ican.activities.MainActivity" /> 
    </activity> 

下面是當選擇我的通知代碼:

Intent resultIntent = new Intent(this, GoogleFormActivity.class); 

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this). 
      addParentStack(GoogleFormActivity.class). 
      addNextIntent(resultIntent); 
    PendingIntent resultPendingIntent = 
      stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 
    mBuilder.setContentIntent(resultPendingIntent); 

    NotificationManager mNotificationManager = 
      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    // mId allows you to update the notification later on. 
    int mId = 1; 
    mNotificationManager.notify(mId, mBuilder.build()); 

至於我可以告訴大家,這看起來完全像Android文檔。但是當GoogleFormActivity啓動後,當我按回時,應用會導航到應用程序的主屏幕。我不明白髮生了什麼事。有任何想法嗎?我不得不道歉。這個昨天沒有工作的代碼現在可以工作。我發誓Android Studio上有一些東西。這是第二次或第三次發生這種事情。

回答

0

當您點擊back button它將關閉當前活動。這意味着它不會開展任何活動。只是關閉當前的活動。活動排列在stack (the back stack)中,按照每個活動打開的順序排列。如果用戶按下Back button,則當前活動從堆棧彈出並銷燬。如果堆棧包含該活動,則堆棧中的上一個活動恢復。當活動被銷燬時,系統不保留活動的狀態。所以,當你來自通知時,你只會打開一個活動。它不會回到主要活動,因爲它沒有打開。您必須使用Intent導航到特定活動。 docs

+0

我想我不明白你在說什麼。 「開始活動時保留導航」文章說我應該能夠返回到MainActivity。 – mhlandry 2014-11-25 04:35:05

+0

這些活動按照每個活動打開的順序排列在一個「堆棧(後退堆棧)」中。如果用戶按下「返回按鈕」,則當前活動從堆棧彈出並銷燬。如果堆棧包含該活動,則堆棧中的上一個活動恢復......請閱讀此內容,但仍不理解讓我知道。 – 2014-11-25 04:37:59

+0

我明白你在說什麼。但是當我看到「開始活動時保留導航」時,我看到:「來自Gmail應用程序的通知證明了這一點。當您單擊一封電子郵件的通知時,您會看到該消息本身。 Gmail轉到主屏幕,就像您從主屏幕輸入Gmail一樣,而不是從通知中輸入Gmail。「而且,我似乎應該能夠完成我想要的。 – mhlandry 2014-11-25 04:42:48

0
@Override 
     public void onBackPressed() { 
      // TODO Auto-generated method stub 
      super.onBackPressed(); 
      Intent intent=new Intent(this,MainActivity.class); 
      startActivity(intent); 
      finish(); 
     } 

在GoogleFormActivity添加此

0

嘗試這樣做,

getFragmentManager().popBackStack(); 
fm.beginTransaction().add(R.id.main, newFragment).addToBackStack("fragBack").commit();