导航

Android framework Handler\HandlerThread\Looper\Message\MessageQueue\

【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實例之後,將會出現什麼狀況呢???【可以用下面的代碼測試一下】

此段代碼摘自:http://blog.csdn.net/dengxiayehu
d、自己创建新的线程,然后在新线程中创建Looper,主线程调用子线程中的发消息方法,将消息发给子线程的消息队列。

Java代码 收藏代码

package com.dxyh.test;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class MainActivity extends Activity {
private final static String TAG = "HandlerTest";

private final static int TASK_BEGIN = 1;
private final static int TASK_1 = 2;
private final static int TASK_2 = 3;
private final static int TASK_END = 4;

private Handler workHandler = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Log.i(TAG, "[M_TID:" + Thread.currentThread().getId() + "]" +
"This is in main thread.");

LooperThread testThread = new LooperThread();
testThread.start();

// 注意,这里需要等待一下,防止出现空指针异常
while (null == workHandler) {
}

testThread.sendMessageTodoYourWork();
}

class LooperThread extends Thread {
@Override
public void run() {
Looper.prepare();

workHandler = new Handler() {
// 现在在每个case之后,你可以做任何耗时的操作了
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case TASK_BEGIN:
Log.i(TAG, "[H_TID:" +
Thread.currentThread().getId() + "] Get TASK_BEGIN");
break;

case TASK_1:
Log.i(TAG, "[H_TID:" +
Thread.currentThread().getId() + "] Get TASK_1");
break;

case TASK_2:
Log.i(TAG, "[H_TID:" +
Thread.currentThread().getId() + "] Get TASK_2");
break;

case TASK_END:
Log.i(TAG, "[H_TID:" +
Thread.currentThread().getId() + "] Get TASK_END");
Looper.myLooper().quit();
finish();
break;
}
super.handleMessage(msg);
}
};

Looper.loop();
}

public void sendMessageTodoYourWork() {
Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +
"Send TASK_START to handler.");
// 启动任务(消息只有标识,立即投递)
workHandler.sendEmptyMessage(TASK_BEGIN);

Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +
"Send TASK_1 to handler.");
// 开始任务1(在workHandler的消息队列中获取一个Message对象,避免重复构造)
Message msg1 = workHandler.obtainMessage(TASK_1);
msg1.obj = "This is task1";
workHandler.sendMessage(msg1);

Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +
"Send TASK_2 to handler.");
// 开启任务2(和上面类似)
Message msg2 = Message.obtain();
msg2.arg1 = 10;
msg2.arg2 = 20;
msg2.what = TASK_2;
workHandler.sendMessage(msg2);

Log.i(TAG, "[S_ID:" + Thread.currentThread().getId() + "]" +
"Send TASK_END to handler.");
// 结束任务(空消息体,延时2s投递)
workHandler.sendEmptyMessageDelayed(TASK_END, 2000);
}
}
}






 



 

 

posted on 2012-03-16 17:06  grass_dcm  阅读(951)  评论(0编辑  收藏

统计