App 啟動時,使用 ImageView 全螢幕顯示啟動圖,但之前會閃現一幀預設主題背景 (白/黑/ActionBar)。
Activity 啟動流程:
1. 系統依 theme 繪製預設視窗背景 (含 ActionBar)。
2. onCreate → setContentView 載入佈局。
3. 兩者間有明顯時間差,造成閃爍。
<!-- styles.xml -->
<style name="AppTheme.Launcher">
<item name="android:windowBackground">@drawable/launch_bg</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
<!-- drawable/launch_bg.xml (layer-list) -->
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@color/white"/>
<item>
<bitmap android:gravity="center" android:src="@mipmap/launch_image"/>
</item>
</layer-list>
<!-- AndroidManifest.xml -->
<activity android:name=".MainActivity"
android:theme="@style/AppTheme.Launcher"> ... </activity>
MainActivity onCreate 先 setTheme(R.style.AppTheme) 再 setContentView 切換到正式主題。
// MainActivity.onCreate 最前
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
getSplashScreen().setOnExitAnimationListener(splashScreenView -> {
splashScreenView.remove();
});
}
配合 themes.xml 設定 windowSplashScreenBackground、windowSplashScreenAnimatedIcon。
| 方案 | 閃爍 | 相容性 | 維護成本 |
|---|---|---|---|
| windowBackground + Launcher Theme | 無 | API 14+ | 低 |
| SplashScreen API | 無 | API 31+ (核心庫回溯至 API 21) | 低 |
| Thread.sleep + 全屏 ImageView | 有 | 全版本 | 高 (需維護 SplashActivity) |