首页 > 代码库 > 4、Android Activity的生命周期 Activity的生命周期
4、Android Activity的生命周期 Activity的生命周期
1、完整生命周期
上图是Android Activity的生命周期图,其中Resumed、Paused、Stopped状态是静态的,这三个状态下的Activity存在时间较长。
(1)Resumed:在此状态时,用户可以与Activity进行交互,Activity在最前端
(2)Paused:在此状态时,Activity被另外一个Activity遮盖,此Activity不可接受用户输入信息。另外一个Activity来到最前面,半透明的,但并不会覆盖整个屏幕。
(3)Stopped:在此状态时,Activity完全被隐藏,不可见。保留当前信息,Activity不执行任何代码。
(4)Created与Started:系统调用onCreate()后迅速调用onStart(),然后迅速执行onResume()。
以上就是Android的Activity整个生命周期。
2、主Activity
用户可以指定程序启动的主界面,此时被声明为“launcher或main”Activity的onCreate()方法被调用,成为程序的入口函数。该入口Activity可以在AndroidManifest.xml中定义主Activity。此时,主Activity必须使用以下标签声明:
<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>
3、一个新的Activity实例
系统首先调用新Activity的onCreate()方法,所以,我们必须实现onCreate()方法。如:声明UI元素、定义成员变量、配置UI等。但是事情不宜太多,避免启动程序太久而看不到界面。
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); } }onCreate()执行完即调用onStart()和onResume()方法,Activity不会在Created或者Started状态停留。
4、销毁Activity
Activity的最后一个回调是onDestroy(),系统会执行这个方法做为你的Activity要从系统中完全删除的信号。大多数APP不需实现此方法,因为局部类的references会随着Activity的销毁而销毁。并且Activity应该在onPause()和onStop()方法中执行清楚Activity资源的操作。如果Activity在onCreate()时创建的后台线程,或者是其他有可能导致内存泄露的资源,你应该在onDestroy()时杀死它们。
@Override public void onDestroy() { super.onDestroy(); // Always call the superclass // Stop method tracing that the activity started during onCreate() android.os.Debug.stopMethodTracing(); }系统通常是在执行了onPause()与onStop()后在调用onDestroy(),除非在onCreate()中调用了finish()。例如,如果你的Activity只是做了一个临时的逻辑跳转功能,它使用用来决定跳转到下一个Activity,这样,你需要在onCreate()中调用finish()方法。系统就会直接调用onDestroy方法,其他生命周期就不会被执行。
5、暂停与恢复
@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()来保存用户改变的数据到永久存储上,当你确认用户期待那些改变能够自动保存的时候,才可以把那些数据存储到永久存储。然而,应该避免在onPause()时执行CPU-intensive的工作,例如写数据到DB,因为他会导致切换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 } }
6、停止与重启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); }
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 } ... }我们可以选择实现onRestoreInstanceState(),而不是在onCreate方法里恢复数据。onRestoreInstanceState()方法会在onStart()方法之后执行,系统仅仅会在存在需要恢复的状态信息时才会调用onRestoreInstanceState(),因此不需检查Bundle是否为NULL。
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); }
4、Android Activity的生命周期 Activity的生命周期