1.消息队列仍绑定在主线程上,但在子线程中发送消息
此时可以在子线程中执行耗时操作,单因为handle是依附在主线程中的,所以handler的handleMessage方法中还是不能执行耗时操作
2.、将消息队列绑定到子线程上,主线程只管通过Handler往子线程的消息队列中投递消息即可。
此时通过
HandlerThread myLooperThread = new HandlerThread("my looper thread");
myLooperThread.start();
Looper looper = myLooperThread.getLooper();
mHandler = new MyHandler(looper);
HandlerThread实际上就一个Thread,只不过它比普通的Thread多了一个Looper。
创建HandlerThread时要把它启动了,即调用start()方法。然后创建Handler时将HandlerThread中的looper对象传入。
HandlerThread thread = new HandlerThread("MyHandlerThread");
thread.start();
mHandler = new Handler(thread.getLooper());
mHandler.post(new Runnable(){...});
那么这个Handler对象就是与HandlerThread这个线程绑定了(这时就不再是与UI线程绑定了,这样它处理耗时操作将不会阻塞UI)。