Launcher Activity在开机时重启两次解决办法

来源:互联网 发布:2016nba数据库排名 编辑:程序博客网 时间:2024/05/26 22:07

今天在看log的时候发现,Launcher activity会被onDestroy掉一次,然后再重启。

可能原因猜测:

1.横竖屏切换

2.MCC MNC等Configuration改变引起的 MCC(移动国家码)和 MNC(移动网络码)


由于当时的Launcher设置为强制横屏了,应该是不会引起重启的。

对于Configuration改变系统会发一个android.intent.action.CONFIGURATION_CHANGED的广播

于是就做了一个广播接收器去检测是不是由于Configuration改变引起的(后来发现Launcher本身有监听这个广播)

果然发现MCC值由0(未定义)变为460(中国)


原因已经初步确定了,怎么才能让activity不重启呢?

既然是activity重启,那就先去看一下activity有什么属性可以防止重启....


运气实在是好,刚好有这么个属性:

android:configChanges=["mcc", "mnc", "locale",                                 "touchscreen", "keyboard", "keyboardHidden",                                 "navigation", "screenLayout", "fontScale", "uiMode",                                 "orientation", "screenSize", "smallestScreenSize"]

官方的解释是这样的:

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 itsonConfigurationChanged() method is called.

大致意思也就是说:

    那些被列举的属性configuration改变时activity是否保存自己的状态。当应用发生了configuration改变,默认情况下activity将关闭并重启自身,但是如果定义了这个属性,activity将不必重启,它将保持运行状态同时调用onConfigurationChanged()方法。也就是说当不配置android:configChanges="mcc|mnc"时,当mcc或mnc的值发生改变的时候,会重启activity,并且onConfigurationChanged()不会被调用


果然配置了这个属性后Launcher Activity就不会在开机时候启动两次了。

1 0