Android 4.0开始后对网络操作等不能再主线程中进行操作,只能在子线程中进行操作。而且子线程不能更新视图,只能在主线程中进行操作。
1.主线程中定义handler
private Handler handler = new Handler();
{
public void handlermessage(andorid.os.Message.msg)
{}
}
2.创建一个子线程
new Thread(){public void run(){
}}
3.通过handler发送消息
new Thread(){public void run(){
Messager msg = new Messager();
msg.obj = "";
handler.sendmessager(msg);
}}
4.接收
private Handler handler = new Handler();
{
public void handlermessage(andorid.os.Message.msg)
{
String content = (String)msg.obj;
}
}
5.msg进行标识分别
msg.what
new Thread(){public void run(){
Messager msg = new Messager();
msg.what=1;
msg.obj = "";
handler.sendmessager(msg);
}}
6.根据msg.what标识符来进行不同的处理
private Handler handler = new Handler();
{
public void handlermessage(andorid.os.Message.msg)
{
switch(msg.what)
{
case 1:
String content = (String)msg.obj;
tv_result.settext(content);
break;
}
default:
{
break;
}
}
}
也可以在子线程中直接使用runOnUiThead那就不用创建handler了
runOnUiThead(new runable(){
public void run(){
}
})