Handler類的只要作用有兩個:
1. 在新啟動的線程中發送消息;2. 在主線程中獲取、處理消息。
看上去,Handler的機制很簡單。讀者不免會問:新啟動的線程何時發送消息?主線程何時去獲取並處理消息?
為了能讓主線程“適時”地處理新啟動的線程所發送的消息,顯然只能通過回調的方式來實現:開發者只要重寫Handler類的處理消息的方法,這樣,在新啟動的線程發送消息時Handler類中處理消息的方法被自動調用。
Handler類包含如下方法用於發送、處理消息。
1. void handleMessage(Message msg):處理消息方法,該方法通常用於被重寫;
2. final boolean hasMessages(int what):檢查消息隊列中是否包含what屬性為指定值的消息;
3. final boolean hasMessage(int what, Object object):檢查消息隊列中是否包含what屬性為指定值且Object屬性為指定對象的消息;
4. Message obtainMessage():獲取消息;
5. sendEmptyMessage(int what):發送空消息;
6. final boolean sendEmptyMessageDelayed(int what, long delayMillis):指定多少毫秒後發送空消息:
7. final boolean sendMessage(Message msg):立即發送消息;
8. final boolean sendMessageDelayed(Message msg, long delayMillis):指定多少毫秒之後發送消。
HandlerDemo:
布局文件:activity_main.xml
<RelativeLayout xmlns:Android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<ImageView
android:id="@+id/imgv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
Java代碼:MainActivity.java
package com.zsl.handlerdemo;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static int[] pic = new int [] {
R.drawable.jay1,
R.drawable.jay2,
R.drawable.jay3,
R.drawable.jay4
};
private static int curPicId = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView show = (ImageView)findViewById(R.id.imgv);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what == 13) {
show.setImageResource(pic[curPicId]);
curPicId = (curPicId + 1) % pic.length;
}
}
};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = new Message();
msg.what = 13;
handler.sendMessage(msg);
}
}, 0, 1000);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}