2013-03-26 35 views
0

我想從「onActivityResult」函數中調用一個新的Intent,但結果並不是我所希望的。它要麼無休止地循環,要麼提前退出。從onActivityResult調用新的StartActivityForResult

在「main」活動中,我創建了一個bundle數組,然後爲每個bundle創建一個intent,等待當前活動返回「done」,然後用下一個bundle開始一個新活動。

問題是每次調用onActivityResult後都會重新啓動「main」活動,這意味着onStart會再次被調用,並且所有的bundle都將在無限循環中重新創建。避免這種情況的唯一方法似乎是添加「finish();」到onActivityResult函數的結尾,但是這隻會在onActivityResult調用一次後停止整個過程。

下面的代碼(有刪節):

public class mainActivity extends Activity { 

    ArrayList<Bundle> bundles; 
    int taskId = 0; 
    // A few other things here; nothing important to this question. 

    public void onCreate(savedInstanceState)) { 
     super.onCreate(savedInstanceState); 
     bundles = new ArrayList<Bundle>(); 
    } 

    public void onStart() { 
     // Here I perform a loop that creates a number of bundles 
     // and adds them to the "bundles" array (not shown). 

     // Start the first activity: 
     Intent firstIntent = new Intent(this, StuffDoer.class); 
     firstIntent.putExtras(bundles.get(0)); 
     startActivityForResult(firstIntent, taskId); 
     bundles.remove(0); 
    } 

    public void onActivityResult(int requestCode, int result, Intent data) { 
     super.onActivityResult(requestCode, result, data); 
     if (result == RESULT_OK) { 
      if (bundles.size() > 0) { 
       taskId += 1; 
       Intent intent = new Intent(this, StuffDoer.class); 
       intent.putExtras(bundles.get(0)); 
       startActivityForResult(intent, taskId); 
       bundles.remove(0); 
      } else { 
       Log.v(TAG, "No more to do, finishing"); 
       finish(); 
      } 
     } else { 
      Log.v(TAG, "Did not get the expected return code"); 
     } 
     // finish(); // If I uncomment this, it only performs this function 
        // once before quitting. Commented out, it loops forever 
        // (runs the onStart, adds more bundles, etc.). 
    } 
} 

什麼是做這種正確的方法是什麼?

+1

你是否正在改變這些活動的佈局方向......即在調用活動景觀中的接收活動中的肖像 – GoCrazy 2013-03-26 19:50:06

+0

@Vino,我不認爲改變活動方向也會破壞調用活動。natedc,你是否嘗試將迭代代碼移至'onCreate'? – Elad92 2013-03-26 19:56:25

+0

將捆綁創建循環移動到onCreate函數解決了它。 – natecornell 2013-03-26 22:21:28

回答

0

我不清楚你想要做什麼,但是如果你只需要在活動首次啓動時創建你的Bundles,那麼在onCreate()中執行。通常,您爲活動實現的回調函數是onCreate,onPause和onResume。在活動的正常生活中,它處於onResume和onPause之間的生命週期循環中。

但是,我很好奇。爲什麼每次都需要返回主要活動?聽起來好像您的主要活動「控制」了其他活動。通常,Android應用程序的更好模型是讓每個活動獨立工作,並在必要時切換到另一個活動。這實際上是一個沒有「主要」的「程序」,除了當用戶點擊啓動器中的應用程序圖標時開始的「等於第一」活動。

+0

我試圖從第一個序列化第二個活動的執行;基本上使用「主要」活動作爲調用/排序活動。我想我會用它來創建一捆捆,然後創建一個意圖。然後,我可以將所有不同迭代的處理留給「stuffDoer」活動。 – natecornell 2013-03-26 20:30:51

+0

將bundle創建循環移動到onCreate函數是我提出的問題的解決方案,但是您對我的技術的批評是現成的。我把活動稱爲只是簡單的類來實例化,運行然後銷燬。這是我的第一個Android應用程序,也是我第一個「真實世界」程序,所以我肯定會推動我的界限。謝謝您的幫助! – natecornell 2013-03-26 22:24:27

相關問題