Android Handler的消息传递机制
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;
}
}