关于handler的使用和理解

对于handler的使用和理解:
handler的创建 :
Hander handler=new handler();
在这里要注意一点:
new handler() 会检测当前线程是否有looper 如果没有looper 则会报错弹出异常
所以在子线程使用new handler的时候 我们需要调用Loop.prepare()创建looper 代码如下:

Handler handler;
new Runable(){
run(){
Loop.prepare(); //调用这句话创建looper
handler=new handler();
}
}
但在主线程中使用new handler()的时候 并不会报错,那是因为主线程在创建的时候会调用Loop.parpareMainLooper();
所以主线程中是包含有looper的,只是我们看不见

接下来是消息的发送和处理
Message msg=Message.obtain(); //获取一个message对象
我们可以使用msg对象附加一些信息比如:
Bundle bundle=new Bundle();
bundle.putString("data","data");
msg.setData(bundle);

handler.sendMessage(msg);//将消息发送

原文地址:https://www.cnblogs.com/dingzb/p/5233632.html