Carnal Carnal - 1 year ago 102
Android Question

Android - Activity onStart

I have this MainActivity which launches when I start the application, and what I know that only then the onCreate will be called, and after that onStart will be called.
Is there anyway to know if onStart has been called, without onCreate being called first?
I mean if I press back button from the second activity, then only onStart will be called, how can figure this out? Or maybe there's a way of knowing the position of one activity in the the whole activity stack?

Thanks in advance!


I have this MainActivity, it will either send you to LoginActivity, or if you are already logged, it will send you to ProfileActivity. When I press back in ProfileActivity i want to be able to go to home, and not the MainActivity. I know how to override back button to act like home button, but problem is that I have other activities, and if I press back on ProfileActivity I only want it to act like home if no other activities are in onPause.


public void onStart(){
if(counter == -1){

public void onPause(){

I'll give my creds to ArcDare for giving me the idea of implementing counters, thanks!

Answer Source

Your question is related to activity lifecycle.

  1. onCreate() gets called only when the activity starts either your app does it or after the process is being killed.

  2. The activity goes in Pause state when another activity comes over it. In this case when user pressed back button then onResume() get's called.

  3. The activity goes in Stop state when activity is not in foreground.

The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.

In this case the acitivity goes in onRestart() -> onStart().

For detailed description over activity lifecycle refer this doc.

To your specific problem as you mentioned in Comments above:

Once you are done with MainActivity/LoginActivity finish() it, then they will not be in your activity stack and now if there is no activity in your stack then on pressing back button it will go to home screen or it there are then it will navigate to that screen. Now you don't need to override back button.