前言
應(yīng)用啟動(dòng)時(shí)如果在Application中做了很多事務(wù),會(huì)導(dǎo)致啟動(dòng)時(shí)有個(gè)白屏的時(shí)間,體驗(yàn)十分不好。通常的做法是給Application或者第一個(gè)啟動(dòng)的Activity的主題添加上android:windowBackground屬性來(lái)優(yōu)化體驗(yàn)。
到了Android 12,官方新增了SplashScreen Api,可為所有應(yīng)用添加新的啟動(dòng)動(dòng)畫(huà),顯示速度十分實(shí)時(shí),所以到了Android 12,我們就不必自己添加android:windowBackground屬性,最重要的是它是能向下兼容的。
Android 12.0及以上
在Android 12上已經(jīng)默認(rèn)使用了SplashScreen,如果不考慮向下兼容的問(wèn)題,不需要任何配置,系統(tǒng)就會(huì)自動(dòng)使用App的圖標(biāo)作為SplashScreen的圖標(biāo)。
Android 12.0以下
這個(gè)時(shí)候就需要一些適配操作
依賴SplashScreen
注意的是必須是在第一個(gè)啟動(dòng)的Activity同目錄的build.gradle中添加依賴
implementation "androidx.core:core-splashscreen:1.0.0-beta02"
添加theme
在Style.xml新建一個(gè)主題,parent必須為T(mén)heme.SplashScreen
windowSplashScreenBackground:?jiǎn)?dòng)動(dòng)畫(huà)的背景
windowSplashScreenAnimatedIcon:?jiǎn)?dòng)動(dòng)畫(huà)的圖標(biāo)
windowSplashScreenAnimationDuration:?jiǎn)?dòng)動(dòng)畫(huà)的時(shí)間
postSplashScreenTheme:?jiǎn)?dòng)動(dòng)畫(huà)退出后的啟動(dòng)頁(yè)的主題
<resources xmlns:tools="http://schemas.android.com/tools">
<style name="SplashTheme" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@color/white</item>
<item name="windowSplashScreenAnimatedIcon">@mipmap/ic_launcher_custom</item>
<item name="windowSplashScreenAnimationDuration">200</item>
<item name="postSplashScreenTheme">@style/AppTheme</item>
</style>
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="colorPrimary">@color/XXXXX</item>
<item name="colorPrimaryDark">@color/XXXXX</item>
<item name="colorAccent">@color/XXXXX</item>
</style>
</resources>
AndroidManifest.xml中使用這個(gè)theme
<activity
android:name=".ui.activity.SplashActivity"
android:exported="true"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
最重要的一步,修改第一個(gè)啟動(dòng)的Activity
在setContentView()之前添加上installSplashScreen()即可
class SplashActivity : Activity() {
private var binding: ActivitySplashBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val splashScreen = installSplashScreen()
binding = ActivitySplashBinding.inflate(layoutInflater)
setContentView(binding!!.root)
}
}
低版本效果
這里我用的是一臺(tái)11的機(jī)器,可以看到效果基本上和12.0差不多,如果不去適配的話11的機(jī)器是看不到這個(gè)頁(yè)面的(請(qǐng)忽略我自己做的圖標(biāo))

結(jié)尾
可以看到適配很簡(jiǎn)單,另外可以看到installSplashScreen()是有返回值的,我們可以利用這個(gè)值去做一些更強(qiáng)大的事情,例如延長(zhǎng)啟動(dòng)頁(yè)面停留時(shí)間、設(shè)置動(dòng)畫(huà)效果等,這些大家自己去研究。