Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 應用實例:動態輪播 assets 目錄下的圖片

功能目標:在 ImageView 中每隔 0.1 秒切換一次圖片,播放完 assets 下的所有圖片後再從頭開始,並可隨時停止。

實作思路

一是透過 AssetManager 取得 assets 內的資源,用 BitmapFactory 把圖片輸入流轉成 Bitmap,再設定給 ImageView。二是動態播放的計時迴圈必須放在子執行緒,但 Android 的子執行緒不能更新 UI,因此要借助執行在主執行緒的 Handler,以 Message 傳遞訊號來完成畫面更新。

關鍵技術點:AssetManager 應用、Bitmap 回收、Handler 訊息機制、多執行緒與執行緒的終止。

第 1 步:建立工程

新增專案 DisplayImagesDemo,Activity 命名為 DisplayImagesActivity。

第 2 步:放入圖片並修改版面

往 assets 目錄複製幾張測試圖片,然後改寫 main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5px"
        android:layout_weight="1" />

    <LinearLayout style="@android:style/ButtonBar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnStart"
            android:text="開始播放"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+id/btnStop"
            android:text="停止播放"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>
</LinearLayout>

第 3 步:撰寫 DisplayImagesActivity

先在 onCreate 中初始化視圖、抓出 assets 內的檔名清單,並建立負責更新圖片的 Handler:

private AssetManager assets = null;
private String[] images = null;
private int currentImg = 0;
private ImageView image;
private Button btnStart, btnStop;
private Handler handler = null;
private Thread thread = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    onInitView();
    images = getImages();
}

private String[] getImages() {
    String[] tempImages = null;
    try {
        assets = getAssets();
        if (null != assets) {
            tempImages = assets.list("");   // 列出 assets 根目錄下所有檔案
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        return tempImages;
    }
}

Handler 只負責比對訊息編號,真正的工作交給更新方法:

handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        if (msg.what == 0x110) {   // 確認是本程式發出的訊息
            dispalyNextImage();
        }
    }
};

播放與停止:用執行緒參照控制生命週期

按下開始鍵時建立子執行緒,每 100 毫秒送出一則訊息;停止時先把 thread 設為 null 再 interrupt,讓迴圈自然結束:

if (v == btnStart) {
    if (thread == null) {
        thread = new Thread() {
            @Override
            public void run() {
                Thread curThread = Thread.currentThread();
                while (thread != null && thread == curThread) {
                    try {
                        Thread.sleep(100);
                        Message msg = new Message();
                        msg.what = 0x110;
                        handler.sendMessage(msg);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
    }
} else if (v == btnStop) {
    Thread temp = thread;
    thread = null;
    temp.interrupt();
}

以「thread == curThread」作為迴圈條件是個實用技巧:停止時只要把 thread 指向 null,執行緒就會自行退出,不必強行砍掉它。

切換圖片與 Bitmap 回收

private void dispalyNextImage() {
    if (currentImg >= images.length) {
        currentImg = 0;
    }
    // assets 底下除了圖片,還有 images、sounds、webkit 等目錄,需跳過非圖片檔
    while (!images[currentImg].endsWith(".png")
            && !images[currentImg].endsWith(".jpg")
            && !images[currentImg].endsWith(".gif")) {
        currentImg++;
        if (currentImg >= images.length) {
            currentImg = 0;
        }
    }

    InputStream assetFile = null;
    try {
        assetFile = assets.open(images[currentImg++]);
    } catch (IOException e) {
        e.printStackTrace();
    }

    BitmapDrawable bitmapDrawable = (BitmapDrawable) image.getDrawable();
    // 上一張若尚未回收,先強制回收,避免記憶體不夠
    if (bitmapDrawable != null && !bitmapDrawable.getBitmap().isRecycled()) {
        bitmapDrawable.getBitmap().recycle();
    }
    image.setImageBitmap(BitmapFactory.decodeStream(assetFile));
}

兩個容易忽略的細節

關於副檔名過濾:assets 目錄並非只有圖片,若不過濾,一播放到 sounds 或 webkit 就會出錯。把 onCreate 中的 displayAssets() 打開執行一次,從 logcat 就能看清目錄裡實際有哪些項目。

關於 Bitmap 回收:手機可用記憶體本來就有限,若頻繁解析並建立 Bitmap,而先前建立的物件遲遲未被回收,很容易觸發 OutOfMemory。把上面 recycle 的那段註解掉再跑一次,通常只能播放數張(我在模擬器上第四張就掛了),錯誤訊息是:

INFO/ActivityManager(73): Low Memory: No more background processes.

這也說明了一件事:在行動裝置上,「能跑」和「跑得久」是兩道完全不同的門檻,記憶體管理往往就是那道看不見的分界線。

Copyright © Linux教程網 All Rights Reserved