Android 訊息機制應用

來源:互聯網
上載者:User

Android 訊息機制應用

通過一個例子來熟悉下 Android 訊息機制的使用,這個例子中主線程中有一個EditText、ImageView 和一個 Button,在 EditText 中輸入圖片地址後,點擊 Button,主線程向後台線程發送訊息請求下載圖片,後台線程下載完圖片後向主線程發送訊息請求更新UI以顯示下載的圖片。通過這個例子一方面熟悉訊息機制過的使用,另一方面理解 Handler 的雙向傳遞。最終的效果如下:

主線程向後台線程發訊息

後台線程向主線程發訊息

樣本原始碼

布局檔案 res/layout/activity_main.xml

            

MainActivity 用於顯示介面,作為主線程,它接收和處理更新介面的訊息。

package com.wuhui.testhandler;import android.app.Activity;import android.graphics.Bitmap;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;/** * Created by Administrator on 2015/5/6. */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 Button.OnClickListener(){            @Override            public void onClick(View v) {                // 下載圖片                mDownloader.downloadImage(mEditText.getText().toString());            }        });    }}

Downloader 類是一個後台線程,其繼承自 HandlerThread 類,所以它具有訊息迴圈。Downloader類負責接收和處理下載圖片的訊息。

package com.wuhui.testhandler;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Handler;import android.os.HandlerThread;import android.os.Message;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by Administrator on 2015/5/6. */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();        // 建立當前線程的 Handler        mHandler = new Handler() {                    @Override            public void handleMessage(Message msg) {                super.handleMessage(msg);                String imageUrl = (String)msg.obj;                // 下載圖片                handleDownloadImage(imageUrl);            }        };    }    public void downloadImage(String imageUrl) {        /**         * 這裡沒有直接調用 handleDownloadImage 來下載圖片,而是發送訊息,         * 這樣做的好處是,如果連續有多張圖片要下載,該方法也可以立即返回,         * 由後台線程根據訊息佇列中的請求依次下載圖片。         * */        // 將下載圖片的訊息發送給當前線程的訊息佇列        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 = 0;            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 (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}

上面就是全部代碼了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.