Training—Managing the Activity Lifecycle
阅读:https://developer.android.com/training/basics/activity-lifecycle/index.html
这是ACtivity的状态以及各个方法的执行步骤,我们没有必要继承所有的方法,但是,有几个原则必须遵守,那就是:
- Does not crash if the user receives a phone call or switches to another app while using your app.
- Does not consume valuable system resources when the user is not actively using it.
- Does not lose the user's progress if they leave your app and return to it at a later time.
- Does not crash or lose the user's progress when the screen rotates between landscape and portrait orientation.
1、当用户来电或者跳转到其他APP的时候不会崩溃;
2、当程序处于后台的时候,释放宝贵的资源;
3、如果用户最后还需要回来操作你的APP,不要让APP进程被结束。
4、要考虑到用户旋转屏幕的情况。
- Resumed
- In this state, the activity is in the foreground and the user can interact with it. (Also sometimes referred to as the "running" state.)
- Paused
- In this state, the activity is partially obscured by another activity—the other activity that's in the foreground is semi-transparent or doesn't cover the entire screen. The paused activity does not receive user input and cannot execute any code.
- Stopped
- In this state, the activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code.
The other states (Created and Started) are transient and the system quickly moves from them to the next state by calling the next lifecycle callback method. That is, after the system calls
onCreate()
, it quickly callsonStart()
, which is quickly followed byonResume()
.That's it for the basic activity lifecycle. Now you'll start learning about some of the specific lifecycle behaviors.
If either the
MAIN
action orLAUNCHER
category are not declared for one of your activities, then your app icon will not appear in the Home screen's list of apps.
While the activity's first lifecycle callback is
onCreate()
, its very last callback isonDestroy()
. The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory.Most apps don't need to implement this method because local class references are destroyed with the activity and your activity should perform most cleanup during
onPause()
andonStop()
. However, if your activity includes background threads that you created duringonCreate()
or other long-running resources that could potentially leak memory if not properly closed, you should kill them duringonDestroy()
.
一般来说,onDestroy不用实现,但是如果当前Activity启动的时候你启用了一些线程还有一些资源,那么你应该在onDestroy结束掉他们。
Note: The system calls
onDestroy()
after it has already calledonPause()
andonStop()
in all situations except one: when you callfinish()
from within theonCreate()
method. In some cases, such as when your activity operates as a temporary decision maker to launch another activity, you might callfinish()
from withinonCreate()
to destroy the activity. In this case, the system immediately callsonDestroy()
without calling any of the other lifecycle methods.
onDestroy()一般只在onPause() and onStop()之后启用,但是如果你在onCreate启用finish(),也会导致onDestroy被调用。
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 theonPause()
callback to:
- Stop animations or other ongoing actions that could consume CPU.
- 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.
应该在onPause()实现:
1、停止动画;
2、提交尚未保存的变化;
3、释放系统资源,例如传感器等等其他一些会影响到电量但用户暂时不需要运行的资源。
@Override public void onPause() { super.onPause(); // Always call the superclass method first // Release the Camera because we don't need it when paused // and other activities might need to use it. if (mCamera != null) { mCamera.release() mCamera = null; } }
例如上面的释放摄像头资源。
Generally, you should not use
onPause()
to store user changes (such as personal information entered into a form) to permanent storage. The only time you should persist user changes to permanent storage withinonPause()
is when you're certain users expect the changes to be auto-saved (such as when drafting an email). However, you should avoid performing CPU-intensive work duringonPause()
, such as writing to a database, because it can slow the visible transition to the next activity (you should instead perform heavy-load shutdown operations duringonStop()
).
但是,这里又有一些问题所在:你不应该把用户的数据保存在永久的storage上面,除非用户真的需要这么做。因为我们需要避免在onPause()避免CPU的大量计算,而存储到永久的storage就需要大量CPU资源,onPause的大量运算会拖慢将要显示的Activity的速度。
onPause的时候,Activity资源还是存在于内存内的,因此当你回到当前Activity的时候你不需要再次初始化那些组件。
@Override public void onResume() { super.onResume(); // Always call the superclass method first // Get the Camera instance as the activity achieves full user focus if (mCamera == null) { initializeCamera(); // Local method to handle camera init } }
Although the
onPause()
method is called beforeonStop()
, you should useonStop()
to perform larger, more CPU intensive shut-down operations, such as writing information to a database.
在onStop(),我们可以进行需要大量CPU运算的操作了,例如数据库的读写。
当系统recreate ACtivity的时候,state data defined at (1) 会被送到 onCreate()
method (2) 还有 onRestoreInstanceState()
method (3).
默认的 onSaveInstanceState()实现会自动保存 EditText 的值,还有 position of a ListView.
记得重写 onSaveInstanceState()的时候一定要调用父类的 onSaveInstanceState()。
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Always call the superclass first // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) { // Restore value of members from saved state mCurrentScore = savedInstanceState.getInt(STATE_SCORE); mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL); } else { // Probably initialize members with default values for a new instance } ... }
因为savedInstanceState会被送到onCreate里,所以一般要检测一下savedInstanceState是否为NULL。
尽管savedInstanceState会作为onCreate的参数,但是回复数据最好的地方,是onRestoreInstanceState(),只有当Activity有数据需要恢复时,才会调用onRestoreInstanceState(),因此你也不需要检测savedInstanceState是否为空。