tags:

views:

59

answers:

1

I tried using this code to start multiple Activities from a parent activity:

for (int i=0; i<NUM_ACTIVITIES; i++) 
{
    Intent intent = new Intent(this, MyActivity.class);
    startActivity(intent);
}

However, according to my log in MyActivity.onCreate(), only 1 Activity was actually created. Is this behavior expected? If so, what's the proper way to launch multiple Activities?

+1  A: 

You can't have multiple activities on top at the same time. Are you trying to have them run in order, one after the other?

One way to accomplish this is to start each activity for result:

Intent intent = new Intent(this, MyActivity.class);
startActivityForResult(intent, 0);

Where you use the request code to track when activity is running. Then, in onActivityResult you can start the next one:

protected void  onActivityResult  (int requestCode, int resultCode, Intent  data) {
  if (requestCode < NUM_ACTIVITIES) {
    Intent intent = new Intent(this, MyActivity.class);
    startActivityForResult(intent, requestCode + 1);
  }
}

Edit: If you want to have some of the activities immediatly in the background, you can chain them together by calling startActivity in each Activity's onCreate. If you start a new Activity in onCreate before creating any views, the activity will never be visible.

protected void  onCreate  (Bundle savedInstanceState) {
  int numLeft = getIntent().getIntExtra("numLeft");
  if (numLeft > 0) {
    Intent intent = new Intent(this, MyActivity.class);
    intent.putExtra("numLeft", numLeft - 1);
    startActivity(intent);
  }
}

This should accomplish the stack that you wanted..

Mayra
What is the reason why multiple instance of an Activity can't be on top at the same time? I am not familiar with this limitation/restriction of Android...
zer0stimulus
You might want to read through the documentation on the activity lifecycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle There is a stack of active Activities, but only the top one is visible (except for in the case of dialogs, but then still only one is active). I wouldn't consider it a limitation...maybe you can explain what behavior you were trying to accomplish by starting multiple activities at once?
Mayra
this is more of an experiment to check my understanding of Activities. I thought a new instance of an Activity is started by default via `startActivity()`, and if I fire 3 intents, 3 new Activities objects will be created- 2 in background and 1 in foreground.
zer0stimulus
Ah ok. I'm just guessing, but I'd imagine the problem is that once you call startActivity, the new activity now has control and your old activity is stopped or paused, so more calls to startActivity in the no-longer-on-top activity fail. Since its open source, you could step through the calls in the debugger and see exactly what is happening. See my edit for an additional way to accomplish this.
Mayra