Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is onStop() always preceded by onPause()

Tags:

android

I have read that a call to onStop() is always preceded by a call to onPause() no matter what the scenario is. Reference: Figure 1 on http://developer.android.com/training/basics/activity-lifecycle/stopping.html

We know that an activity is paused when it does not have user's focus but it still partially visible, and it is stopped when it is not visible at all.

Now in the scenario when a user is in an activity and from the recent apps window selects and enters another app, the activity will enter from resumed/running to stopped state. No intermediate paused state.

Isn't it?

What is the good reason for always having onPause() before onStop(). We can do in onStop() what is done in onPause(). Why do we always need onPause() before onStop()?

like image 458
user2882662 Avatar asked Nov 05 '13 15:11

user2882662


1 Answers

onPause() is always called. This is guaranteed. If you need to save any state in your activity you need to save it in onPause(). onStop() may be called after onPause(), or it may not. Depends on the situation.

There are a lot of lifecycle methods. You don't need to override all of them. You only need to override the ones where you need (or want) to customize the behaviour for your activity. There are a lot of lifecycle methods because different applications have different requirements. The lifecycle of an Activity is well-documented and well-behaved. This allows programmers to put the code exactly where it is needed, based on the particular requirements of the application.

You have asked

What is the good reason for always having onPause() before onStop(). We can do in onStop() what is done in onPause().

onPause() is always called on your Activity if it is in the foreground when Android wants to do something else. It may start another Activity which may result in your Activity's onStop() getting called. It may just call onResume() on your activity. It may just kill your process without calling any more of your lifecycle methods.

Since onStop() is not guaranteed to be called, you can't always do in onStop() what is done in onPause().

In most Activities, you will find that you will need to put code in onResume() and onPause(). You usually don't have to do anything in onStop(), onStart() or onRestart().

like image 123
David Wasser Avatar answered Nov 07 '22 05:11

David Wasser