一、源碼分析
1. 一般調(diào)用
mHandler.sendEmptyMessage(100);
2. Handler.java
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
3. MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
// 第一次添加數(shù)據(jù)到隊(duì)列中秒梳,或者當(dāng)前 msg 的時(shí)間小于 mMessages 的時(shí)間
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
// 把當(dāng)前 msg 插入到列表中
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
4.把消息都存到隊(duì)列里面去了幔崖,然后他們是怎么輪訓(xùn)的呢?(Looper.java)
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
// 不斷的從消息隊(duì)列里面取消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// 通過(guò) target 去 dispatchMessage 而 target 就是綁定的 Handler
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "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);
}
msg.recycleUnchecked();
}
}
5. 這個(gè)loop是什么時(shí)候調(diào)用的呢霎奢?我們看看ActivityThread的main方法(ActivityThread.java)
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
Process.setArgV0("<pre-initialized>");
// 初始化Looper
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
// 開(kāi)始輪訓(xùn)
Looper.loop();
}
6. 總結(jié)
- handler.sendMessage 其實(shí)只是把我們的 Message 加入了消息隊(duì)列益愈,隊(duì)列采用的是鏈表的方式梢灭,按照 when 也就是時(shí)間排序,然后再也沒(méi)干其他蒸其;
- Looper的loop一直輪訓(xùn)這個(gè)隊(duì)列敏释,這是一個(gè)死循環(huán),然后調(diào)用message的target枣接,就是我們寫(xiě)的Handler執(zhí)行dispatchMessage。
- 當(dāng)Laucher啟動(dòng)一個(gè)App的時(shí)候缺谴,首先會(huì)通過(guò)zygote Fork一個(gè)進(jìn)程但惶,然后進(jìn)程會(huì)執(zhí)行ActivityThread的main函數(shù)耳鸯,在main函數(shù)里面初始化looper,執(zhí)行l(wèi)oop膀曾。
二县爬、自己手寫(xiě)
1. Handler
public class Handler {
// 包含一個(gè)消息隊(duì)列
MessageQueue mQueue;
public Handler() {
//獲取looper 輪訓(xùn)器。在Activity啟動(dòng)的時(shí)候創(chuàng)建
Looper looper = Looper.myLooper();
if(looper == null){
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue= looper.mQueue;
}
public void sendMessage(Message message) {
sendMessageDelayed(message,0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, System.currentTimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
return queue.enqueueMessage(msg, uptimeMillis);
}
// 空方法并沒(méi)具體的實(shí)現(xiàn)
public void handleMessage(Message msg) {
}
}
2. Looper
public class Looper {
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static void prepare() {
sThreadLocal.set(new Looper());
}
MessageQueue mQueue;
public Looper() {
mQueue = new MessageQueue();
}
public static void loop() {
//無(wú)限輪訓(xùn) 獲取隊(duì)列里面的消息
Looper looper = myLooper();
for(;;){
MessageQueue queue = looper.mQueue;
Message message = queue.next();
if(message == null){
return;
}
message.target.handleMessage(message);
}
}
static Looper myLooper() {
return sThreadLocal.get();
}
}
3. MessageQueue
public class MessageQueue {
private Message mMessages;
// 按照時(shí)間排序插入
public boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
msg.when = when;
Message p = mMessages;
//按照when 的時(shí)間進(jìn)行排序插入
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
} else {
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
}
return true;
}
// 無(wú)限輪訓(xùn) 獲取下一個(gè)消息
public Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
for (;;) {
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = System.currentTimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message
// in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null);
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up
// when it is ready.
} else {
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
return msg;
}
} else {
}
if (pendingIdleHandlerCount <= 0) {
continue;
}
}
}
}
}
4. Message
public class Message {
public Object obj;
public Handler target;
public long when;
public Message next;
}
5. 因?yàn)長(zhǎng)ooper是在主線(xiàn)程中執(zhí)行的添谊,我們來(lái)寫(xiě)一個(gè)ActivityThread
public class ActivityThread {
final H mH = new H();
public void attach(boolean b) {
Activity mainActivity = new TestActivity();
mainActivity.onCreate();
// 通過(guò) Handler 去執(zhí)行Activity的生命周期
Message message = new Message();
message.obj = mainActivity;
mH.sendMessage(message);
}
private class H extends Handler {
public void handleMessage(Message msg) {
Activity mainActivity = (Activity) msg.obj;
mainActivity.onResume();
}
}
}
6. 模擬Activity
public class Activity {
public void onCreate(){
}
public void onResume(){
}
public TextView findViewById(int id){
return new TextView();
}
}
7. TestActivity
/**
* @author 512573717@qq.com
* @created 2018/8/23 下午7:08.
*/
public class TestActivity extends Activity {
private static final String TAG = "TestActivity";
private TextView mHTextView;
private Handler mHHandler = new Handler() {
@Override
public void handleMessage(Message message) {
Log.e(TAG, "當(dāng)前線(xiàn)程名稱(chēng)===="+Thread.currentThread().getName());
mHTextView.setText((CharSequence) message.obj);
}
};
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
mHTextView = findViewById(0x111111);
new Thread(new Runnable() {
@Override
public void run() {
// mHTextView.setText("I will be update !!!");
Log.e(TAG, "當(dāng)前線(xiàn)程名稱(chēng)==="+Thread.currentThread().getName());
try {
Thread.sleep(100);
Message msg = new Message();
msg.obj = "I will be update !!!";
mHHandler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
).start();
}
@Override
public void onResume() {
super.onResume();
Log.e(TAG, "onResume");
}
}
8. 模擬UI控件TextView
public class TextView {
private Thread mThread;
public TextView(){
mThread = Thread.currentThread();
}
public void setText(CharSequence text){
checkThread();
System.out.println("更新UI成功:"+text);
}
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new RuntimeException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
}
9. Client
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Looper.prepare();
ActivityThread thread = new ActivityThread();
thread.attach(false);
Looper.loop();
}
}
10 .打印結(jié)果
1945-1945/? E/TestActivity: onCreate
1945-1945/? E/TestActivity: onResume
1945-1957/? E/TestActivity: 當(dāng)前線(xiàn)程名稱(chēng)===Thread-161
1945-1945/demo.dhcc.com.handlerdemo E/TestActivity: 當(dāng)前線(xiàn)程名稱(chēng)====main
1945-1945/demo.dhcc.com.handlerdemo I/System.out: 更新UI成功:I will be update !!!
三财喳、面試相關(guān)問(wèn)題
1. 為什么不能再子線(xiàn)程里面創(chuàng)建Handler
new Thread(new Runnable() {
@Override
public void run() {
Handler handler=new Handler();
handler.sendMessage(Message.obtain());
}
}).start();
//
??這個(gè)時(shí)候會(huì)報(bào)錯(cuò)“Can't create handler inside thread that has not called Looper.prepare()”,查看源碼發(fā)現(xiàn)斩狱。
public Handler(Callback callback, boolean async) {
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 = callback;
mAsynchronous = async;
}
??修改代碼
Looper.prepare();
Handler handler=new Handler();
handler.sendMessage(Message.obtain());
Looper.loop();
??為什么這樣有可以
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
??為什么主線(xiàn)程的可以(ActivityThread.java)
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
Process.setArgV0("<pre-initialized>");
// 啟動(dòng)時(shí)已經(jīng)創(chuàng)建了
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
}
總結(jié)
?? 一個(gè)Looper對(duì)應(yīng)一個(gè)線(xiàn)程耳高。存放在ThreadLocal里面。Looper必須創(chuàng)建了才有消息隊(duì)列所踊。如果沒(méi)有消息隊(duì)列Message就沒(méi)地方存泌枪。所以必須先創(chuàng)建Looper。