2013-03-26 81 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

相关问题