190

I can't get the meaning of onStart() transition state. The onResume() method is always called after onStart(). Why can't it be the onResume() is invoked after onRestart() and onCreate() methods just excluding onStart()? What is its purpose?

Why can't we live without onStart(). I still consider it as redundant (probably because don't understand its meaning completely).

3
  • Look here for the application lifecycle : d.android.com/guide/topics/fundamentals.html
    – ykatchou
    Dec 29, 2010 at 12:31
  • This stuff is easy. Try explaining this WITH Fragments, now that's android programming for ya!
    – SMBiggs
    Dec 28, 2015 at 5:46
  • Answers below doesn't have actual code with explanation.This is code that explains it with fragment.
    – Atul
    Apr 11, 2016 at 4:59

12 Answers 12

320
+50

Why can't it be the onResume() is invoked after onRestart() and onCreate() methods just excluding onStart()? What is its purpose?

OK, as my first answer was pretty long I won't extend it further so let's try this...

public DriveToWorkActivity extends Activity
    implements onReachedGroceryStoreListener {
}

public GroceryStoreActivity extends Activity {}

PLEASE NOTE: I've deliberately left out the calls to things like super.onCreate(...) etc. This is pseudo-code so give me some artistic licence here. ;)

The methods for DriveToWorkActivity follow...

protected void onCreate(...) {
    openGarageDoor();
    unlockCarAndGetIn();
    closeCarDoorAndPutOnSeatBelt();
    putKeyInIgnition();
}

protected void onStart() {
    startEngine();
    changeRadioStation();
    switchOnLightsIfNeeded();
    switchOnWipersIfNeeded();
}

protected void onResume() {
    applyFootbrake();
    releaseHandbrake();
    putCarInGear();
    drive();
}

protected void onPause() {
    putCarInNeutral();
    applyHandbrake();
}

protected void onStop() {
    switchEveryThingOff();
    turnOffEngine();
    removeSeatBeltAndGetOutOfCar();
    lockCar();
}

protected void onDestroy() {
    enterOfficeBuilding();
}

protected void onReachedGroceryStore(...) {
    Intent i = new Intent(ACTION_GET_GROCERIES, ...,  this, GroceryStoreActivity.class);
}

protected void onRestart() {
    unlockCarAndGetIn();
    closeDoorAndPutOnSeatBelt();
    putKeyInIgnition();
}

OK, so it's another long one (sorry folks). But here's my explanation...

onResume() is when I start driving and onPause() is when I come to a temporary stop. So I drive then reach a red light so I pause...the light goes green and I resume. Another red light and I pause, then green so I resume. The onPause() -> onResume() -> onPause() -> onResume() loop is a tight one and occurs many times through my journey.

The loop from being stopped back through a restart (preparing to carry on my journey) to starting again is perhaps less common. In one case, I spot the Grocery Store and the GroceryStoreActivity is started (forcing my DriveToWorkActivity to the point of onStop()). When I return from the store, I go through onRestart() and onStart() then resume my journey.

I could put the code that's in onStart() into both onCreate() and onRestart() and not bother to override onStart() at all but the more that needs to be done between onCreate() -> onResume() and onRestart() -> onResume(), the more I'm duplicating things.

So, to requote once more...

Why can't it be the onResume() is invoked after onRestart() and onCreate() methods just excluding onStart()?

If you don't override onStart() then this is effectively what happens. Although the onStart() method of Activity will be called implicitly, the effect in your code is effectively onCreate() -> onResume() or onRestart() -> onResume().

