管理Activity的生命周期(3)暂停和重启一个Activity

来源:互联网 发布:淘宝卖家关闭订单付款 编辑:程序博客网 时间:2024/05/16 11:57

当用户离开App时,系统会调用onStop()来停止Activity,在stopped的时候返回时,就会调用onRestart(),接着快速的onStart(),onResume()

停止Activity

当你的Activity接收一个onStop()的方法回调,就不再可见了,这时我们应该释放所有用户不会再用到的不必要的资源。一旦Activyt停止了,如果系统需要恢复系统资源,可能会销毁这个实例。极端的例子就是系统可能杀死app进程而没有调用onDestroy()这个回调方法。所以,有必要在onStop()中来释放可能内存泄漏的资源。

虽然onPause()这个方法已经在onStop()之前就调用了,但是呢,那么密集型的,耗内存的操作,比如写数据库等,应该放在onStop()这个地方。

例子:

@Overrideprotected 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停止了,Activity对象仍然保存在内存中,在Resumed的时候,这个对象还会被调用出来。我们不用再次重新初始化那些组件,系统仍然保存当前的每个layout中的View的状态,因此用户输入的文字依旧还是存在于EditText中的,因此输入的内容之类的,就不用再保存了哦。


!!!即使系统在onStop的时候销毁了Activity,它仍然会保存那些View对象的状态在一个Bundle中并且会在用户返回同一个Activity实例中恢复那些数据。


@Overrideprotected 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"    }}@Overrideprotected void onRestart() {    super.onRestart();  // Always call the superclass method first        // Activity being restarted from stopped state    }


0 0
原创粉丝点击