Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 啟動畫面(Splash Screen)的實作方式

編輯:Android 開發實例

啟動畫面在應用程式中相當常見,通常會伴隨一個背景執行緒,為主程式的啟動預先準備資源。Android 上實作起來並不複雜,以下是最基礎的做法。

第一步:準備版面配置

建立 splash.xml,內容基本上就是一張鋪滿畫面的 ImageView:

<LinearLayout
  xmlns:android="https://schemas.android.com/apk/res/android"
  android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical">
<ImageView android:layout_height="fill_parent" android:layout_width="fill_parent" android:scaleType="fitCenter" android:src="@drawable/splash"></ImageView>
</LinearLayout>

第二步:讓 SplashActivity 作為啟動入口

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    Handler x = new Handler();
    x.postDelayed(new splashhandler(), 2000);

}

class splashhandler implements Runnable{
    public void run() {
        startActivity(new Intent(getApplication(),MainActivity.class));
        SplashActivity.this.finish();
    }
}

關鍵是 postDelayed():延遲兩秒後跳轉到 MainActivity,並立刻 finish 掉 SplashActivity,避免使用者按返回鍵又回到啟動畫面。

實務上的補充建議

上面這個範例用固定秒數硬跳,缺點很明顯:如果初始化還沒做完就跳頁,使用者會看到空白畫面;如果早就準備好了,又會白等兩秒。比較穩健的做法有兩個方向:

  • 把等待條件改成「初始化完成」的信號,再搭配一個最長逾時(例如 3 秒)作為保險,避免流程卡死。
  • 若只是想消除冷啟動的白屏,Android 5.0 之後可以直接用主題的 windowBackground 設定啟動圖,不必額外開一個 Activity,也不會有版面配置的膨脹成本。

另外提醒:真正耗時的初始化工作應該放在背景執行緒,不要在 onCreate() 或主執行緒裡做 I/O。

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