Search code examples
androidandroid-activityandroid-lifecycleactivity-lifecycle

basics of android activity life cycle functions


I was testing out this code which shows which state an activity is in

public class Activity101Activity extends Activity {
    String tag  =  "Lifecycle";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
        // setContentView(R.layout.main);
        setContentView(R.layout.activity_activity101);
        Log.d(tag , "In the onCreate() event");
    }
    public void onStart()
    {
        super.onStart();
        Log.d(tag , "In the onStart() event");
    }

    public void onRestart()
    {
         super.onRestart();
        Log.d(tag , "In the onRestart() event");
    }

    public void onResume()
    {
         super.onResume();
        Log.d(tag , "In the onResume() event");
    }

    public void onPause()
    {
         super.onPause();
        Log.d(tag , "In the onPause() event");
    }

    public void onStop()
    {
         super.onStop();
        Log.d(tag , "In the onStop() event" );
    }

    public void onDestroy()
    {
         super.onDestroy();
        Log.d(tag , "In the onDestroy() event");
    }
}  

so I see that onDestroy() is only called when we press the back button while the activity is on screen, and is never called otherwise. So it should be running in the back ground if I press the home button while the activity is running. However, if I go to Settings -> Apps -> Running I can't see it on the list. So does that mean it is running in the background or not?

Again, Again, this code shows that onPause() is always followed by onStop() and onStart() is always followed by onResume(). So why are they defined as different functions in the Android environment and not combined?


Solution

  • Once the activity goes in backstack, it is in suspended mode. So you dont see it in running app list. Once you relaunch such suspended application, it comes to foreground from backstack and starts to run. It is kept in backstack to preserve its state and resume from the place where it got stopped before going in background.

    To understand why, onStart is needed before onResume follow the link below. It will clear all your doubts very clearly:

    Difference between onStart() and onResume()