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

Android 歡迎頁(Splash Screen)的兩種實現方式

編輯:關於 Android 程式設計

裝好一個 App 首次打開,映入眼簾的往往就是那張 Splash Screen。撇開 Material Design 對這種做法的態度不談,它至少解決了兩個實際問題:一是新裝應用的品牌曝光與新手指引,二是版本更新時的功能亮點說明。有人對它嗤之以鼻,有人趨之若鶩,好壞不在本文討論範圍,這裡只談怎麼寫。

一、最簡單的 Splash:定時跳轉

如果歡迎頁只需要展示 Logo、版本號這類靜態信息,那麼做法非常直白——讓 WelcomeActivity 停留幾秒,然後自動跳轉到主界面。Handler.postDelayed() 就能勝任:

// 3 秒後啟動主界面
new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent i = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(i);
        finish();   // 啟動主 Activity 後銷毀自身,避免返回鍵回到歡迎頁
    }
}, 3000);

別忘了那句 finish(),否則用戶按返回鍵會退回閃屏,體驗很怪。

二、進階 Splash:先乾活,再進主界面

更常見的場景是:App 在進入主界面前必須完成一些初始化工作,比如從網路拉取配置、下載圖片、解析 JSON/XML、上報設備信息、校驗登入態等等。這時 Splash 就成了「合法的等待時間」——把耗時任務藏進去,完成後再放行。

下面以「遠程下載一張圖片,解析後展示在主界面」為例。

1. 歡迎頁佈局 res/layout/splash_screen.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/appImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/logo" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:text="Welcome"
        android:textColor="#00ACED"
        android:textSize="30sp" />

</LinearLayout>

佈局效果:

2. 主界面佈局 res/layout/activity_main.xml

只放一個 ImageView,用來展示下載下來的圖片:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

3. SplashScreenActivity

用 AsyncTask 在後台完成下載與解析,再通過 Intent 把結果傳給 MainActivity:

public class SplashScreenActivity extends Activity {

    private static final String URL = "https://www.jycoder.com/json/Image/1.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        /* 簡單版 Splash 的寫法(保留備用)
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        }, 3000);
        */

        // 後台執行下載任務
        new FetchDataTask().execute(URL);
    }

    public class FetchDataTask extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            try {
                HttpURLConnection connection =
                        (HttpURLConnection) (new URL(params[0])).openConnection();
                InputStream is = connection.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
            // 注意:Intent 傳遞 Bitmap 時,圖片大小不宜超過 40K
            intent.putExtra("Image", result);
            startActivity(intent);
            finish();   // 同樣要銷毀自身
        }
    }
}

4. MainActivity 接收數據

public class MainActivity extends Activity {

    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.image);
        Intent intent = getIntent();
        if (intent != null) {
            Bitmap bitmap = intent.getParcelableExtra("Image");
            imageView.setImageBitmap(bitmap);
        }
    }
}

5. Manifest 配置

記得加網路權限,並把 SplashScreenActivity 設為啟動項:

<manifest package="com.coder.splashscreen"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:theme="@style/AppTheme">

        <activity android:name=".SplashScreenActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity" />
    </application>

</manifest>

6. 一個容易踩的坑

我第一次用遠程圖片測試時直接崩了,報的是 TransactionTooLargeException 一類的錯誤:

原因是 Intent 附带的 Bundle 大小受限,傳 Bitmap 時不宜超過 40K。生產環境中更推薦的做法是:把圖片寫入本地檔案或傳 URI/路徑,主界面再去讀取,或者乾脆交給成熟的圖片加載庫處理。

完成後的效果:

小結

例子都不算複雜,但 Splash Screen 的思路基本就這兩類:要麼純定時跳轉,要麼「後台幹活 + 完成後跳轉」。真正需要斟酌的其實不是代碼,而是該不該放、放多久——超過三五秒的閃屏,只會讓用戶想卸載。

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