我想從「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.).
}
}
什麼是做這種正確的方法是什麼?
你是否正在改變這些活動的佈局方向......即在調用活動景觀中的接收活動中的肖像 – GoCrazy 2013-03-26 19:50:06
@Vino,我不認爲改變活動方向也會破壞調用活動。natedc,你是否嘗試將迭代代碼移至'onCreate'? – Elad92 2013-03-26 19:56:25
將捆綁創建循環移動到onCreate函數解決了它。 – natecornell 2013-03-26 22:21:28