主要用于异步处理: 存在于线程中
开启子线程:异步处理
主要接受子线程发送的数据,并用此数据配合主线程更新UI
···
//1.创建Handler对象
private Handler handler=new Handler(){
//2.重写handleMessage
public void handleMessage(android.os.Message msg) {
5.获取消息:
String data= msg.obj;
Toast.makeText(getApplicationContext(), data, 1).show();
tv.setText("这是Hander")
}
};
在子线程:
String s='你好';
3.创建消息对象
Messge message = new Message();
message.obj=data;
message.what=10086; //消息编号
4.发送消息
mHandler.sendMessage(message);
···
---------------------handler--------------------
···
switch (msg.what) {
case 10086:
String data2=(String) msg.obj;
tv.setText(data2);
break;
case 10087:
Integer data3=(Integer) msg.obj;
tv.setText(data3+"");
break;
default:
break;
}
···
··················子线程···························
···
new Thread(new Runnable() {
@Override
public void run() {
try {
//
Thread.sleep(3000);
String data="你好";
//4.创建Message
Message message = new Message();
message.obj=data;
message.what=10086;//编号
//3.发送消息
handler.sendMessage(message);
handler.sendEmptyMessage(10086);
handler.sendMessageDelayed(message, 2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
int data=12542;//主线程 先显示
Message message = new Message();
message.obj=data;
message.what=10087;
// //3.发送消息
handler.sendMessage(message);
···
*****************Handler****开启子线程***************************
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
// //2.重写handleMessage
// //获取消息
switch (msg.what) {
case 10086:
String data2=(String) msg.obj;
tv.setText(data2);
break;
case 10087:
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Integer data3=(Integer) msg.obj;
tv.setText(data3+"");
break;
default:
break;
}
};
};