前言
应用启动时如果在Application中做了很多事务,会导致启动时有个白屏的时间,体验十分不好。通常的做法是给Application或者第一个启动的Activity的主题添加上android:windowBackground属性来优化体验。
到了Android 12,官方新增了SplashScreen Api,可为所有应用添加新的启动动画,显示速度十分实时,所以到了Android 12,我们就不必自己添加android:windowBackground属性,最重要的是它是能向下兼容的。
Android 12.0及以上
在Android 12上已经默认使用了SplashScreen,如果不考虑向下兼容的问题,不需要任何配置,系统就会自动使用App的图标作为SplashScreen的图标。
Android 12.0以下
这个时候就需要一些适配操作
依赖SplashScreen
注意的是必须是在第一个启动的Activity同目录的build.gradle中添加依赖
implementation "androidx.core:core-splashscreen:1.0.0-beta02"
添加theme
在Style.xml新建一个主题,parent必须为Theme.SplashScreen
windowSplashScreenBackground:启动动画的背景
windowSplashScreenAnimatedIcon:启动动画的图标
windowSplashScreenAnimationDuration:启动动画的时间
postSplashScreenTheme:启动动画退出后的启动页的主题
<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中使用这个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>
最重要的一步,修改第一个启动的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)
}
}
低版本效果
这里我用的是一台11的机器,可以看到效果基本上和12.0差不多,如果不去适配的话11的机器是看不到这个页面的(请忽略我自己做的图标)
结尾
可以看到适配很简单,另外可以看到installSplashScreen()是有返回值的,我们可以利用这个值去做一些更强大的事情,例如延长启动页面停留时间、设置动画效果等,这些大家自己去研究。