編輯:Android 技術基礎
本章我們先打基礎,好好認識一下 Handler、Message、Looper 這三兄弟的用法。理解它們如何搭配,是日後處理多線程與 UI 更新的關鍵一步。
打開 res/layout/activity_main.xml,放兩顆按鈕與一個文字元件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnmain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自主線程發送消息給自己" />
<Button
android:id="@+id/btnother"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自其它線程發送消息至主線程" />
<TextView
android:id="@+id/tvmsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
打開 src/com.genwoxue.handlemessageloop/MainActivity.java。這個例子示範兩種情境:主線程給自己發消息,以及子線程把消息送到主線程。
package com.genwoxue.handlemessageloop;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity{
private static long s=0;
private String TAG = "HandlerTest";
private ReceiveMessageThread receiveMessageThread =null;
private EventHandler mHandler = null;
private Button btnMain = null;
private Button btnOther = null;
private TextView tvMsg = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMain = (Button)super.findViewById(R.id.btnmain);
btnOther = (Button)super.findViewById(R.id.btnother);
tvMsg = (TextView)super.findViewById(R.id.tvmsg);
btnMain.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
//主線程發送消息給自己
Looper looper = Looper.myLooper(); //get the Main looper related with the main thread
//如果不給任何參數的話會用當前線程對應的Looper(這裡就是Main Looper)為Handler裡面的成員mLooper賦值
mHandler = new EventHandler(looper);
// 清除整個MessageQueue裡的消息
mHandler.removeMessages(0);
String obj = "This main thread's message and received by itself!";
Message msg = mHandler.obtainMessage(1,1,1,obj);
// 將Message對象送入到main thread的MessageQueue裡面
mHandler.sendMessage(msg);
}
});
btnOther.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
//other線程發送消息給主線程
receiveMessageThread = new ReceiveMessageThread();
receiveMessageThread.start();
}
});
}
class EventHandler extends Handler{
public EventHandler(Looper looper){
super(looper);
}
public EventHandler(){
super();
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e(TAG, "CurrentThread id:----------+>" + Thread.currentThread().getId());
switch(msg.what){
case 1:
tvMsg.setText((String)msg.obj);
break;
default:
Log.e(TAG,(String)msg.obj);
break;
}
}
}
//ReceiveMessageThread has his own message queue by execute Looper.prepare();
class ReceiveMessageThread extends Thread {
@Override
public void run(){
Looper.prepare();
Looper looper = Looper.getMainLooper();
mHandler = new EventHandler(looper);
mHandler.removeMessages(0);
s=s+1;
Message msg =new Message();
msg.what=1;
msg.obj=String.valueOf(s);
// 將Message對象送入到main thread的MessageQueue裡面
mHandler.sendMessage(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Looper.loop();
}
}
}
打開 AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.genwoxue.handlemessageloop"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.genwoxue.handlemessageloop.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
採用預設的 AndroidManifest.xml 即可,無須額外配置。
按下第一顆按鈕,主線程會給自己送出一則消息並在文字元件上顯示;按下第二顆按鈕,子線程則會每隔一秒把累加的數字送到主線程更新畫面。透過 LogCat 你還能觀察到 handleMessage() 究竟在哪條線程上被執行——這正是理解「消息在哪裡發、又在哪裡收」的最佳教材。


第60章、把資料寫進記憶卡再讀回來(從零開始學Android)
以檔案方式保存資料是最傳統、也最容易理解的做法。好消息是:Android 上的檔案讀寫寫法與 Java SE 的 I/O 幾乎完全一致,File、FileOutputSt
Android Service 入門:線程概念與生命週期
線程與 Service 的關係 學習 Service 前,先釐清幾個常見概念:程式是靜態的指令集合,進程是執行中的程式,線程則是進程中的執行單元。Service 是 An
Genymotion 模擬器安裝與使用:打造流暢 Android 測試環境
為什麼選擇 Genymotion若沒有真機,或覺得原生 AVD 啟動慢、運行不順,可以考慮 Genymotion。它在效能與操作流暢度上通常優於內建模擬器。下載與註冊前往
Android 佈局教學:GridLayout 網格佈局實作計算機按鍵盤
GridLayout 是 Android 4.0 之後加入的佈局管理器,用虛擬的細線把畫面切分成列、行與儲存格,還允許單一控件同時跨越多行多列。它的 API 和 Line