适当的停止和重启你的activity是activity生命周期中一个非常重要的过程,它可以确保你的用户意识到你的app总是活的并且没有丢失进度。有一些情景中,你的activity需要停止和重启:
用户打开最近的 Apps窗口并且跳转到你其他的app。 你的app中的前景activity已经停止。如果用户从主屏图标或者最近app窗口返回你的,然后activity重启。
用户在你的app中执行一个动作来启动一个新的activity。 当创建一个activity时当前的activity已经停止。 如果用户按返回键,第一个activity被重启。
在用户使你的app的时候,用户接到一个电话。
注意: 由于停止的时候系统内存中保留了你的Activity实例,所以你有可能不需要实现
Figure 1. 等用户离开你的activity,系统调用onStop()前调用
停止你的Activity
当你的activity接到
例如,下面有个
@OverrideprotectedvoidonStop(){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.ContentValuesvalues=newContentValues();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停止的时候销毁了你的activity,它仍然在
启动/重启你的Activity
当你的activity从停止状态中回到前台时,它将会接受到onRestart的调用。每次你的activity变得可视时(无论是重启还是第一次创建),系统也会调用
用
例如,由于用户在回到你的app前,已经离开了很长时间,
@OverrideprotectedvoidonStart(){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 enabledLocationManagerlocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);booleangpsEnabled=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"}}@OverrideprotectedvoidonRestart(){super.onRestart();// Always call the superclass method first// Activity being restarted from stopped state}
当系统销毁你的activity时,它为你的