Dialvik/ARP(ANDROID)中的多线程机制(2)

来源:互联网 发布:卷皮折扣和淘宝那个好 编辑:程序博客网 时间:2024/06/10 10:15

Android消息处理机制(二)

角色综述(回顾):

   (1)UI thread通常就是main thread,而Android启动程序时会替它建立一个MessageQueue。

(2)当然需要一个Looper对象,来管理该MessageQueue。

(3)我们可以构造Handler对象来push新消息到Message Queue里;或者接收Looper(从Message Queue取出)所送来的消息。

(4)线程A的Handler对象可以传递给别的线程,让别的线程B或C等能送讯息来给线程A(存于A的Message Queue里)。

(5)线程A的Message Queue里的消息,只有线程A所属的对象可以处理。

 

子线程传递消息给主线程

publicclass Activity2extends Activityimplements OnClickListener{

       Buttonbutton =null;

       TextViewtext =null;

       MyHandlermHandler =null;

       Threadthread ;

      @Override

      protectedvoid onCreate(Bundle savedInstanceState) {

             super.onCreate(savedInstanceState);

              setContentView(R.layout.activity1);        

             button = (Button)findViewById(R.id.btn);

             button.setOnClickListener(this);

             text = (TextView)findViewById(R.id.content);

       }

      publicvoid onClick(View v) {

             switch (v.getId()) {

             case R.id.btn:

                    thread =new MyThread();

                    thread.start();

                    break;

              }            

       }     

      privateclass MyHandlerextends Handler{             

             public MyHandler(Looper looper){

                    super(looper);

              }

             @Override

             publicvoid handleMessage(Message msg) {//处理消息

                    text.setText(msg.obj.toString());

              }            

       }

      privateclass MyThreadextends Thread{

             @Override

             publicvoid run() {

                     Looper curLooper = Looper.myLooper();

                     Looper mainLooper = Looper.getMainLooper();

                     String msg ;

                    if(curLooper==null){

                           mHandler =new MyHandler(mainLooper);

                            msg ="curLooper is null";

                     }else{

                           mHandler =new MyHandler(curLooper);

                            msg ="This is curLooper";

                     }

                    mHandler.removeMessages(0);

                     Message m =mHandler.obtainMessage(1, 1, 1, msg);

                    mHandler.sendMessage(m);

              }            

       }

}

说明:

Android会自动替主线程建立Message Queue。在这个子线程里并没有建立Message Queue。所以,myLooper值为null,而mainLooper则指向主线程里的Looper。于是,执行到:

mHandler = new MyHandler (mainLooper);

mHandler属于主线程。

   mHandler.sendMessage(m);

就将m消息存入到主线程的Message Queue里。mainLooper看到Message Queue里有讯息,就会作出处理,于是由主线程执行到mHandler的handleMessage()来处理消息。

用Android线程间通信的Message机制

在Android下面也有多线程的概念,在C/C++中,子线程可以是一个函数,一般都是一个带有循环的函数,来处理某些数据,优先线程只是一个复杂的运算过程,所以可能不需要while循环,运算完成,函数结束,线程就销毁。对于那些需要控制的线程,一般我们都是和互斥锁相互关联,从而来控制线程的进度,一般我们创建子线程,一种线程是很常见的,那就是带有消息循环的线程。
消息循环是一个很有用的线程方式,曾经自己用C在Linux下面实现一个消息循环的机制,往消息队列里添加数据,然后异步的等待消息的返回。当消息队列为空的时候就会挂起线程,等待新的消息的加入。这是一个很通用的机制。
在Android,这里的线程分为有消息循环的线程和没有消息循环的线程,有消息循环的线程一般都会有一个Looper,这个事android的新概念。我们的主线程(UI线程)就是一个消息循环的线程。针对这种消息循环的机制,我们引入一个新的机制Handle,我们有消息循环,就要往消息循环里面发送相应的消息,自定义消息一般都会有自己对应的处理,消息的发送和清除,消息的的处理,把这些都封装在Handle里面,注意Handle只是针对那些有Looper的线程,不管是UI线程还是子线程,只要你有Looper,我就可以往你的消息队列里面添加东西,并做相应的处理。
但是这里还有一点,就是只要是关于UI相关的东西,就不能放在子线程中,因为子线程是不能操作UI的,只能进行数据、系统等其他非UI的操作。
那么什么情况下面我们的子线程才能看做是一个有Looper的线程呢?我们如何得到它Looper的句柄呢?
Looper.myLooper();获得当前的Looper
Looper.getMainLooper () 获得UI线程的Lopper
我们看看Handle的初始化函数,如果没有参数,那么他就默认使用的是当前的Looper,如果有Looper参数,就是用对应的线程的Looper。
如果一个线程中调用Looper.prepare(),那么系统就会自动的为该线程建立一个消息队列,然后调用 Looper.loop();之后就进入了消息循环,这个之后就可以发消息、取消息、和处理消息。这个如何发送消息和如何处理消息可以再其他的线程中通过Handle来做,但前提是我们的Hanle知道这个子线程的Looper,但是你如果不是在子线程运行 Looper.myLooper(),一般是得不到子线程的looper的。
public void run() {
            synchronized (mLock) {
                Looper.prepare();
               //do something
            }
            Looper.loop();
        }
