Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

android - Is onStop() always preceded by onPause()

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...