8
  • 1
    This implies that both onCreate() and onRestart() would share a lot of common code, right? Apr 7, 2012 at 6:35
  • 1
    @Dheeraj: No not necessarily. This is pseudo code and meant to just illustrate how each stage of the Activity life-cycle might be used. The creation stage onCreate(...) may well do a great deal when it comes to instantiating instance members (UI elements etc) but a 'restart' shouldn't need to do that. In reality many Activities don't really need to implement more than onCreate(...), onResume() and onPause() the other methods are available for cases where you might need to do other things and the key is to understand where to put the code.
    – Squonk
    Apr 7, 2012 at 7:04
  • 1
    This is why I have come to hate the Android API compared to iOS and even WP7... Ive been making a game that runs on all three in C# and I have to say i'm rly disappointed with Google and Android. They seem to be lacking in the Language / API design department. I rly hope some other linux phone OS takes over, cuz I do vote for Open Source in general...
    – zezba9000
    Jul 8, 2012 at 2:10
  • 2
    @Tim : OK, come up with a better design. How would you deal with a scenario on a mobile phone when somebody is using an app (your app) and they suddenly get a phone call? The app designer doesn't explicitly call the Activity life-cycle methods - it's the Android OS which does it and it does it very efficiently (assuming the app developer knows what they're doing and also codes efficiently). If you do a lot of Android development you'll realise why things work the way they do - it's not 100% perfect but it's pretty good.
    – Squonk
    Nov 10, 2013 at 13:17
  • 13
    I think Nilesh's answer below is much clearer. The key difference between onStart and onResume is that of 'visibility' and 'user interaction'. This driving-a-car metaphor is confusing and not really helpful.
    – K J
    Apr 9, 2015 at 19:14
162

Short answer:

We can't live without onStart because that is the state when the activity becomes "visible" to the user, but the user cant "interact" with it yet may be cause it's overlapped with some other small dialog. This ability to interact with the user is the one that differentiates onStart and onResume. Think of it as a person behind a glass door. You can see the person but you can't interact (talk/listen/shake hands) with him. OnResume is like the door opener after which you can begin the interaction.

Additionally onRestart() is the least understood one. We can ask the question as to why not directly go to onStart() or onResume() after onStop() instead of onRestart(). It becomes easier to understand if we note that onRestart() is partially equivalent to onCreate() if the creation part is omitted. Basically both states lead to onStart() (i.e the Activity becomes visible). So both the states have to "prepare" the stuff to be displayed. OnCreate has the additional responsibility to "create" the stuff to be displayed

So their code structures might fit to something like:

onCreate()
{
     createNecessaryObjects();

     prepareObjectsForDisplay();
}


onRestart()
{
     prepareObjectsForDisplay();

}

The entire confusion is caused since Google chose non-intuitive names instead of something as follows:

onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change] 

The Activity Diagram might be interpreted as:

Android Activity Lifecycle

10
  • 5
    When I explain it to students, I use maybeOnInvisible() instead of onStop(). And use maybeOnDestroy() instead of onDestroy(). These names work well as explanations I find. Thought, I wouldn't want Google to actually change to these names. Dec 21, 2013 at 18:37
  • I like your suggested names, they help make some sense of this part of the ridiculous Android API. I still have a question in general about the lifecycle. In all of the diagrams it shows there's a path from onPause directly to onResume. I don't think I've ever seen that path actually followed in any cases. It always takes the path from onStop to onStart. What would trigger the other path? Apr 7, 2015 at 17:56
  • 1
    @StephanBranczyk could you explain what has changed? I tested this out and when a dialog or menu is opened in front of the activity (so the activity is partially covered) neither onPause() nor onResume() is fired. In fact, I couldn't reproduce any case where onResume() without onStart() is fired. This confuses me..
    – Damnum
    Feb 11, 2016 at 4:47
  • 1
    @Damnum, For the most recent explanation of the Activity lifecycle, I'd suggest you check out the intermediate Android Udacity course created by Google. It's free, assuming you click on the blue button to access its materials for free, and not the trial button (nor the nanodegree button). udacity.com/course/developing-android-apps--ud853 Feb 11, 2016 at 10:48
  • 1
    @Damnum, I'd suggest you ask that question in the udacity forum related to the video you watched. But basically, I think it depends on the dialog being used, whether it's a dialog activity, or a dialog only. Feb 11, 2016 at 21:52
31

onStart() called when the activity is becoming visible to the user. onResume() called when the activity will start interacting with the user. You may want to do different things in this cases.

See this link for reference.