所以很多人都是这样做的:我直接在子线程中新建handle,然后在子线程中发送消息,这样的话就失去了我们多线程的意义了。
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,可以把 private EHandler mHandler ;放在外面,这样我们的发消息和处理消息都可以在外面来定义,这样增加程序代码的美观,结构更加清晰。
对如任何的Handle,里面必须要重载一个函数
public void handleMessage(Message msg)
这个函数就是我们的消息处理,如何处理,这里完全取决于你,然后通过 obtainMessage和 sendMessage等来生成和发送消息, removeMessages(0)来清除消息队列。Google真是太智慧了,这种框架的产生,我们写代码更加轻松了。
有的时候,我们的子线程想去改变UI了,这个时候千万不要再子线程中去修改,获得UI线程的Looper,然后发送消息即可。
我们看看Goole Music App的源代码。
在MediaPlaybackActivity.java中,我们可以看一下再OnCreate中的有这样的两句:
        mAlbumArtWorker = new Worker("album art worker");
        mAlbumArtHandler = new AlbumArtHandler(mAlbumArtWorker.getLooper());
很明显这两句,是构建了一个子线程。并且这个子线程还是Looper的子线程,这里很牛逼的使用了 mAlbumArtWorker.getLooper()这个函数,因为我们知道,我们能够得到子线程的Looper的途径只有一个:就是在子线程中调用 Looper.myLooper (),并且这个函数还要在我们perpare之后调用才能得到正确的Looper,但是他这里用了一个这样的什么东东 getLooper,不知道它是如何实现的?
这里有一个大概的思路,我们在子线程的的prepare之后调用 myLooper ()这个方法,然后保存在一个成员变量中,这个getLooper就返回这个东西,但是这里会碰到多线程的一个很突出的问题,同步。我们在父线程中调用 mAlbumArtWorker.getLooper(),但是想要这个返回正确的looper就必须要求我们的子线程运行了prepare,但是这个东西实在子线程运行的,我们如何保证呢?
我们看Google是如何实现的?
   private class Worker implements Runnable {
        private final Object mLock = new Object();
        private Looper mLooper;
        
        /**
         * Creates a worker thread with the given name. The thread
         * then runs a [email=%7B@link]{@link[/email] android.os.Looper}.
         * @param name A name for the new thread
         */
        Worker(String name) {
            Thread t = new Thread(null, this, name);
            t.setPriority(Thread.MIN_PRIORITY);
            t.start();
            synchronized (mLock) {
                while (mLooper == null) {
                    try {
                        mLock.wait();
                    } catch (InterruptedException ex) {
                    }
                }
            }
        }
        
        public Looper getLooper() {
            return mLooper;
        }
        
        public void run() {
            synchronized (mLock) {
                Looper.prepare();
                mLooper = Looper.myLooper();
                mLock.notifyAll();
            }
            Looper.loop();
        }
        
        public void quit() {
            mLooper.quit();
        }
    }
