Search code examples
androidandroid-activitylifecycleandroid-intent

startNewActivity many times lifecycle miss understanding


in oncreate of activity A

while(i<5){
startActivity(new Intent(this, ActivityB.class));
Log.v(tag,"activity A");
}

in activity B inside oncreate

Log.v(tag,"activity B");
finish();

and then in the console I see something like this

activity A
activity A
activity A
activity A
activity A
activity B
activity B
activity B
activity B
activity B

What should I change to have situation where the output is like this

activity A
activity B
activity A
activity B
activity A
activity B

I mean for every startActivity method I want new activity to actually to be started. Cause the activity B actually lives for a fraction of moment it is started and than finished. My problem is in the understanding the activity lifecycle. I expected that when I call srartActivity the activity to be started indeed, but it doesn't happens.

Edit1: ok I pasted just a small snippet of my code. and the problem is not in the while loop, in my real project is wrote correctly with initialization of the i variable like int i-0; and incrementing inside the loop like i++; . . . As you can see the output from the app is good, everything is get called in a sertian number of times and so on, but the problem is the order of calling. it is like startActivity doesn't start the activity after the call of the srartActivity, instead every thing is started after oncreate of activityA is finished.


Solution

  • This is not just about activity lifecycle, but also about the message processing in the main thread (=UI thread) of your app. startActivity returns immediately after sending the intent, so the while loop fires 5 intents to start Activity B within a very short time before returning control to the thread's message loop. Only after returning from the current method call, your applications main thread can start processing the previously generated messages that will result in creating the 5 instances of Acitvity 5, once again one after the other.

    If you want Activity A to hold off until Activity B has finished, you can call startActivityForResult - once!. Then, in Activity B, call finish( int) to return a result to Activity A. Override onActivityResult in Activity A to get the result code and from here you can again start Acitity B if needed.

    See also Starting Activities and Getting Results