一般安卓APP启动时,都会有一个启动画面(Splash Screen)或者说欢迎画面,利用好这一点,可以使人感觉你的APP启动速度非常快。
有些人可能会发现,一些APP点击启动后,会有一个黑屏期或都白屏期,而有一些会停顿一会才启动,这些都是启动时处理不当的后果。这里举一个比较好的APP网易云音乐,手机上有的可以体会下,启动应用后,立马出现一张红色图片,然后才出来广告页,最后进入主界面,一切看起来是很和谐的。
下面来说说出问题的原因和解决的方法。
原因:安卓启动一个APP时,首先启动主Activity,而启动Activity时,需要跑完Activity中的onCreate和onResume才会显示界面。也就是说,需要处理一些数据才会显示设定好的界面布局,然而,即使你在onCreate和onResume中什么都不做,程序自身的界面生成也是要费时间的,这一些时间是无法避免的,所以仍然会有黑屏阶段。
解决黑屏的方法有两个,首先介绍第一个(不推荐)
使用透明背景
原理:将启动时的黑屏改成透明的,这样就不会出现黑屏了,后果是,程序在出现真正的界面时,会没有任何反应一样,才就是说,点击应用图标启动应用后,会“卡顿”很长一段时间,然后显示界面。
实现方法:
在values/styles.xml中新建一个theme,使背景图片透明。<!-- Splash screen theme. --> <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar"> <!-- Customize your theme here. --> <item name="android:windowIsTranslucent">true</item> <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> </style>
说明:第一行item表示背景透明为真,第二行item表示状态栏透明为真,第三行item表示导航栏透明为真
然后在AndroidManifest.xml中的欢迎界面中设置theme为刚才新建的theme,如<activity android:name=".SplashActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name" android:theme="@style/SplashTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
其中的android:theme行即为设置theme为刚才新建的SplashTheme
然后再启动APP时,便不会出现黑屏或白屏了,但会有明显的卡顿感存在。
第二种方法,是一般APP都用的方法(推荐)
使用一张图片替换黑屏界面
原理:把黑屏阶段的黑屏替换为显示一张图片,这样,只要图片设置的好,感觉应用就像秒开一样。
实现方法:在values/styles.xml中新建一个theme,使背景图片透明。
<!-- Splash screen theme. --> <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar"> <!-- Customize your theme here. --> <item name="android:windowBackground">@drawable/splash</item> <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> </style>
说明:第一行的item使用一背景图,一旦点击应用图标,将首先启动这张图,然后再进行相关的处理程序。下面现行同方法一。
然后为Activity添加主题为上面新建的SplashTheme
<activity android:name=".SplashActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name" android:theme="@style/SplashTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
代码和上面方法一是一样的。
来一张效果图:
GitHub地址:Splash Screen