onConfigurationChanged的作用

onConfigurationChanged的作用

API原文說明:
android:configChanges
Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.

Any or all of the following strings are valid values for this attribute. Multiple values are separated by '|' — for example, "locale|navigation|orientation".

All of these configuration changes can impact the resource values seen by the application. Therefore, when onConfigurationChanged() is called, it will generally be necessary to again retrieve all resources (including view layouts, drawables, and so on) to correctly handle the change.

 

在一些特殊的情況中,你可能希望當一種或者多種配置改變時避免重新啓動你的activity。你可以通過在manifest中設置android:configChanges屬性來實現這點。
你可以在這裏聲明activity可以處理的任何配置改變,當這些配置改變時不會重新啓動activity,而會調用activity的
onConfigurationChanged(Resources.Configuration)方法。如果改變的配置中包含了你所無法處理的配置(在android:configChanges並未聲明),
你的activity仍然要被重新啓動,而onConfigurationChanged(Resources.Configuration)將不會被調用。

其次:android:configChanges=""中可以用的值:keyboard|mcc|mnc|locale|touchscreen|keyboardHidden|navigation|orientation……
Configuration 類中包含了很多種信息,例如系統字體大小,orientation,輸入設備類型等等.(如上圖)
比如:android:configChanges="orientation|keyboard|keyboardHidden"

 

當Configuration改變後,ActivityManagerService將會發送"配置改變"的廣播,會要求ActivityThread 重新啓動當前focus的Activity.
這是默認情況,我們不做任何處理,如果我們android:configChanges來配置Activity信息,那麼就可以避免對Activity銷燬再重新創建,而是調用
onConfigurationChanged方法。

通過查閱Android API可以得知android:onConfigurationChanged實際對應的是Activity裏的onConfigurationChanged()方法。
在AndroidManifest.xml中添加上訴代碼的含義是表示在改變屏幕方向、彈出軟件盤和隱藏軟鍵盤時,不再去執行onCreate()方法,
而是直接執行onConfigurationChanged()。如果不申明此段代碼,按照Activity的生命週期,都會去執行一次onCreate()方法,而onCreate()方法通常會在顯示之前做一些初始化工作。所以如果改變屏幕方向這樣的操作都去執行onCreate()方法,就有可能造成重複的初始化,降低程序效率是必然的了,而且更有可能因爲重複的初始化而導致數據的丟失。這是需要千萬避免的。


參考:
Android學習筆記——關於onConfigurationChanged
http://www.cnblogs.com/wisekingokok/archive/2011/10/06/2199948.html

onConfigurationChanged信息處理 監聽屏幕旋轉 語言變換 鍵盤滑動 
http://fghzhaopai.blog.163.com/blog/static/4780555620116882211560/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章