簡介

啟動畫面 (Splash Screen) 是一種在 APP 正常運作之前的一個過渡型畫面。

我們有時在 APP 正常運作前會做一些準備動作,例如:檢查權限、資料同步…等,這會造成 APP 的畫面無法出現或停頓,所以我們會設計一個畫面來讓 App 的啟動流程更滑順一點。

早期為了達成這個目標,大家都各顯神通,方法五花八門,但是在 Android 12 後,Google 提供了一個比較標準化的方式來建立啟動畫面 (Splash Screen),稱為 SplashScreen API 。在預設的狀況下,也會自動產生一個有 App Logo 的啟動頁面。

依賴

implementation("androidx.core:core-splashscreen:1.0.1")

程式碼範例

先讓他跑起來

res/values/splash.xml (新建)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.App.Starting" parent="Theme.SplashScreen">
        
        <!-- 設定啟動頁面的背景色,此處設為紅色 -->
        <item name="windowSplashScreenBackground">#FF0000</item>
        
        <!-- 設定啟動頁面的 logo,此處設為預設的 android icon -->
        <item name="windowSplashScreenAnimatedIcon">@drawable/ic_launcher_foreground</item>
        
        <!-- 設定啟動後的 theme,此為必要設定,通常就是專案的 theme  -->
        <item name="postSplashScreenTheme">@style/Theme.SplashScreenKata</item>
    </style>
</resources>

AndroidManifest.xml (編輯)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        ...
        android:theme="@style/Theme.App.Starting"
        tools:targetApi="31">
        <activity
            ...
            android:theme="@style/Theme.App.Starting">
            ...
        </activity>
    </application>

</manifest>

此時再執行 app,就會發現啟動畫面的背景色變為紅色

模擬啟動時的耗時處理

MainViewModel.kt (新建)

class MainViewModel: ViewModel() {
    val isCheckingStatus = mutableStateOf<Boolean>(true)

    init {
        viewModelScope.launch {
            sleep(3000)
            isLoading.value = false
        }
    }
}

MainActivity.kt (編輯)

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        
        // 加入以下程式碼
        val viewModel = MainViewModel()
        installSplashScreen().apply {
            setKeepOnScreenCondition {
                // 值為 false 時,就會結束啟動畫面
                viewModel.isLoading.value
            }
        }

        setContent {
            ...
        }
    }
}

此時執行 app,畫面就會停留 3 秒後,再進入 app 的主頁面。

參考資料

Mastering Splash Screens in Android: A Complete Guide to Using Splash API

How to Build an Animated Splash Screen on Android – The Full Guide – by Philipp

Android Developers: 啟動畫面

Implementing SplashScreen using SplashScreen API in Android Jetpack Compose

Last modified: 2025 年 7 月 9 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.