18

onResume() is called:

  1. after onStart()
  2. when the Activity comes to the foreground.

From http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle: alt text

10

The book "Hello, Android, Introducing Google's Mobile Development Platform" gives a nice explanation of the life cycle of android apps. Luckily they have the particular chapter online as an excerpt. See the graphic on page 39 in http://media.pragprog.com/titles/eband3/concepts.pdf

By the way, this book is highly recommendable for android beginners!

2
  • 2
    Nice image and good book, but still it doesn't give an answer why do we really need onStart() method and what special things we can do in it we can't do in onResume().
    – Eugene
    Jan 6, 2011 at 18:02
  • 8
    onStart() is NOT called, if the app was paused. Your app is "paused" if another app gains the focus but does NOT obscure your app completely. So you may do different things in the "paused" state than you would do in "Stopped" state. Thus, you may do different things if your app is just "resumed" from paused state than you would do if your app is "started" from stopped state or from complete start. Does that help? Jan 6, 2011 at 19:09
9

onStart()

  1. Called after onCreate(Bundle) or after onRestart() followed by onResume().
  2. you can register a BroadcastReceiver in onStart() to monitor changes that impact your UI, You have to unregister it in onStop()
  3. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

onResume()

  1. Called after onRestoreInstanceState(Bundle), onRestart(), or onPause()
  2. Begin animations, open exclusive-access devices (such as the camera)

onStart() normally dispatch work to a background thread, whose return values are:

  • START_STICKY to automatically restart if killed, to keep it active.

  • START_REDELIVER_INTENT for auto restart and retry if the service was killed before stopSelf().

onResume() is called by the OS after the device goes to sleep or after an Alert or other partial-screen child activity leaves a portion of the previous window visible so a method is need to re-initialize fields (within a try structure with a catch of exceptions). Such a situation does not cause onStop() to be invoked when the child closes.

onResume() is called without onStart() when the activity resumes from the background

For More details you can visits Android_activity_lifecycle_gotcha And Activity Lifecycle

1
  • actually I gets onstop when my app goes to background
    – deadfish
    May 20, 2017 at 18:14
7

A particularly feisty example is when you decide to show a managed Dialog from an Activity using showDialog(). If the user rotates the screen while the dialog is still open (we call this a "configuration change"), then the main Activity will go through all the ending lifecycle calls up untill onDestroy(), will be recreated, and go back up through the lifecycles. What you might not expect however, is that onCreateDialog() and onPrepareDialog() (the methods that are called when you do showDialog() and now again automatically to recreate the dialog - automatically since it is a managed dialog) are called between onStart() and onResume(). The pointe here is that the dialog does not cover the full screen and therefore leaves part of the main activity visible. It's a detail but it does matter!

0
7

Hopefully a simple explanation : -

onStart() -> called when the activity becomes visible, but might not be in the foreground (e.g. an AlertFragment is on top or any other possible use case).

onResume() -> called when the activity is in the foreground, or the user can interact with the Activity.

0
4

onStart() means Activity entered into visible state and layout is created but can't interact with this activity layout.

Resume() means now you can do interaction with activity layout.

3

Not sure if this counts as an answer - but here is YouTube Video From Google's Course (Developing Android Apps with Kotlin) that explains the difference.

  • On Start is called when the activity becomes visible
  • On Pause is called when the activity loses focus (like a dialog pops up)
  • On Resume is called when the activity gains focus (like when a dialog disappears)
1

Note that there are things that happen between the calls to onStart() and onResume(). Namely, onNewIntent(), which I've painfully found out.

If you are using the SINGLE_TOP flag, and you send some data to your activity, using intent extras, you will be able to access it only in onNewIntent(), which is called after onStart() and before onResume(). So usually, you will take the new (maybe only modified) data from the extras and set it to some class members, or use setIntent() to set the new intent as the original activity intent and process the data in onResume().

0

Reference to http://developer.android.com/training/basics/activity-lifecycle/starting.html

onResume() Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it. Always followed by onPause().

onPause() Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns. Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.