我们知道,一个线程类的构造函数是在主线程中完成的,所以在我们的 Worker的构造函数中我们创佳一个线程,然后让这个线程运行,这一这个线程的创建是指定一个 Runnabl,这里就是我们的Worker本身,在主线程调用 t.start();,这后,我们子线程已经创建,并且开始执行work的run方法。然后下面的代码很艺术:
synchronized (mLock) {
                while (mLooper == null) {
                    try {
                        mLock.wait();
                    } catch (InterruptedException ex) {
                    }
                }
            }
我们开始等待我们的子线程给mLooper赋值,如果不赋值我们就继续等,然后我们的子线程在运行run方法之后,在给 mLooper赋值之后,通知worker够着函数中的wait,然后我们的构造函数才能完成,所以我们说:
mAlbumArtWorker = new Worker("album art worker");
这句本身就是阻塞的,它创建了一个子线程,开启了子线程,并且等待子线程给mLooper赋值,赋值完成之后,这个函数才返回,这样才能保证我们的子线程的Looper的获取绝对是正确的,这个构思很有创意。值得借鉴

Android中Handler的使用方法——在子线程中更新界面

本文主要介绍Android的Handler的使用方法。Handler可以发送Messsage和Runnable对象到与其相关联的线程的消息队列。每个Handler对象与创建它的线程相关联,并且每个Handler对象只能与一个线程相关联。

1.    Handler一般有两种用途:1)执行计划任务,你可以再预定的实现执行某些任务,可以模拟定时器。2)线程间通信。在Android的应用启动时,会创建一个主线程,主线程会创建一个消息队列来处理各种消息。当你创建子线程时,你可以再你的子线程中拿到父线程中创建的Handler对象,就可以通过该对象向父线程的消息队列发送消息了。由于Android要求在UI线程中更新界面,因此,可以通过该方法在其它线程中更新界面。
◆ 通过Runnable在子线程中更新界面的例子

1.○ 在onCreate中创建Handler 
public class HandlerTestApp extends Activity { 
        Handler mHandler; 
        TextView mText; 
        /** Called when the activity is first created. */ 
       @Override 
       public void onCreate(Bundle savedInstanceState) { 
           super.onCreate(savedInstanceState); 
           setContentView(R.layout.main); 
           mHandler = new Handler();//创建Handler 
           mText = (TextView) findViewById(R.id.text0);//一个TextView 
       } 
     ○ 构建Runnable对象,在runnable中更新界面,此处,我们修改了TextView的文字.此处需要说明的是,Runnable对象可以再主线程中创建,也可以再子线程中创建。我们此处是在子线程中创建的。 
     Runnable mRunnable0 = new Runnable() 
    { 
                @Override 
                public void run() { 
                        mText.setText("This is Update from ohter thread, Mouse DOWN");
                } 
    }; 
?    ○ 创建子线程,在线程的run函数中,我们向主线程的消息队列发送了一个runnable来更新界面。

    private void updateUIByRunnable(){ 
          new Thread()  
         {  
               //Message msg = mHandler.obtainMessage();  
              public void run()  
             { 

                   //mText.setText("This is Update from ohter thread, Mouse DOWN");//这句将抛出异常
                   mHandler.post(mRunnable0);  
             }  
         }.start();

     }

◆ 用Message在子线程中来更新界面

1.    用Message更新界面与Runnable更新界面类似,只是需要修改几个地方。
    ○ 实现自己的Handler,对消息进行处理

    private class MyHandler extends Handler
    { 

        @Override 
        public void handleMessage(Message msg) { 
            super.handleMessage(msg); 
            switch(msg.what) 
            { 
            case UPDATE://在收到消息时,对界面进行更新 
                mText.setText("This update by message"); 
                break; 
            } 
        } 
    }

