Android App 啟動時展示歡迎頁(Splash Screen)是標準需求。傳統做法創建獨立 SplashActivity 延遲跳轉,但會增加啟動延遲且體驗生硬。現代最佳實踐是主題背景法:利用 windowBackground 瞬間顯示圖片,無需額外 Activity。
Android 啟動 App 時會先顯示 Theme 指定的 windowBackground,再加載佈局。利用這一機制,在主題中設置全屏圖片作為背景,主 Activity 啟動後立即在 onCreate 切換到正常主題,實現「零延遲」無縫切換。
<!-- res/values/styles.xml -->
<style name="AppTheme.Splash" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/splash_bg</item>
<item name="android:windowFullscreen">true</item>
</style>
<!-- res/drawable/splash_bg.xml -->
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@color/white" /> <!-- 背景色 -->
<item>
<bitmap
android:gravity="center"
android:src="@mipmap/ic_launcher_splash" /> <!-- Logo 圖片 -->
</item>
</layer-list>
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme.Splash"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// 必須在 super.onCreate() 之前調用,切換到正常主題
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 正常業務邏輯...
}
}
| 方案 | 啟動速度 | 代碼複雜度 | 用戶體驗 | 維護性 |
|---|---|---|---|---|
| 獨立 SplashActivity + Handler 延遲 | 慢(額外 Activity 棧) | 高 | 有明顯切換動畫 | 差 |
| 主題背景法 (推薦) | 極快(無額外開銷) | 低 | 無縫平滑 | 優 |
| Android 12+ SplashScreen API | 極快 | 低 | 系統級標準 | 優 (需適配) |
// 依賴
implementation "androidx.core:core-splashscreen:1.0.1"
// MainActivity.onCreate 最前調用
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
SplashScreen.installSplashScreen(this);
}
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
採用主題背景法或官方 API,告別笨重的 SplashActivity,打造專業級啟動體驗。