天天看点

关于 onPause 和 onStop 的那些事

onPause 和 onStop 是 Android 管理 Activity 的两个生命周期,我们平时可能对这两个生命周期的关注不是很大,大部分都是在 onCreate 这个生命周。从 Android 的官方文档,我们可以发现,在我们的实际开发中,onPause 和 onStop 主要用来释放资源,但是他们也有一些区别,我们线看看官方文档的说命:

When the system calls

onPause()

for your activity, it technically means your activity is still partially visible, but most often is an indication that the user is leaving the activity and it will soon enter the Stopped state. You should usually use the

onPause()

callback to:
  • Check if the activity is visible; if it is not, stop animations or other ongoing actions that could consume CPU. Remember, beginning with Android 7.0, a paused app might be running in multi-window mode. In this case, you would not want to stop animations or video playback.
  • Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).
  • Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.
Although the

onPause()

method is called before

onStop()

, you should use

onStop()

to perform larger, more CPU intensive shut-down operations, such as writing information to a database.

从以上的说明,我们可以看出,onPause 和 onStop 都有回收资源和保存数据的角色,但是 onPause 主要执行一些轻量级的操作,而 onStop 执行一些稍微耗时的操作。同时很多人可能会疑问 Android 开发中 onStart 和 onResume, onPause 和 onStop可以二取其一,其实不然,出现这两个,我个人观点是出现这两对操作,其中的一个角色是提高系统流畅。

我们都知道启动 Activity 的流程是 onCreate -> onStart -> onResume,退出前台的过程是 onPause -> onStop, 其中的一个问题时,当一个Activity A启动另一个 Activity B时, B的 onCreate 是在A 执行onPause 还是 onStop之后执行,这也就导致 onPause 和 onStop 的一些差别。

启动顺序

从这里我们可以明显看出有两种假设,一种是 B 的 onCreate 在 onPause之后执行,另一种是在 onStop 之后执行。我们先讨论把 onPause 和 onStop 合二为一这种其中,假设此时只存在 onPause, 为了更突出这其中的差距,先假设我们在onPause 执行一个耗时操作,假定其为 3s,则此时我们启动 B 时,则需等待 3s 才能进入B,这会严重降低用户体验。而如果存在两个操作,我们可以在onPause 执行轻量操作,然后在 onStop 执行耗时操作(好像已经假定某种假设了,尴尬)。

如果是第一种假设,则我们可以马上进入 B, 而如果是第二种假设,此时的操作和把 onPause 和 onStop 合二为一相差无几。下面我们用实际代码来验证这两种假设。

我们有两个 Activity,分别是 MainActivity 和 SecondActivity,同时在他们每个生命周期打印当前的Activity名字和生命周期名字,我们通过 MainActivity 中的按钮来启动 SecondActivity.

启动 MainActivity 的顺序和我们大家所想一样没什么异常, 按照 onCreate -> onStart -> onResume

关于 onPause 和 onStop 的那些事

当我们启动SecondActivity 时, 此时的运行过程如下:

关于 onPause 和 onStop 的那些事

从这里我们可以清楚地发现 SecondActivity 的 onCreate 是在 onPause 之后执行,从而第一种假设正确,同时和官方文档的建议不谋而合。下面我们用代码在MainActivity 的 onPause 中让主线程睡眠3秒,