编写:kesenhoo - 原文: http://developer.android.com/training/basics/activity-lifecycle/stopping.html
Note:因为系统在activity停止时会在内存中保存Activity的实例。有些时候你不需要实现onStop(),onRestart()甚至是onStart()方法. 因为大多数的activity相对比较简单,activity会自己停止与重启,你只需要使用onPause()来停止正在运行的动作并断开系统资源链接。
Figure 1.上图显示:当用户离开你的activity,系统会调用onStop()来停止activity (1). 这个时候如果用户返回,系统会调用onRestart()(2), 之后会迅速调用onStart()(3)与onResume()(4). 请注意:无论什么原因导致activity停止,系统总是会在onStop()之前调用onPause()方法。
@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.
);
}
Note:即使系统会在activity stop的时候停止这个activity,它仍然会保存View对象的状态(比如EditText中的文字) 到一个Bundle中,并且在用户返回这个activity时恢复他们(下一个会介绍在activity销毁与重新建立时如何使用Bundle来保存其他数据的状态).
@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
}