Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Possible to start multiple instances of an Activity in same task?

Tags:

android

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?

like image 815
zer0stimulus Avatar asked Jul 26 '10 20:07

zer0stimulus


People also ask

Can I run two instances of Android studio?

Android Studio Project SiteIt's possible to have multiple versions of Android Studio installed simultaneously.

Can we create instance of activity android?

Activity instances are always created by the Android system. This is because a lot of initializations have to be done for the activity to work. To create a new activity you call startActivity with an Intent describing the activity to start.

How do I start the same activity again on android?

If you just want to reload the activity, for whatever reason, you can use this. recreate(); where this is the Activity. This is never a good practice. Instead you should startActivity() for the same activity and call finish() in the current one.

Can fragments be used in multiple activities?

You can use multiple instances of the same fragment class within the same activity, in multiple activities, or even as a child of another fragment.


1 Answers

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..

like image 127
Cheryl Simon Avatar answered Sep 19 '22 17:09

Cheryl Simon