悠悠途恩
通过Handler类,可以提交和处理Message对象和Runnable对象,这里介绍Message对象。
在Android中,线程分为有消息循环的线程和没有消息循环的线程,线程默认没有消息循环。
有消息循环的线程一般都会有一个Looper,这个是android中的新概念。主线程(UI线程)就是一个消息循环的线程。
针对这种消息循环的机制,就要用到Handler,因为Handler可以传递Message对象。
如果要在线程中运行消息循环。必须在线程中先调用prepare()创建一个运行循环;然后调用loop()处理消息直到循环结束。
有消息循环,就要往消息循环里面发送相应的消息,自定义消息一般都会有自己对应的处理,消息的发送和清除,消息的处理,把这些都封装在Handler里面,
注意:Handler只是针对那些有Looper的线程,不管是UI线程还是子线程,只要你有Looper,我就可以往你的消息队列里面添加东西,并做相应的处理。
注意:只要是关于UI相关的东西,就不能放在子线程中,因为子线程是不能操作UI的,只能进行数据、系统等其他非UI的操作。
在有消息循环的线程中,如何得到Looper的句柄呢?
Looper.myLooper();//获得当前的Looper
Looper.getMainLooper () //获得UI线程的Lopper
我们看看Handle的初始化函数,如果没有参数,那么他就默认使用的是当前的Looper,如果有Looper参数,就是用对应的线程的Looper。
如果一个线程中调用Looper.prepare(),那么系统就会自动的为该线程建立一个消息队列,然后调用 Looper.loop();之后就进入了消息循环,这个之后就可以发消息、取消息、和处理消息。这个如何发送消息和如何处理消息可以再其他的线程中通过Handler来做,但前提是我们的Handle知道这个子线程的Looper,但是你如果不是在子线程运行 Looper.myLooper(),一般是得不到子线程的looper的。
看下面的代码:
class MyThread extends Thread{
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
很多人都像上面这样直接在子线程中新建handler,然后在子线程中发送消息,这样是不对的,失去了多线程的意义。
应该让其他的线程(主线程)来控制我们的handler,把 private EHandler mHandler ;放在run方法外面,
这样我们的发消息和处理消息都可以在外面来定义,这样增加程序代码的美观,结构更加清晰。
class MyThread extends Thread{
private EHandler mHandler ;
public void run() {
Looper myLooper, mainLooper;
myLooper = Looper.myLooper ();
mainLooper = Looper.getMainLooper ();
String obj;
if (myLooper == null ){
mHandler = new EHandler(mainLooper);
obj = “current thread has no looper!” ;
}
else {
mHandler = new EHandler(myLooper);
obj = “This is from current thread.” ;
}
mHandler .removeMessages(0);
Message m = mHandler .obtainMessage(1, 1, 1, obj);
mHandler .sendMessage(m);
}
}
对任何的Handle,里面必须要重载一个函数
public void handleMessage(Message msg)
这个函数就是我们的接受消息处理,
在需要发送消息的地方,先通过 obtainMessage获取Message对象,如,myMessage = mHandler.obtainMessage();
并设置信息,如,
myMessage.what=ok;
myMessage.arg1=1;
然后通过sendMessage等发送消息,给Handler的处理函数handleMessage(Message msg)去处理。
其中removeMessages(0)来清除消息队列。
我们的子线程想去改变UI了,这个时候千万不要再子线程中去修改,获得UI线程的Looper,然后发送消息即可。