SplashScreen简略

产生背景,建议阅读:优化-启动白屏一系列文章

在 Android 中,SplashScreen 是应用启动时短暂显示的界面,通常用于展示应用 logo、品牌或加载资源。它的核心作用有两个:

1. 给用户反馈:告诉用户 App 正在启动,避免白屏;

2. 掩盖启动延迟:在后台加载资源、初始化数据时填补空白。

一、现代 Android(API 31+)中的 SplashScreen(推荐方式)

Android 12(API 31) 开始,Google 提供了官方的 SplashScreen API,通过 androidx.core.splashscreen 实现一致的启动体验。

1. 使用方式

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // 启用系统 SplashScreen
        installSplashScreen()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

默认显示应用图标和背景。

2. 自定义延迟消失条件(如动画未完成、数据未加载完)

installSplashScreen().setKeepOnScreenCondition {
    viewModel.isLoading // 返回 true 表示还不允许消失
}

二、旧版本的实现方式(API 30 及以下)

1. 创建一个 SplashActivity;

2. 使用定时器或加载状态判断进入 MainActivity;

3. 在 style.xml 设置主题(无 ActionBar)以避免闪烁。

<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowBackground">@drawable/splash_background</item>
</style>



class SplashActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }
}

三、系统层面:SplashScreen 与 Window 启动流程的关系

在系统底层,SplashScreen 会影响以下阶段:

Activity 还未绘制第一帧时,系统会使用 SplashScreen 覆盖窗口;

只有当 ViewRootImpl.finishDrawing() 被调用,且 mReportNextDraw = true 时,系统才会真正移除 SplashScreen;

• 这也解释了 mReportNextDraw 的用途:即使 Activity 不可见也强制绘制,确保及时移除 Splash。

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器