【Looper和Handler類分析】

就應用程序而言,Android系統中Java的應用程序和其他系統上相同,都是靠消息驅動來工作的,他們大致的工作原理如下:

a.有一個消息隊列,可以往這個消息隊列中投遞消息。

b.有一個消息循環,不斷從消息隊列中取出消息,然後處理。

 

在Android系統中,這些工作主要由Looper和Handler來實現:

a.Looper類,用於封裝消息循環,並且有一個消息隊列。

b.Handler類,有點像輔助類,它封裝了消息投遞、消息處理等接口。

Looper類是其中的關鍵。

 

通過分析會發現,Looper的作用是:

a.封裝了一個消息隊列。

b.Looper的prepare函數把這個Looper和調用prepare的線程(也就是最終的處理線程)綁定在一起了。

c.處理線程調用loop函數,處理來自該消息隊列的消息。

 

Looper、Message和Handler的關係

Looper、Message和Handler之間也存在曖昧關係:用兩句話就可以說清除:

a.Looper中有一個Message隊列,裡面存儲的是一個個待處理的Message。

b.Message中有一個Handler,這個Handler是用來處理Message的。

 

Handler把Message的target設為自己,是因為Handler除了封裝消息添加等功能外還封裝了消息處理的接口。

==================================Looper Used Sample ==============================

  * <p>This is a typical example of the implementation of a Looper thread,
  * using the separation of {@link #prepare} and {@link #loop} to create an
  * initial Handler to communicate with the Looper.
  *
  * <pre>
  *  class LooperThread extends Thread {
  *      public Handler mHandler;
  *      
  *      public void run() {
  *          Looper.prepare();
  *          
  *          mHandler = new Handler() {
  *              public void handleMessage(Message msg) {
  *                  // process incoming messages here
  *              }
  *          };
  *          
  *          Looper.loop();
  *      }
  *  }</pre>

================================== HandlerThread ==================================

    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;
    }

 

================================== Resource Code ==================================

私有化的Looper:

 

    private Looper() {
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}

 

Looper的實例化:

     /** 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
* {
@link #loop()} after calling this method, and end it by calling
* {
@link #quit()}.
*/
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}

Looper循環:

    /** Returns the application's main looper, which lives in the main thread of the application.
*/
public synchronized static final Looper getMainLooper() {
return mMainLooper;
}
/**
* Run the message queue in this thread. Be sure to call
* {
@link #quit()} to end the loop.
*/
public static final void loop() {
Looper me = myLooper();
MessageQueue queue = me.mQueue;
while (true) {
Message msg = queue.next(); // might block
//if (!me.mRun) {
// break;
//}
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
}
if (me.mLogging!= null) me.mLogging.println(
">>>>> Dispatching to " + msg.target + " "
+ msg.callback + ": " + msg.what
);
msg.target.dispatchMessage(msg);
if (me.mLogging!= null) me.mLogging.println(
"<<<<< Finished to " + msg.target + " "
+ msg.callback);
msg.recycle();
}
}
}
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static final Looper myLooper() {
return (Looper)sThreadLocal.get();
}
    public void quit() {
Message msg = Message.obtain();
// NOTE: By enqueueing directly into the message queue, the
// message is left with a null target. This is how we know it is
// a quit message.
mQueue.enqueueMessage(msg, 0);
}

 

通過下面的代碼,我們可以了解到,Handler的實例應在Looper實例之後。

    /**
* 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.
*/
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());
}
}

mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = null;
}

 

如果我們將Looper.prepare()放在Handler實例之後,將會出現什麼狀況呢???【可以用下面的代碼測試一下】






 



 

 

相关文章:

  • 2021-05-24
  • 2021-05-26
  • 2021-12-13
  • 2021-09-28
  • 2021-06-05
  • 2022-01-17
  • 2022-12-23
  • 2021-08-22
猜你喜欢
  • 2021-04-30
  • 2022-12-23
  • 2021-07-29
  • 2022-02-05
  • 2021-05-16
  • 2021-05-04
相关资源
相似解决方案