【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();
// 注意,這裡需要等待一下,防止出現null 指標異常
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);
}
}
}