Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 打造 Splash 啟動閃屏畫面的簡潔做法

編輯:關於 Android 程式設計

App 啟動時那張短暫出現的品牌畫面,就是所謂的 Splash 畫面。做法其實相當樸素:開一個專用的 Activity 當入口,顯示圖片後用 Handler.postDelayed() 延遲一小段時間,再跳轉到主畫面並把自己關掉。

Java 程式碼

public class Splash extends Activity {

    private final int SPLASH_DISPLAY_LENGHT = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent mainIntent = new Intent(Splash.this, Application.class);
                Splash.this.startActivity(mainIntent);
                Splash.this.finish();
            }
        }, SPLASH_DISPLAY_LENGHT);
    }
}

SPLASH_DISPLAY_LENGHT 是顯示的毫秒數,這裡設為 1000 也就是一秒。實務上建議別拉太長,超過一秒半使用者就會開始不耐煩。最後那個 finish() 千萬別省,否則使用者按返回鍵會又回到閃屏畫面。

AndroidManifest.xml 的設定

關鍵是把 Splash 設為啟動入口,並讓主畫面退居其後。

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name">
    <activity
        android:name=".Application"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.DEFAULT" />
            <category android:name="android.intent.category.VIEW" />
        </intent-filter>
    </activity>
    <activity
        android:name="Splash"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

帶有 MAIN 與 LAUNCHER 的那個 Activity 就是桌面圖示點下去後會開啟的畫面,所以 Splash 必須掛上這組 filter,主畫面則不需要。

可以更好的地方

這種固定睡覺式的閃屏有兩個常見缺點。一是純粹在浪時間,二是若閃屏期間正在初始化資料,延遲結束時初始化可能還沒跑完。比較好的做法有兩種:把初始化工作放到背景執行緒,等真正準備好才跳轉,並設一個逾時上限避免卡在閃屏;或者改用 Android 12(API 31)起提供的 SplashScreen API,由系統統一處理啟動動畫,這也是目前官方推薦的方式。

另外若使用固定延時寫法,記得在 onDestroy() 中移除 Handler 的 callback,避免 Activity 已銷毀卻仍被回呼而導致記憶體洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved