android Looper类

    Android中的Looper类,该类为一个线程维护一个消息队列,用于android线程中进行消息处理。消息并不是直接加入MessageQueue,而是通过与Looper对象关联MessageQueue.IdleHandler对象添加的

    调用Looper.myQueue方法可以获取当前线程的MessageQueue,MessageQueue通常附属于某一个创建它的线程

    Looper类用来为一个线程开启一个消息循环。默认情况下android中新诞生的线程是没有开启消息循环的。主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环。Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。 Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。

    通常是通过Handler对象来与Looper进行交互的。Handler可看做是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。默认情况下Handler会与其被定义时所在线程的Looper绑定,比如,Handler在主线程中定义,那么它是与主线程的Looper绑定。mainHandler = new Handler() 等价于new Handler(Looper.myLooper()).
Looper.myLooper():获取当前进程的looper对象,类似的 Looper.getMainLooper() 用于获取主线程的Looper对象。

    在非主线程中直接new Handler() 会报如下的错误: E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught  exception  E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。

    Looper.loop(); 让Looper开始工作,从消息队列里取消息,处理消息。

    注意:写在Looper.loop()之后的代码不会被执行,这个函数内部应该是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。

 

01.public class Looper {  
02.    private static final boolean DEBUG = false;  
03.    private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;  
04.  
05.    // sThreadLocal.get() will return null unless you've called prepare().   
06.    private static final ThreadLocal sThreadLocal = new ThreadLocal();  
07.  
08.    final MessageQueue mQueue;  
09.    volatile boolean mRun;  
10.    Thread mThread;  
11.    private Printer mLogging = null;  
12.    private static Looper mMainLooper = null;  
13.     /** Initialize the current thread as a looper. 
14.      * This gives you a chance to create handlers that then reference 
15.      * this looper, before actually starting the loop. Be sure to call 
16.      * {@link #loop()} after calling this method, and end it by calling 
17.      * {@link #quit()}. 
18.      */  
19.    public static final void prepare() {  
20.        if (sThreadLocal.get() != null) {  
21.            throw new RuntimeException("Only one Looper may be created per thread");  
22.        }  
23.        sThreadLocal.set(new Looper());  
24.}  
25./** Initialize the current thread as a looper, marking it as an application's main  
26.     *  looper. The main looper for your application is created by the Android environment, 
27.     *  so you should never need to call this function yourself. 
28.     * {@link #prepare()} 
29.     */  
30.       
31.    public static final void prepareMainLooper() {  
32.        prepare();  
33.        setMainLooper(myLooper());  
34.        if (Process.supportsProcesses()) {  
35.            myLooper().mQueue.mQuitAllowed = false;  
36.        }  
37.    }  
38.  
39.  
40.    private synchronized static void setMainLooper(Looper looper) {  
41.        mMainLooper = looper;  
42.    }  
43.      
44.    /** Returns the application's main looper, which lives in the main thread of the application. 
45.     */  
46.    public synchronized static final Looper getMainLooper() {  
47.        return mMainLooper;  
48.    }  
49.public static final void loop() {  
50.        Looper me = myLooper();  
51.        MessageQueue queue = me.mQueue;  
52.        while (true) {  
53.            Message msg = queue.next(); // might block   
54.            if (msg != null) {  
55.                if (msg.target == null) {  
56.                    return;  
57.                }  
58.                if (me.mLogging!= null) me.mLogging.println(  
59.                        ">>>>> Dispatching to " + msg.target + " "  
60.                        + msg.callback + ": " + msg.what  
61.                        );  
62.                msg.target.dispatchMessage(msg);  
63.                if (me.mLogging!= null) me.mLogging.println(  
64.                        "<<<<< Finished to    " + msg.target + " "  
65.                        + msg.callback);  
66.                msg.recycle();  
67.            }  
68.        }  
69.    }  
70./** 
71.     * Return the Looper object associated with the current thread.  Returns 
72.     * null if the calling thread is not associated with a Looper. 
73.     */  
74.    public static final Looper myLooper() {  
75.        return (Looper)sThreadLocal.get();  
76.    } 

  

你可能感兴趣的:(Looper 消息队列)