onPause():
- 當系統調用你的activity中的onPause(),從技術上講,那意味着你的activity仍然處於部分可見的狀態,當時大多數時候,那意味着用戶正在離開這個activity並馬上會進入Stopped state. 你通常應該在onPause()回調方法里面做下面的事情:
- 停止動畫或者是其他正在運行的操作,那些都會導致CPU的浪費.
- 提交沒有保存的改變,但是僅僅是在用戶離開時期待保存的內容(such as a draft email).
- 釋放系統資源,例如broadcast receivers, sensors (like GPS), 或者是其他任何會影響到電量的資源。
- 例如, 如果你的程序使用Camera,onPause()會是一個比較好的地方去做那些釋放資源的操作。
-
-
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;
-
}
-
}
- 通常,你not應該使用onPause()來保存用戶改變的數據 (例如填入表格中的個人信息) 到永久磁盤上。僅僅當你確認用戶期待那些改變能夠被自動保存的時候such as when drafting an email),你可以把那些數據存到permanent storage 。然而,你應該避免在onPause()時執行CPU-intensive 的工作,例如寫數據到DB,因為它會導致切換到下一個activity變得緩慢(你應該把那些heavy-load的工作放到onStop()去做)。
- 如果你的activity實際上是要被Stop,那么你應該為了切換的順暢而減少在OnPause()方法里面的工作量。
- Note:當你的activity處於暫停狀態,Activity實例是駐留在內存中的,並且在activity 恢復的時候重新調用。你不需要在恢復到Resumed狀態的一系列回調方法中重新初始化組件。
OnStop():
- 當你的activity調用onStop()方法, activity不再可見,並且應該釋放那些不再需要的所有資源。一旦你的activity停止了,系統會在不再需要這個activity時摧毀它的實例。在極端情況下,系統會直接殺死你的app進程,並且不執行activity的onDestroy()回調方法, 因此你需要使用onStop()來釋放資源,從而避免內存泄漏。(這點需要注意)
- 盡管onPause()方法是在onStop()之前調用,你應該使用onStop()來執行那些CPU intensive的shut-down操作,例如writing information to a database.
- 例如,下面是一個在onStop()的方法里面保存筆記草稿到persistent storage的示例:
-
-
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對象會保存在內存中,並且在activity resume的時候重新被調用到。你不需要在恢復到Resumed state狀態前重新初始化那些被保存在內存中的組件。系統同樣保存了每一個在布局中的視圖的當前狀態,如果用戶在EditText組件中輸入了text,它會被保存,因此不需要保存與恢復它。
- Note:即時系統會在activity stop的時候銷毀這個activity,它仍然會保存View objects (such as text in an EditText) 到一個Bundle中,並且在用戶返回這個activity時恢復他們(下一個會介紹在activity銷毀與重新建立時如何使用Bundle來保存其他數據的狀態).
onDestroy():
- 當系統Destory你的activity,它會為你的activity調用onDestroy()方法。因為我們會在onStop方法里面做釋放資源的操作,那么onDestory方法則是你最后去清除那些可能導致內存泄漏的地方。因此你需要確保那些線程都被destroyed並且所有的操作都被停止。
參考:http://hukai.me/android-training-course-in-chinese/basics/activity-lifecycle/pausing.html
http://hukai.me/android-training-course-in-chinese/basics/activity-lifecycle/stopping.html