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

Android 消息機制的實際應用:Handler 雙向通信

編輯:關於 Android 程式設計

本文透過一個完整示例來熟悉 Android 消息機制的使用。示例中主線程有一個 EditText、一個 ImageView 和一個 Button:使用者在 EditText 中輸入圖片地址後點擊 Button,主線程向後台線程發送消息請求下載圖片;後台線程下載完成後,再向主線程發送消息請求更新 UI 以顯示圖片。透過這個例子,既能熟悉消息機制的用法,也能理解 Handler 的雙向傳遞。最終效果如下:

布局文件 res/layout/activity_main.xml

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <EditText
        android:id="@+id/edittext_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download Image" />
    <ImageView
        android:id="@+id/imageview_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="center" />
</LinearLayout>

MainActivity(主線程)

MainActivity 負責顯示界面,作為主線程,它接收並處理更新界面的消息:

 public class MainActivity extends Activity {
    private EditText mEditText;
    private Button mButton;
    private ImageView mImageView;
    private Downloader mDownloader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.edittext_url);
        mImageView = (ImageView) findViewById(R.id.imageview_image);

        // 創建與主線程關聯的 Handler,並作為構造參數傳給 Downloader
        mDownloader = new Downloader(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case Downloader.MESSAGE_DOWNLOAD:
                        if (msg.obj != null) {
                            Bitmap bitmap = (Bitmap) msg.obj;
                            mImageView.setImageBitmap(bitmap); // 更新圖片
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        mDownloader.start();        // 啟動後台線程
        mDownloader.getLooper();    // 確保消息循環初始化

        mButton = (Button) findViewById(R.id.button_download);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDownloader.downloadImage(mEditText.getText().toString());
            }
        });
    }
}

Downloader(後台線程)

Downloader 是一個後台線程,繼承自 HandlerThread,因此具備消息循環。它負責接收和處理下載圖片的消息:

 public class Downloader extends HandlerThread {
    private static final String mName = "Downloader";
    public static final int MESSAGE_DOWNLOAD = 1;
    private Handler mHandler;          // 當前線程的 Handler
    private Handler mResponseHandler;  // 主線程的 Handler

    Downloader(Handler handler) {
        super(mName);
        mResponseHandler = handler; // 保存主線程的 Handler
    }

    // 該函數在消息循環開始前被調用
    @Override
    protected void onLooperPrepared() {
        super.onLooperPrepared();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String imageUrl = (String) msg.obj;
                handleDownloadImage(imageUrl);
            }
        };
    }

    public void downloadImage(String imageUrl) {
        // 發送消息而非直接下載,可支持連續多張圖片依次下載
        mHandler.obtainMessage(MESSAGE_DOWNLOAD, imageUrl).sendToTarget();
    }

    private void handleDownloadImage(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection =
                    (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) return;
            InputStream in = connection.getInputStream();
            byte[] buffer = new byte[512];
            int readSize;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((readSize = in.read(buffer)) > 0) {
                out.write(buffer, 0, readSize);
            }
            out.close();
            byte[] bitmapBytes = out.toByteArray();
            Bitmap bitmap = BitmapFactory.decodeByteArray(
                    bitmapBytes, 0, bitmapBytes.length);
            // 向主線程發送消息,將下載的圖片作為消息參數
            mResponseHandler.obtainMessage(MESSAGE_DOWNLOAD, bitmap)
                    .sendToTarget();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

這個示例清晰地展現了 Handler 雙向通信的精髓:主線程透過 mDownloader.downloadImage() 向後台線程的 Handler 發送下載消息,後台線程下載完成後又透過 mResponseHandler 向主線程發送帶有 Bitmap 的消息,最終由主線程安全地更新 UI。這正是 Android 消息機制在多線程協作中的典型應用。

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