一个简洁的Activity生命周期说明图,类似阶梯金字塔。这张图显示了Activity的各个状态到达onResume状态的回调函数(callback)。由于Activity的复杂性,我们并不需要实现生命周期里所包含的所有的方法,重要是理解每个方法并实现它,达到用户的期望。
实现生命周期里的方法能保证(1)用户在使用你的app的时候接到一个电话或者转到其他app,你的app不会崩溃。
(2)当用户不常使用的时候不会消耗珍贵的系统资源。
(3)当用户离开app再返回时不会丢失离开时的进度。
(4)当屏幕旋转时不会丢失当时的进度。除了以下三种状态,生命周期里的其他状态都是不稳定的(不长期存在,只是到达稳定状态的过度)。(1)onResume( )这个状态下,Activity处于前台,用户可以与之交互。
(2)onPause( )这个状态下,activity被另一个activity部分遮住。即另一个处于前台半透明的或没有占满全屏的activity。处于pause状态的activity不能收到用户的输入,不会执行任何代码。
(3)onStop( )这个状态下,activity被完全隐藏,用户看不到。activity的实例和成员变量都被保留,但不能执行任何代码。activity启动时,system调用onCreate( )之后快速调用onStart( )接着到达onResume( )。
以下为几种行为下的函数调用情况:
1、创建新的实例时:
这个说明图重点说明在创建实例时系统依次调用的三个主要回调函数onCreate( )、onStart( )、onResume( )。这三个函数依次调用后就到了onResume( )状态,此时用户就可以与 activity交互。
TextView mTextView; // Member variable for text view in the layout @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the user interface layout for this Activity // The layout file is defined in the project res/layout/main_activity.xml file setContentView(R.layout.main_activity); // Initialize member TextView so we can manipulate it later mTextView = (TextView) findViewById(R.id.text_message); // Make sure we're running on Honeycomb or higher to use ActionBar APIs if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // For the main activity, make sure the app icon in the action bar // does not behave as a button ActionBar actionBar = getActionBar(); actionBar.setHomeButtonEnabled(false); } }
2、销毁一个活动,onDestroy( )
系统在调用onDestroy( )之前会先调用onPause( )、onStop( ),除非当你的activity作为一个暂时的决策者(decision maker)去启动(launch)另一个activity,你可能会在onCreate( )中调用finish( )来销毁你的activity。
@Override public void onDestroy() { super.onDestroy(); // Always call the superclass // Stop method tracing that the activity started during onCreate() android.os.Debug.stopMethodTracing(); }
3、停止和恢复一个Activity,(Pausing and Resuming an Activity)
当一个半透明状态(semi-transparent)的activity模糊了你的activity,系统调用onPause( ),activity会在上图状态1等待,当处于onPause状态是用户返回activity系统调用onResume( )。例如相机:
@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; } }
当用户将activity从PauseState恢复时调用onResume( )。每当activity到前台时,或activity第一次创建时系统都会调用onResume( )。因此你需要实现onResume( )方法来初始化在onPause( )时释放掉的元素。
下面的一个例子是在onResume( )中对Pause相机释放掉的初始化:
@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 } }
4、停止和重新启动一个Activity(Stoping and Restarting an Activity)
当用户离开activity,系统调用onStop( ) 1来使activity停止,当activity在停止状态,用户返回,系统调用onRestart( )2,紧接着是onStart( )、onResume( ).无论何种情况系统停止一个activity,总是在调用onStop( )之前调用onPause( )。当activity接收到onStop( )方法,activity就不可见了并且释放所有当用户不使用activity时的资源。当 activity Stop时很可能会内存泄漏,因此最好use onStop( ) to perform larger,下面一个例子是onStop( )方法的实现,在存储器中保存草稿(saves the contents of a draft note to persistent storage)。
@Override protected void onStop() { super.onStop(); // Always call the superclass method first // Save the note's current draft, because the activity is stopping // and we want to be sure the current note progress isn't lost. ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText()); values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle()); getContentResolver().update( mUri, // The URI for the note to update. values, // The map of column names and new values to apply to them. null, // No SELECT criteria are used. null // No WHERE columns are used. ); }
当activity is stopped,Activity 对象会在内存中保存,当activity恢复时调用,不用重新初始化元素。系统还会记录每个View的当前状态,例如关闭前在EditText中输入的内容再次打开时会显示。
5、重新创建一个Activity
当系统停止一个activity,它调用onSaveInstanceState( ).如果activity destroyed,同样的实例再次创建的时候,系统会将在1定义的状态数据传递给2onCreate( )方法和3onRestoreInstanceState( )方法。当activity开始stop的时候,系统调用onSaveInstanceState( ),因此activity以键值对的形式收集信息。
static final String STATE_SCORE = "playerScore"; static final String STATE_LEVEL = "playerLevel"; ... @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current game state savedInstanceState.putInt(STATE_SCORE, mCurrentScore); savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel); // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); }