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



<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 負責顯示界面,作為主線程,它接收並處理更新界面的消息:
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 是一個後台線程,繼承自 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 消息機制在多線程協作中的典型應用。
Android 高仿滑動驗證碼:自定義 Path、摳圖與動畫實現
效果目標滑動驗證碼常見於需要基本防機器人的情境。使用者需拖動滑塊,使驗證碼拼圖對齊指定位置。若在 Android 中自行實作,可以透過自定義 View 完成繪製、拖曳、驗
觀察者模式在Android開發中的應用:Java源碼深度分析(一)
對於觀察者,很多開發者並不陌生,它在日常開發中是一個非常常見的設計模式,尤其是 Android 開發者——很多人知道 broadcast 就是典型的觀察者模式,而近期火熱
Android Preference 元件完整實作教學
Preference 主要用來存放配置類資料——那些使用者上次點選的內容,我們希望下次啟動應用時仍然有效,不必讓使用者重新設定一遍。Android 提供 Preferen
Android 自定義 View 實現音頻條形圖動畫
這是一個模擬音頻輸出的條形圖。由於重點在自定義 View 的繪製邏輯,這裡不去真實讀取音頻振幅,而是用隨機數模擬數據變化。 第一步:畫出靜態的矩形序列 實現思路很直白: