在上一篇中我們簡單了解關于Android中狀态儲存的過程和原理,這一篇中我們來看一下在系統配置改變的情況下儲存資料及恢複資料的過程。
下面我們先來看一個現象:(代碼在 Android中狀态儲存探究(上)中)
先啟動應用如下:
列印的Log
再翻轉螢幕
列印的Log如下
可以看到每翻轉一次螢幕實際上系統會停止原理的activity并銷毀然後重新啟動一次,在這個過程中會調用onSaveInstanceState方法來儲存原來的資料并通過onCreate方法恢複資料。因為要先onDestroy然後才onCreate,是以就會出現一個黑屏(閃屏)的短暫過程。像這種改變整個系統配置的現象叫做ConfigurationChanges.
ConfigurationChange具體有哪些,都代表什麼,請看:http://developer.android.com/reference/android/R.attr.html#configChanges
Constant
Value
Description
<code>mcc</code>
0x0001
The IMSI MCC has changed, that is a SIM has been detected and updated the Mobile Country Code.
<code>mnc</code>
0x0002
The IMSI MNC has changed, that is a SIM has been detected and updated the Mobile Network Code.
<code>locale</code>
0x0004
The locale has changed, that is the user has selected a new language that text should be displayed in.
<code>touchscreen</code>
0x0008
The touchscreen has changed. Should never normally happen.
<code>keyboard</code>
0x0010
The keyboard type has changed, for example the user has plugged in an external keyboard.
<code>keyboardHidden</code>
0x0020
The keyboard or navigation accessibility has changed, for example the user has slid the keyboard out to expose it. Note that despite its name, this applied to any accessibility: keyboard or navigation.鍵盤隐藏
<code>navigation</code>
0x0040
The navigation type has changed. Should never normally happen.導航
<code>orientation</code>
0x0080
The screen orientation has changed, that is the user has rotated the device.螢幕翻轉
<code>screenLayout</code>
0x0100
The screen layout has changed. This might be caused by a different display being activated.螢幕布局改變
<code>uiMode</code>
0x0200
The global user interface mode has changed. For example, going in or out of car mode, night mode changing, etc.
<code>screenSize</code>
0x0400
<code>smallestScreenSize</code>
0x0800
<code>layoutDirection</code>
0x2000
The layout direction has changed. For example going from LTR to RTL.
<code>fontScale</code>
0x40000000
The font scaling factor has changed, that is the user has selected a new global font size.字型大小
有時候我們需要在配置改變的時候恢複一些不能夠序列化的對象,這時候就需要用onRetainNonConfigurationInstance方法儲存,然後在onCreate方法中通過getLastNonConfigurationInstance擷取對象。但是要注意的是,儲存的對象不要用與context關聯的對象,比如View,否則會引起記憶體洩露。
有沒有什麼方法在Configuration改變的時候不重新啟動Activity,在manifest檔案中我們來看一下一個配置:
好吧,先配上orientation值,我們再去Activity中添加一段代碼,如下:
這個時候切換螢幕時系統會調用onConfigurationChanged方法,來處理我們自定義的配置改變。而不會去重新啟動新的Activity。