标签:
当我们在app的不同页面间穿梭翱翔的时候,app中的Activity也在他们各自的生命周期中转换着不同的状态。当用户执行进入或者是离开某个Activity的操作时,Android系统会调用一系列生命周期的回调函数进行处理,而我们也可以重写这些回调函数,让Activity在不同的状态下执行我们想要的操作。
下图展示了一个Activity的生命周期以及回调方法。这张图看起来就像是一个梯形金字塔,每一步都对应着Activity的一种生命状态。
在这些状态中,只有如下三种状态是静态的,即可持续一段时间的,其他状态都是瞬态的:
Resumed:在这个状态下,Activity处于前台,用户可以与它交互(也可以称之为Running态,即运行态);
Paused:在这个状态下,Activity部分被其他Activity遮挡(其他处于前台的Activity是半透明的或者并没与充满整个屏幕),处在这个状态的Activity并不接收用户输入,也不执行任何代码;
Stopped:在这个状态下,Activity是完全被隐藏的,用户无法看到,这种状态可以认为Activity处于后台,这个Activity实例以及它的状态信息在这种状态下都被保存了下来,但是不能执行任何代码。
Created和Started这两个状态都是瞬间态的,系统会在到达这两个状态后很快就调用后面的生命周期回调方法,即系统在调用onCreate()之后紧跟着就会调用onStart(),然后再紧跟着调用onResume()。
<activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </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); } }技术上来说,在调用onStart()的时候Activity对用户就是可见的了。
@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; } }在onPause()中我们应该尽量做些简单的操作,而避免做高CPU负荷的操作,例如写入数据库,因为这会减慢跳转到下一个Activity的速度(大负荷的操作我们可以在onStop()中执行)。
@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 } }
@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实例会保存在内存中,所以在恢复的时候我们并不需要重新初始化。同时,系统也记录了布局中各个view的当前状态,所以如果用户在文本输入框中输入了文字,那么这些内容会被保存下来,所以并不需要我们去另外存储及还原它们。
@Override protected void onStart() { super.onStart(); // Always call the superclass method first // The activity is either being restarted or started for the first time // so this is where we should make sure that GPS is enabled LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (!gpsEnabled) { // Create a dialog here that requests the user to enable GPS, and use an intent // with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action // to take the user to the Settings screen to enable GPS when they click "OK" } } @Override protected void onRestart() { super.onRestart(); // Always call the superclass method first // Activity being restarted from stopped state }
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); }当Activity要重建的时候,系统会将之前这个Bundle传到onCreate()和onRestoreInstanceState()这两个方法中。这两个方法的差别在于,onCreate()中并不会检查Bundle是否为null,而onRestoreInstanceState()仅当Bundle中有需要被还原的状态时才会被调用,所以并不需要检查是否为null,且这个方法是在onStart()后调用的。
@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 } //... }
public void onRestoreInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState); // Restore state members from saved instance mCurrentScore = savedInstanceState.getInt(STATE_SCORE); mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL); }
@Override public void onDestroy() { super.onDestroy(); // Always call the superclass // Stop method tracing that the activity started during onCreate() android.os.Debug.stopMethodTracing(); }
跟着Google学Android —— 3.1 管好Activity的生命周期
标签:
原文地址:http://blog.csdn.net/qiwenhe1990/article/details/51011590