Handler可以将子线程的操作运送到主线程或反向
1.子线程发送数据到主线程
Message message = handler.obainMessage(); // Message message = Message.obtain();
message.obj = content; //obj可以放任何类型,可放Bundle传多条数据;arg1、arg2、what为int
handler.sendMessage(message);
handler.sendMessageDelayed(message, 3000);
handler.sendEmptyMessage(what);
handler.sendEmptyMessage(1, 1000);
接收方即为实例化Handler的地方(应先将Handler对象实例化才能使用)
handler = new Handler(){
public void handleMessage(Message msg) { //只有接收到数据才调用
super.handleMessage(msg);
String content = (String)msg.obj;
tv.setText(content);
}
}
2.主线程向子线程发送数据
//子线程
Looper.prepare();
handler = new Handler(){ ... };
Looper.loop();
3.在handleMessage(...){}里调用
if(what!=-1) {
handler.sendEmptyMessageDelayed(what, 1000);
}
实现自己给自己发消息,形成循环,但在这之前必须要发送一个消息触发该循环
4.
view.post(new Runnable(){ //view可以是任何控件或Handler对象
public void run() { tv.setText(result); }
});
5.封装工具类 HandlerNetUtils
a.
public class HandlerNetUtils{
private static Handler handler = new Handler();
public static void doNetwork(final String path, final DataCallback callback) {
...
final byte[] bytes = baos.toByteArray();
handler.post(new Runnable(){
public void run(){
callback.doData(bytes); //回调接口
}
});
}
}
b.
public class HandlerNetUtils{
public static void doNetwork(final String path, final Handler handler) {
...
final byte[] bytes = baos.toByteArray();
Message msg = Message.obtain();
msg.obj = bytes;
handler.sendMessage(msg);
}
}