Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop()
after calling this method, and end it by calling quit()
.
private Handler mHandler;//set/getprivate void createMQ() {new Thread("自定义"){public void run() {Looper.prepare();mHandler = new Handler() {//把mHander作为外层类的Field,供其他发送消息的对象引用。public void handleMessage(Message msg) {Log.i(Thread.currentThread().getName(), (String)msg.obj);}};Looper.loop();
}}.start();}
决定Handler处理哪个线程的消息队列MQ,是由new Handler构造函数决定的。Looper对象来自哪个线程,而不是Handler的创建位置。
Handler()无参构造的注释是:
Default constructor associates this handler with the queue for the current thread. If there isn't one, this handler won't be able to receive messages.
默认的构造函数关联了一个来自当前线程的队列(queue)。就是说,默认使用的主线程的MQ,也可显示引用:
new Handler(Looper.getMainLooper());
Looper的静态方法返回Main函数的Looper.
如果要使用自定义的一个消息队列,需要自己new,或者使用Looper.prepare()代码执行之后自动创建的一个MQ,它从属于该线程,使用Looper.getMyLooper():
new Handler(Looper.myLooper());//Use the provided queue instead of the default one.
使用looper对象的构造方法,使用提供的queue代替默认的主线程的MQ,参数是looper为什么说成是queue呢?因为queue从属于一个Looper对象,可以使用
Looper.myLooper().myQueue();获取到MQ对象。
测试:将Looper对象拿到,然后变成外层对象的变量,在外层对象创建一个Handler对象,将该Looper实例传给Handler构造函数,
启动测试,发现Handler所处理的线程在自定义线程中,这是因为Looper对象来自于自定义线程;而如果将Handler调用为无参函数,
那么显示来自于main函数。
这样使用自定义的线程对象就可以随时进行控制,暂停cancel之类的操作了。