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).

Deepzz
  • 4,573
  • 1
  • 28
  • 52
Eugene
  • 59,186
  • 91
  • 226
  • 333
  • Look here for the application lifecycle : http://d.android.com/guide/topics/fundamentals.html – ykatchou Dec 29 '10 at 12:31
  • This stuff is easy. Try explaining this WITH Fragments, now **that's** android programming for ya! – SMBiggs Dec 28 '15 at 05:46
  • Answers below doesn't have actual code with explanation.[This](http://stackoverflow.com/a/14021717/1911652) is code that explains it with fragment. – Atul Apr 11 '16 at 04:59

12 Answers12

321

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().

Squonk
  • 48,735
  • 19
  • 103
  • 135
  • 1
    This implies that both `onCreate()` and `onRestart()` would share a lot of common code, right? – Dheeraj Vepakomma Apr 07 '12 at 06: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 07 '12 at 07: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 08 '12 at 02:10
  • To me, having to call same function multiple times during these lifecycle events is a sign to bad design. – Timuçin Nov 10 '13 at 10:58
  • 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 '13 at 13:17
  • Don't take me as a developer. I am generally speaking. It just comes to me that there must be even number of lifecycle functions because it is the natural behaviour of a cycle. – Timuçin Nov 10 '13 at 16:20
  • 14
    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 09 '15 at 19:14
  • Nice analogy! Nice to see that onDestroy() doesn't have a method called driveOffTheCliff() – Red M Jun 21 '21 at 17:11
164

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

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
Nilesh Pawar
  • 3,895
  • 3
  • 21
  • 19
  • 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. – Stephan Branczyk Dec 21 '13 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? – Dewey Vozel Apr 07 '15 at 17:56
  • @StephanBranczyk why do you use maybe...()? Why "maybe"? – Marian Paździoch Sep 18 '15 at 10:50
  • @DeweyVozel If your Activity gets covered by something else but not completely (it's still visible under that something but not in foreground) - then onPause -> OnResume is fired. I'd say http://developer.android.com/reference/android/app/Dialog.html is a good example but I didn't check. – Marian Paździoch Sep 18 '15 at 10:54
  • @MarianPaździoch, Do not rely on this old answer. Do not rely on my own comment either. The nuances of the Activity lifecycle have changed since then. – Stephan Branczyk Sep 18 '15 at 17:34
  • 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 '16 at 04: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). https://www.udacity.com/course/developing-android-apps--ud853 – Stephan Branczyk Feb 11 '16 at 10:48
  • @StephanBranczyk I watched Lesson 4A, Active and Visible Lifetimes. There the guy explained exactly that: When an activity is partly covered by a dialog, onPause() should be called. That just doesn't happen with my app. I open a list of menu items from the action bar and from there I open a dialog, all without triggering onPause().. Why is that? – Damnum Feb 11 '16 at 14:01
  • 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. – Stephan Branczyk Feb 11 '16 at 21:52
  • So what method is active on an app when I press the home button and I'm in my app overview? onPause or/and onStop? – AlexioVay Jun 19 '16 at 08:55
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.

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
19

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

Langusten Gustel
  • 10,917
  • 9
  • 46
  • 59
Jonas Alves
  • 1,306
  • 12
  • 17
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!

Martin Booka Weser
  • 3,192
  • 5
  • 28
  • 41
  • 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 06 '11 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? – Martin Booka Weser Jan 06 '11 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

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
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!

pjv
  • 10,658
  • 6
  • 43
  • 60
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.

aprofromindia
  • 1,111
  • 1
  • 13
  • 27
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.

Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
Abhi
  • 1,043
  • 12
  • 7
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)
hba
  • 7,406
  • 10
  • 63
  • 105
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().

Corneliu Dascălu
  • 3,900
  • 1
  • 28
  • 38
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.

Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
androidwifi
  • 1,009
  • 10
  • 8