android冷启动优化
什么是冷启动 冷启动指的是应用第一次启动或者应用被杀死(不在内存中)后重新启动的情况。 你可能已经发现了,这种情况下启动时间会稍长一点。因为它会重新初始化资源(Application等)。app启动时通常会在Application或者所谓的SplashActivity中做初始化工作。如果Application中的工作过多的话, 那么当冷启动的时候,就会出现白屏情况,因为此时SplashActivity还没有被初始化,SplashActivity上的图片还没有被显示出来。
我们当然不希望出现白屏的情况。
解决方案应该从两方面考虑,1是优化Application的初始化逻辑,比如该异步的异步,该延迟的延迟。2是将白屏换成SplashActivity中展示的图片,让用户有一种应用已经启动了的错觉,本文讲的就是这种优化方案。
如何优化 我们需要为SplashActivity设置一个Theme,如下:styles.xml
<style name="AppTheme.Launcher"> <item name="android:windowBackground">@drawable/launch_screen</item> <item name="android:windowFullscreen">true</item> </style>这个Theme继承了app的基础主题AppTheme,同时复写了windowBackground属性,它的值即SplashActivity将展示的图片(logo等等…)。
launch_screen.xml
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque"> <item android:drawable="@android:color/white"/> <!-- Your product logo - 144dp color version of your app icon --> <item> <bitmap android:src="@drawable/splash_defalut" android:gravity="fill"/> </item> </layer-list>然后将这个主题设置到SplashActivity上:
<activity android:name=".ui.activity.SplashActivity" android:configChanges="fontScale" android:screenOrientation="portrait" android:theme="@style/AppTheme.Launcher" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>这还没有完,因为我们为SplashActivity多设置了一个背景图,必然会导致过渡绘制,所以我们在其初始化前,将主题设置回原来的:
@Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); setContentView(R.layout.splash_activity);以上。
现在你会发现即使启动时间再长,也不会出现白屏。