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

Android Activity生命周期:暂停与重启
当用户离开Android App,Activity会经历onStop(),此时应释放非必要资源以防止内存泄漏。系统在需要时可能会直接销毁Activity。onResume()前会先调用onRestart()和onStart()。重度操作如数据库写入应在onStop()完成,因为onPause()不保证执行。系统会保存View状态,以便用户返回时恢复。

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

停止Activity

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

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

例子:

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


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


@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    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值