    ○ 在新的线程中发送消息     
    private void updateByMessage() 
    { 
        //匿名对象 
         new Thread() 
         { 
                public void run() 
                { 
                    //mText.setText("This is Update from ohter thread, Mouse DOWN");

                    //UPDATE是一个自己定义的整数,代表了消息ID 
                    Message msg = mHandler.obtainMessage(UPDATE);
                    mHandler.sendMessage(msg);
                } 
         }.start(); 
    }

 

--------------------------------------------------------华丽的分割线-------------------------------------------------------------

 

 

android的消息处理有三个核心类:Looper,Handler和Message。其实还有一个Message Queue(消息队列),但是MQ被封装到Looper里面了,我们不会直接与MQ打交道,因此我没将其作为核心类。下面一一介绍:

线程的魔法师 Looper

Looper的字面意思是“循环者”,它被设计用来使一个普通线程变成Looper线程。所谓Looper线程就是循环工作的线程。在程序开发中(尤其是GUI开发中),我们经常会需要一个线程不断循环,一旦有新任务则执行,执行完继续等待下一个任务,这就是Looper线程。使用Looper类创建Looper线程很简单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<pre name="code" class="java">public class LooperThread extends Thread { 
   
 @Override 
public void run() { 
        // 将当前线程初始化为Looper线程  
        Looper.prepare(); 
        // ...其他处理,如实例化handler  
        // 开始循环处理消息队列  
        Looper.loop(); 
    
 
<pre name="code" class="java">public class LooperThread extends Thread {
 
 @Override
public void run() {
        // 将当前线程初始化为Looper线程
        Looper.prepare();
        // ...其他处理,如实例化handler
        // 开始循环处理消息队列
        Looper.loop();
    }
}

  

通过上面两行核心代码,你的线程就升级为Looper线程了!!!是不是很神奇?让我们放慢镜头,看看这两行代码各自做了什么。

1)Looper.prepare()

通过上图可以看到,现在你的线程中有一个Looper对象,它的内部维护了一个消息队列MQ。注意,一个Thread只能有一个Looper对象,为什么呢?咱们来看源码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class Looper { 
    // 每个线程中的Looper对象其实是一个ThreadLocal,即线程本地存储(TLS)对象  
    private static final ThreadLocal sThreadLocal = new ThreadLocal(); 
   
    // Looper内的消息队列  
    final MessageQueue mQueue; 
   
    // 当前线程  
    Thread mThread; 
   
    // 。。。其他属性  
   
    // 每个Looper对象中有它的消息队列,和它所属的线程  
    private Looper() { 
        mQueue = new MessageQueue(); 
        mRun = true
        mThread = Thread.currentThread(); 
    
   
    // 我们调用该方法会在调用线程的TLS中创建Looper对象  
    public static final void prepare() { 
        if (sThreadLocal.get() != null) { 
            // 试图在有Looper的线程中再次创建Looper将抛出异常  
            throw new RuntimeException("Only one Looper may be created per thread"); 
        
        sThreadLocal.set(new Looper()); 
    
    // 其他方法  
 
public class Looper {
    // 每个线程中的Looper对象其实是一个ThreadLocal,即线程本地存储(TLS)对象
    private static final ThreadLocal sThreadLocal = new ThreadLocal();
 
    // Looper内的消息队列
    final MessageQueue mQueue;
 
    // 当前线程
    Thread mThread;
 
    // 。。。其他属性
 
    // 每个Looper对象中有它的消息队列,和它所属的线程
    private Looper() {
        mQueue = new MessageQueue();
        mRun = true;
        mThread = Thread.currentThread();
    }
 
    // 我们调用该方法会在调用线程的TLS中创建Looper对象
    public static final void prepare() {
        if (sThreadLocal.get() != null) {
            // 试图在有Looper的线程中再次创建Looper将抛出异常
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
    }
    // 其他方法
}

  

通过源码,prepare()背后的工作方式一目了然,其核心就是将looper对象定义为ThreadLocal。如果你还不清楚什么是ThreadLocal,请参考《理解ThreadLocal》。

2)Looper.loop()

调用loop方法后,Looper线程就开始真正工作了,它不断从自己的MQ中取出队头的消息(也叫任务)执行。其源码分析如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public static final void loop() { 
        Looper me = myLooper();  //得到当前线程Looper  
        MessageQueue queue = me.mQueue;  //得到当前looper的MQ  
        // 这两行没看懂= = 不过不影响理解  
        Binder.clearCallingIdentity(); 
   
        final long ident = Binder.clearCallingIdentity(); 
   
        // 开始循环  
        while (true) { 
            Message msg = queue.next(); // 取出message  
            if (msg != null) { 
                if (msg.target == null) { 
                    // message没有target为结束信号,退出循环  
                    return
                
                // 日志。。。  
                if (me.mLogging!= null) me.mLogging.println( 
                        ">>>>> Dispatching to " + msg.target + " " 
                        + msg.callback + ": " + msg.what 
                        ); 
                // 非常重要!将真正的处理工作交给message的target,即后面要讲的handler  
                msg.target.dispatchMessage(msg); 
                // 还是日志。。。  
                if (me.mLogging!= null) me.mLogging.println( 
                        "<<<<< Finished to    " + msg.target + " " 
                        + msg.callback); 
                                // 下面没看懂,同样不影响理解  
                final long newIdent = Binder.clearCallingIdentity(); 
                if (ident != newIdent) { 
                    Log.wtf("Looper""Thread identity changed from 0x" 
                            + Long.toHexString(ident) + " to 0x" 
                            + Long.toHexString(newIdent) + " while dispatching to " 
                            + msg.target.getClass().getName() + " "+ msg.callback + " what=" + msg.what); 
                
                // 回收message资源  
                msg.recycle(); 
            
        
    
 
public static final void loop() {
        Looper me = myLooper();  //得到当前线程Looper
        MessageQueue queue = me.mQueue;  //得到当前looper的MQ
        // 这两行没看懂= = 不过不影响理解
        Binder.clearCallingIdentity();
 
        final long ident = Binder.clearCallingIdentity();
 
        // 开始循环
        while (true) {
            Message msg = queue.next(); // 取出message
            if (msg != null) {
                if (msg.target == null) {
                    // message没有target为结束信号,退出循环
                    return;
                }
                // 日志。。。
                if (me.mLogging!= null) me.mLogging.println(
                        ">>>>> Dispatching to " + msg.target + " "
                        + msg.callback + ": " + msg.what
                        );
                // 非常重要!将真正的处理工作交给message的target,即后面要讲的handler
                msg.target.dispatchMessage(msg);
                // 还是日志。。。
                if (me.mLogging!= null) me.mLogging.println(
                        "<<<<< Finished to    " + msg.target + " "
                        + msg.callback);
                                // 下面没看懂,同样不影响理解
                final long newIdent = Binder.clearCallingIdentity();
                if (ident != newIdent) {
                    Log.wtf("Looper""Thread identity changed from 0x"
                            + Long.toHexString(ident) + " to 0x"
                            + Long.toHexString(newIdent) + " while dispatching to "
                            + msg.target.getClass().getName() + " "+ msg.callback + " what=" + msg.what);
                }
                // 回收message资源
                msg.recycle();
            }
        }
    }

  

除了prepare()和loop()方法,Looper类还提供了一些有用的方法,比如

Looper.myLooper()得到当前线程looper对象:

1
2
3
4
public static final Looper myLooper() { 
        // 在任意线程调用Looper.myLooper()返回的都是那个线程的looper  
        return (Looper)sThreadLocal.get(); 

  getThread()得到looper对象所属线程:

1
2
3
public Thread getThread() { 
        return mThread; 

  quit()方法结束looper循环:

1
2
3
4
5
6
7
8
9
10
11
12
13
public void quit() { 
        // 创建一个空的message,它的target为NULL,表示结束循环消息  
        Message msg = Message.obtain(); 
        // 发出消息  
        mQueue.enqueueMessage(msg, 0); 
 
public void quit() {
        // 创建一个空的message,它的target为NULL,表示结束循环消息
        Message msg = Message.obtain();
        // 发出消息
        mQueue.enqueueMessage(msg, 0);
}

  

到此为止,你应该对Looper有了基本的了解,总结几点:

1.每个线程有且最多只能有一个Looper对象,它是一个ThreadLocal

2.Looper内部有一个消息队列,loop()方法调用后线程开始不断从队列中取出消息执行

3.Looper使一个线程变成Looper线程。

那么,我们如何往MQ上添加消息呢?下面有请Handler!(掌声~~~)

异步处理大师 Handler

什么是handler?handler扮演了往MQ上添加消息和处理消息的角色(只处理由自己发出的消息),即通知MQ它要执行一个任务(sendMessage),并在loop到自己的时候执行该任务(handleMessage),整个过程是异步的。handler创建时会关联一个looper,默认的构造方法将关联当前线程的looper,不过这也是可以set的。默认的构造方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class handler { 
    final MessageQueue mQueue;  // 关联的MQ  
   
    final Looper mLooper;  // 关联的looper  
   
    final Callback mCallback;  
   
    // 其他属性  
   
    public Handler() { 
        // 没看懂,直接略过,,,  
        if (FIND_POTENTIAL_LEAKS) { 
            final Class<? extends Handler> klass = getClass(); 
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && 
                    (klass.getModifiers() & Modifier.STATIC) == 0) { 
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " 
                    klass.getCanonicalName()); 
            
        
        // 默认将关联当前线程的looper  
        mLooper = Looper.myLooper(); 
        // looper不能为空,即该默认的构造方法只能在looper线程中使用  
        if (mLooper == null) { 
            throw new RuntimeException( 
                "Can't create handler inside thread that has not called Looper.prepare()"); 
        
        // 重要!!!直接把关联looper的MQ作为自己的MQ,因此它的消息将发送到关联looper的MQ上  
        mQueue = mLooper.mQueue; 
        mCallback = null
    
    // 其他方法  
 
public class handler {
    final MessageQueue mQueue;  // 关联的MQ
 
    final Looper mLooper;  // 关联的looper
 
    final Callback mCallback;
 
    // 其他属性
 
    public Handler() {
        // 没看懂,直接略过,,,
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }
        // 默认将关联当前线程的looper
        mLooper = Looper.myLooper();
        // looper不能为空,即该默认的构造方法只能在looper线程中使用
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        // 重要!!!直接把关联looper的MQ作为自己的MQ,因此它的消息将发送到关联looper的MQ上
        mQueue = mLooper.mQueue;
        mCallback = null;
    }
    // 其他方法
}

  下面我们就可以为之前的LooperThread类加入Handler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class LooperThread extends Thread { 
    private Handler handler1; 
   
    private Handler handler2; 
   
    @Override 
    public void run() { 
        // 将当前线程初始化为Looper线程  
        Looper.prepare(); 
        // 实例化两个handler  
        handler1 = new Handler(); 
        handler2 = new Handler(); 
        // 开始循环处理消息队列  
        Looper.loop(); 
    
 
public class LooperThread extends Thread {
    private Handler handler1;
 
    private Handler handler2;
 
    @Override
    public void run() {
        // 将当前线程初始化为Looper线程
        Looper.prepare();
        // 实例化两个handler
        handler1 = new Handler();
        handler2 = new Handler();
        // 开始循环处理消息队列
        Looper.loop();
    }
}

  

加入handler后的效果如下图:

可以看到,一个线程可以有多个Handler,但是只能有一个Looper!

Handler发送消息

有了handler之后,我们就可以使用 post(Runnable),postAtTime(Runnable, long),postDelayed(Runnable, long),sendEmptyMessage(int),sendMessage(Message),sendMessageAtTime(Message, long)sendMessageDelayed(Message, long)这些方法向MQ上发送消息了。光看这些API你可能会觉得handler能发两种消息,一种是Runnable对象,一种是message对象,这是直观的理解,但其实post发出的Runnable对象最后都被封装成message对象了,见源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<pre name="code" class="java"><span style="color:#000000;">public final boolean post(Runnable r) 
    // 注意getPostMessage(r)将runnable封装成message  
    return  sendMessageDelayed(getPostMessage(r), 0); 
   
private final Message getPostMessage(Runnable r) { 
   
     Message m = Message.obtain();  //得到空的message  
     m.callback = r;  //将runnable设为message的callback  
     return m; 
   
public boolean sendMessageAtTime(Message msg, long uptimeMillis) 
     boolean sent = false
     MessageQueue queue = mQueue; 
     if (queue != null) { 
         msg.target = this;  // message的target必须设为该handler!  
         sent = queue.enqueueMessage(msg, uptimeMillis); 
     
     else 
         RuntimeException e = new RuntimeException( 
             this " sendMessageAtTime() called with no mQueue"); 
         Log.w("Looper", e.getMessage(), e); 
      
      return sent; 
}</span> 
 
<pre name="code" class="java"><span style="color:#000000;">public final boolean post(Runnable r)
{
    // 注意getPostMessage(r)将runnable封装成message
    return  sendMessageDelayed(getPostMessage(r), 0);
}
 
private final Message getPostMessage(Runnable r) {
 
     Message m = Message.obtain();  //得到空的message
     m.callback = r;  //将runnable设为message的callback
     return m;
}
 
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
     boolean sent = false;
     MessageQueue queue = mQueue;
     if (queue != null) {
         msg.target = this;  // message的target必须设为该handler!
         sent = queue.enqueueMessage(msg, uptimeMillis);
     }
     else {
         RuntimeException e = new RuntimeException(
             this " sendMessageAtTime() called with no mQueue");
         Log.w("Looper", e.getMessage(), e);
      }
      return sent;
}</span>

  

其他方法就不罗列了,总之通过handler发出的message有如下特点:

1.message.target为该handler对象,这确保了looper执行到该message时能找到处理它的handler,即loop()方法中的关键代码

msg.target.dispatchMessage(msg);

2.post发出的message,其callback为Runnable对象

Handler处理消息

说完了消息的发送,再来看下handler如何处理消息。消息的处理是通过核心方法dispatchMessage(Message msg)与钩子方法handleMessage(Messagemsg)完成的,见源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 处理消息,该方法由looper调用  
public void dispatchMessage(Message msg) { 
    if (msg.callback != null) { 
        // 如果message设置了callback,即runnable消息,处理callback!  
        handleCallback(msg); 
    else 
        // 如果handler本身设置了callback,则执行callback  
        if (mCallback != null) { 
             /* 这种方法允许让activity等来实现Handler.Callback接口,避免了自己编写handler重写handleMessage方法。见http://alex-yang-xiansoftware-com.iteye.com/blog/850865 */ 
            if (mCallback.handleMessage(msg)) { 
                return
            
        
        // 如果message没有callback,则调用handler的钩子方法handleMessage  
        handleMessage(msg); 
    
   
    // 处理runnable消息  
private final void handleCallback(Message message) { 
    message.callback.run();  //直接调用run方法!  
   
// 由子类实现的钩子方法  
public void handleMessage(Message msg) { 
 
    // 处理消息,该方法由looper调用
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            // 如果message设置了callback,即runnable消息,处理callback!
            handleCallback(msg);
        else {
            // 如果handler本身设置了callback,则执行callback
            if (mCallback != null) {
                 /* 这种方法允许让activity等来实现Handler.Callback接口,避免了自己编写handler重写handleMessage方法。见http://alex-yang-xiansoftware-com.iteye.com/blog/850865 */
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            // 如果message没有callback,则调用handler的钩子方法handleMessage
            handleMessage(msg);
        }
    }
 
        // 处理runnable消息
    private final void handleCallback(Message message) {
        message.callback.run();  //直接调用run方法!
    }
 
    // 由子类实现的钩子方法
    public void handleMessage(Message msg) {
    }

  

可以看到,除了handleMessage(Message msg)和Runnable对象的run方法由开发者实现外(实现具体逻辑),handler的内部工作机制对开发者是透明的。这正是handler API设计的精妙之处!

Handler的用处

我在小标题中将handler描述为“异步处理大师”,这归功于Handler拥有下面两个重要的特点:

1.handler可以在任意线程发送消息,这些消息会被添加到关联的MQ上。

              

2.handler是在它关联的looper线程中处理消息的。

这就解决了android最经典的不能在其他非主线程中更新UI的问题。android的主线程也是一个looper线程(looper在android中运用很广),我们在其中创建的handler默认将关联主线程MQ。因此,利用handler的一个solution就是在activity中创建handler并将其引用传递给worker thread,worker thread执行完任务后使用handler发送消息通知activity更新UI。(过程如图)

当然,handler能做的远远不仅如此,由于它能post Runnable对象,它还能与Looper配合实现经典的Pipeline Thread(流水线线程)模式。请参考此文《Android Guts: Intro to Loopers and Handlers》