2016-10-14 65 views
0

我知道如何使用startActivityForResult從其他活動獲得結果,但問題是我有3個活動A,B和C.主要活動是A,後退按鈕所有活動都應該返回那裏。從並非從當前活動開始的活動獲得額外價值

現在當我們從活動A打開活動B,然後從活動B打開活動C.當在活動C上按下後退按鈕時,如何將結果返回到活動A?

活動答:

@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    if (requestCode == 1) { 
     if(resultCode == Activity.RESULT_OK){ 
      int result=data.getIntExtra("result", 0); 
      SetNotification(result); 
     } 
    } 
} 

活動C:

//This works for activity B which is started directly from activity A 
@Override 
public void onBackPressed() { 
    Intent returnIntent = new Intent(); 
    returnIntent.putExtra("result", unreadCount); 
    setResult(Activity.RESULT_OK,returnIntent); 
    finish(); 
} 
+0

我個人將其存儲在一個靜態變量 – clavio

回答

1

「當活動C上的後退按鈕被按下時,我如何將結果返回到活動A?」

不要回去。往前走,年輕的螞蚱:P

Intent intent = new Intent(this, activityClass); 

// FLAG_ACTIVITY_NEW_TASK : If set, this activity will become the start of a new task on this history stack. 
// FLAG_ACTIVITY_CLEAR_TOP: If set, and the activity being launched is already running in the current task, 
// then instead of launching a new instance of that activity, all of the other activities on 
// top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent. 
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 

intent.putExtra("result", unreadCount); 

startActivity(intent); 
0

我會做這樣的:

@Override 
public void onBackPressed() { 
    Intent returnIntent = new Intent(C.this, A.class); 
    returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    returnIntent.putExtra("result", unreadCount); 
    startActivity(intent); 
} 

然後你就可以在一個的onCreate獲取您的附加功能(功能)。

希望它有幫助。

0

也許你可以使用onActivityResult()從活動B到呼叫重定向到活動A.事情是這樣的:

// Activity B 
@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

     if (requestCode == 1) { 
      if(resultCode == Activity.RESULT_OK){ 
       // Get data from activity C 
       int result = data.getIntExtra("result", 0); 

       // Create intent with data from activity C 
       Intent returnIntent = new Intent(); 
       returnIntent.putExtra("result", result); 

       // Set the response 
       setResult(Activity.RESULT_OK,returnIntent); 
       finish(); 
      } 
     } 
    } 
0

ActivityB可以將此結果傳遞給ActivityA當ActivityB的onActivityResult在ActivityC被按下後被調用時。所以ActivityB操作如下:

@覆蓋 保護無效onActivityResult(INT requestCode,INT resultCode爲,意圖數據){

if (requestCode == 1) { 
    if(resultCode == Activity.RESULT_OK){ 
     int result=data.getIntExtra("result", 0); 

     Intent returnIntent = new Intent(); 
     returnIntent.putExtra("result", result); 
     setResult(Activity.RESULT_OK,returnIntent); 
     finish(); 
    } 
} 

}