Android 中onConfigurationChanged问题

onConfigurationChanged 不生效问题解决方案:

  1).首先,需要重写onConfigurationChanged函数

   @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //do something
    }

  2). 需要在AndroidManifest.xml的Activity中配置android:configChanges参数。

       <activity android:name=”.StationListActivity”
            android:configChanges=”locale|layoutDirection”     //4.2之后的版本中必现添加layoutDirection属性,否则onConfigurationChanged不生效。
            android:windowSoftInputMode=”adjustNothing”
            android:screenOrientation=”portrait”>
       </activity>

  3)详解如下:

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”.

《Android 中onConfigurationChanged问题》

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.

 以上文档在较早版本中摘录,确少android 4.2之后的版本中的配置,需要参考最新的开发文档。必须属性layoutDirection

 

在一些特殊的情况中,你可能希望当一种或者多种配置改变时避免重新启动你的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() 方法,就有可能造成重复的初始化,降低程序效率是必然的了,而且更有可能因为重复的初始化而导致数据的丢失。这是需要千万避免的。

 

    原文作者:ActivityManagerService
    原文地址: https://www.cnblogs.com/kings-boke/p/4280842.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