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?
Android Studio Project SiteIt's possible to have multiple versions of Android Studio installed simultaneously.
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.
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.
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.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With