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()
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…