之间在上篇文章中介绍过了Android的异步消息处理机制,这里再进行一些补充,说下多线程中的消息处理以及HandlerThread的介绍,如果你还不是很了解handler的机制,可以先看看上篇文章
Android-异步消息处理机制(Handler,Looper,Message)
在上篇文章中开头说过我们平时在子线程中去更新ui的操作一般是通过handler来发送message的方式进行处理,但是其实还有几种更简便的方式来进行ui的操作:
1. Handler的post()方法
2. View的post()方法
3. Activity的runOnUiThread()方法
代码如下:
new Thread(
new Runnable() {
@Override
public void run() {
//1.普遍的方式
//发送消息
Message msg = Message. obtain() ;
msg. what = 111 ;
Bundle bundle= new Bundle() ;
bundle.putString( "huan" , "hello") ;
msg.setData(bundle) ;
mHandler.sendMessage(msg) ;
//2.post的方式
mHandler.post( new Runnable() {
@Override
public void run() {
//可以直接在这儿进行ui的更新
}
}) ;
//3.view.post方式
mTvHelloWord.post( new Runnable() {
@Override
public void run() {
//可以直接在这儿进行ui的更新
}
}) ;
//4.runOnUiThread方式
runOnUiThread( new Runnable() {
@Override
public void run() {
//可以直接在这儿进行ui的更新
}
}) ;
}
}).start() ;
@Override
public void run() {
//1.普遍的方式
//发送消息
Message msg = Message. obtain() ;
msg. what = 111 ;
Bundle bundle= new Bundle() ;
bundle.putString( "huan" , "hello") ;
msg.setData(bundle) ;
mHandler.sendMessage(msg) ;
//2.post的方式
mHandler.post( new Runnable() {
@Override
public void run() {
//可以直接在这儿进行ui的更新
}
}) ;
//3.view.post方式
mTvHelloWord.post( new Runnable() {
@Override
public void run() {
//可以直接在这儿进行ui的更新
}
}) ;
//4.runOnUiThread方式
runOnUiThread( new Runnable() {
@Override
public void run() {
//可以直接在这儿进行ui的更新
}
}) ;
}
}).start() ;
从代码中可以明显的看出,后面三种方式要简便的多,而且是一种比一种简便,都不需要通过Message 的创建去封装消息;第二种方式还需要使用handler作为载体,第三种方式需要使用view来作为载体,第四种方式直接用runOnUiThread方法即可。为什么可以这样写也能达到目的?进去看看知道了。
1⃣️先说下handler post方式的使用,我们不需要再去创建一个Message对象,把数据封装在Message中,然后在handler的callback中进行ui的操作,而是直接可以在run中进行操作。进入到post方法中:
public final boolean
post(Runnable r)
{
return sendMessageDelayed( getPostMessage(r) , 0) ;
}
{
return sendMessageDelayed( getPostMessage(r) , 0) ;
}
所噶,原来还是通过sendMessageDelayed(Message msg, long delayMillis)这个方法来进行操作的,并且将我们传入的runnable对象通过getPostMessage方法转为了一个Message;那我们再进入getPostMessage方法中一看应该就能明了了:
private static Message
getPostMessage(Runnable r) {
Message m = Message. obtain() ;
m. callback = r ;
return m ;
}
Message m = Message. obtain() ;
m. callback = r ;
return m ;
}
创建了一个消息,并把这个消息的callback设置为了我们传入的runnnable;还记得我们上篇文章说过的在Looper进行消息循环的时候,取出来的消息将会通过dispatchMessage这个方法进行处理:
public void
dispatchMessage(Message msg) {
if (msg. callback != null) {
handleCallback(msg) ;
} else {
if ( mCallback != null) {
if ( mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg) ;
}
}
if (msg. callback != null) {
handleCallback(msg) ;
} else {
if ( mCallback != null) {
if ( mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg) ;
}
}
首先判断的就是msg的callback是否为null,如果不为null就会执行handleCallback(msg):
private static void
handleCallback(Message message) {
message. callback.run() ;
}
message. callback.run() ;
}
直接调用了msg的runnable对象也就是我们一开始传给msg的runnable对象,瞬间就很清晰明了了。
2⃣️view.post方式
view.post方法和handler的写法几乎一致,看看它的里面实现了什么:
public boolean
post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo ;
if (attachInfo != null) {
return attachInfo. mHandler.post(action) ;
}
// Assume that post will succeed later
ViewRootImpl. getRunQueue().post(action) ;
return true;
}
final AttachInfo attachInfo = mAttachInfo ;
if (attachInfo != null) {
return attachInfo. mHandler.post(action) ;
}
// Assume that post will succeed later
ViewRootImpl. getRunQueue().post(action) ;
return true;
}
原来就是通过attachInfo获取到了handler,然后执行handler的post方法而已。换汤不换药。
3⃣️runOnUiThread方式
这个方法其实是属于Activity的方法,也就是只能在Activity中才能使用,代码如下:
public final void
runOnUiThread(Runnable action) {
if (Thread. currentThread() != mUiThread) {
mHandler.post(action) ;
} else {
action.run() ;
}
}
if (Thread. currentThread() != mUiThread) {
mHandler.post(action) ;
} else {
action.run() ;
}
}
首先判断了当前线程是否是ui线程,如果不是,就用handler post的方式;否则就直接run。
看完了这三种方式的源代码发现其实底层都是通过handler发送message 的方式来进行消息的处理;所以平时我们在开发android的过程中如果明白了handler的消息机制;那么这几种方法你都是可以任意使用的,哪种方便用哪种。
Looper和handler的同步关系:
接下来说下在多线程中handler和looper的处理;先模拟一个运行场景:
1主线程中开启一个线程1;线程1开启的时候会启动线程2;
2线程2启动后获取到Looper,并执行looper.loop ;
3将线程2中的looper对象赋值给线程1中的looper对象
4通过线程1中的looper对象,在主线程中创建一个hanlder对象;
5通过handler发送一个msg,请问这个msg是在哪个线程中收到这个消息并进行处理;
看下代码:
线程1:
public class LooperThread1
extends Thread {
/**
* 定义一个public的成员变量Looper
*/
public Looper myLooper = null;
/**
* 初始化Looper,开启消息循环
*/
public void initLooper(){
Looper. prepare() ;
myLooper = Looper. myLooper() ;
Looper. loop() ;
}
@Override
public void run() {
//开启另一个线程
Thread thread2 = new Thread( new Runnable() {
@Override
public void run() {
initLooper() ;
}
}) ;
thread2.start() ;
Log. e( "test" , "thread2 id:" + thread2.getId()) ;
}
}
/**
* 定义一个public的成员变量Looper
*/
public Looper myLooper = null;
/**
* 初始化Looper,开启消息循环
*/
public void initLooper(){
Looper. prepare() ;
myLooper = Looper. myLooper() ;
Looper. loop() ;
}
@Override
public void run() {
//开启另一个线程
Thread thread2 = new Thread( new Runnable() {
@Override
public void run() {
initLooper() ;
}
}) ;
thread2.start() ;
Log. e( "test" , "thread2 id:" + thread2.getId()) ;
}
}
主线程:
//主线程id
Log. e( "test" , "Main Thread:" + Thread. currentThread().getId()) ;
LooperThread1 myLooperThread1= new LooperThread1() ;
myLooperThread1.start() ;
//线程1 id
Log. e( "test" , "thread1 id:"+myLooperThread1.getId()) ;
Looper looper=myLooperThread1. myLooper ;
android.os.Handler handler= new android.os.Handler(looper , new android.os.Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if(msg. what== 111){
Log. e( "test" , "handleMessage :111") ;
//当前线程
Log. e( "test" , "current Thread:"+Thread. currentThread().getId()) ;
}
return false;
}
}) ;
handler.sendEmptyMessage( 111) ;
Log. e( "test" , "Main Thread:" + Thread. currentThread().getId()) ;
LooperThread1 myLooperThread1= new LooperThread1() ;
myLooperThread1.start() ;
//线程1 id
Log. e( "test" , "thread1 id:"+myLooperThread1.getId()) ;
Looper looper=myLooperThread1. myLooper ;
android.os.Handler handler= new android.os.Handler(looper , new android.os.Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if(msg. what== 111){
Log. e( "test" , "handleMessage :111") ;
//当前线程
Log. e( "test" , "current Thread:"+Thread. currentThread().getId()) ;
}
return false;
}
}) ;
handler.sendEmptyMessage( 111) ;
最开始我是为了验证这个handler发送的消息最终是在哪个线程中接收,但是其实这段代码是有问题的,一运行会报java.lang.NullPointerException。具体的原因就在与:创建handler的时候,传入的这个looper为空。我们在获取线程1的looper对象时,这个时候可能线程2还没有执行完获取到looper;所以问题就出在这儿;不过我们可以加一个同步锁的方式来解决,但是如果每次写你都去这样操作那不是很麻烦? 所以,android给我们推荐了一个 HandlerThread线程来解决多线程中handler和looper之间同步的问题。
HandlerThread中的源码:
@Override
public void run() {
mTid = Process. myTid() ;
Looper. prepare() ;
synchronized ( this) {
mLooper = Looper. myLooper() ;
notifyAll() ;
}
Process. setThreadPriority( mPriority) ;
onLooperPrepared() ;
Looper. loop() ;
mTid = - 1 ;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason is isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized ( this) {
while (isAlive() && mLooper == null) {
try {
wait() ;
} catch (InterruptedException e) {
}
}
}
return mLooper ;
}
public void run() {
mTid = Process. myTid() ;
Looper. prepare() ;
synchronized ( this) {
mLooper = Looper. myLooper() ;
notifyAll() ;
}
Process. setThreadPriority( mPriority) ;
onLooperPrepared() ;
Looper. loop() ;
mTid = - 1 ;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason is isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized ( this) {
while (isAlive() && mLooper == null) {
try {
wait() ;
} catch (InterruptedException e) {
}
}
}
return mLooper ;
}
其实就是加上了一个同步锁的机制,并且在run中自动帮我们创建好了looper;那么我们接下来再来验证下消息的处理是在哪个线程:
//主线程id
Log. e( "test" , "Main Thread:" + Thread. currentThread().getId()) ;
HandlerThread handlerThread = new HandlerThread( "handler_thread") ;
handlerThread.start() ;
Log. e( "test" , "HandlerThread:" + handlerThread.getId()) ;
android.os.Handler handler= new android.os.Handler(handlerThread.getLooper() , new android.os.Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if(msg. what== 222){
Log. e( "test" , "receiveMsh thread id:"+Thread. currentThread().getId()) ;
}
return false;
}
}) ;
handler.sendEmptyMessage( 222) ;
Log. e( "test" , "Main Thread:" + Thread. currentThread().getId()) ;
HandlerThread handlerThread = new HandlerThread( "handler_thread") ;
handlerThread.start() ;
Log. e( "test" , "HandlerThread:" + handlerThread.getId()) ;
android.os.Handler handler= new android.os.Handler(handlerThread.getLooper() , new android.os.Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if(msg. what== 222){
Log. e( "test" , "receiveMsh thread id:"+Thread. currentThread().getId()) ;
}
return false;
}
}) ;
handler.sendEmptyMessage( 222) ;
打印log为:
得出结论:handler发送的Message处理,不会依赖与创建handler时所在的线程,依赖与传入的looper对象所在的线程,looper所在的线程来执行msg的处理;
到这里,通过两篇文章总算是将handler这个知识点大部分总结完了;接下来会继续总结其他技术点的知识;如果文章有疏漏,错误,望君能给我评论指出。谢谢!