版權聲明:本文爲博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接和本聲明。
本文連接:https://blog.csdn.net/fnhfire_7030/article/details/79518819
前言:又到了一年一度的跳槽季,準備跳槽的你在關於Android面試方面的知識都徹底掌握了嗎?Android面試中常常被問到的知識——Android消息機制即Handler有關的問題你都能解釋的清楚嗎?若是你對Android消息機制比較模糊或者可以回答與Handler有關的問題可是不清楚其中的原理,那麼你將會在本文獲得你想要的答案。android
閱讀本文後的收貨
閱讀本文後你將會有如下收穫:面試
清楚的理解Handler的工做原理
理清Handler、Message、MessageQueue以及Looper之間的關係
知道Looper是怎麼和當前線程進行綁定的
是否能在子線程中建立Handler
得到分析Handler源碼的思路
要想有以上的收穫,就須要研究Handler的源碼,從源碼中來獲得答案。多線程
開始探索之路
Handler的使用
先從Handler的使用開始。咱們都知道Android的主線程不能處理耗時的任務,否者會致使ANR的出現,可是界面的更新又必需要在主線程中進行,這樣,咱們就必須在子線程中處理耗時的任務,而後在主線程中更新UI。可是,咱們怎麼知道子線程中的任務什麼時候完成,又應該何時更新UI,又更新什麼內容呢?爲了解決這個問題,Android爲咱們提供了一個消息機制即Handler。下面就看下Handler的常見使用方式,代碼以下併發
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mStartTask;less
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
Toast.makeText(MainActivity.this, "刷新UI、", Toast.LENGTH_SHORT).show();
}
}
};async
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}ide
private void initView() {
mStartTask = findViewById(R.id.btn_start_task);
mStartTask.setOnClickListener(this);
}函數
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start_task:
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
mHandler.sendEmptyMessage(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
break;
}
}
}工具
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
能夠看到在子線程中,讓線程睡了一秒,來模仿耗時的任務,當耗時任務處理完以後,Handler會發送一個消息,而後咱們能夠在Handler的handleMessage方法中獲得這個消息,獲得消息以後就可以在handleMessage方法中更新UI了,由於handleMessage是在主線程中嘛。到這裏就會有如下疑問了:oop
Handler明明是在子線程中發的消息怎麼會跑到主線程中了呢?
Handler的發送消息handleMessage又是怎麼接收到的呢?
帶着這兩個疑問,開始分析Handler的源碼。
Handler的源碼分析
先看下在咱們實例化Handler的時候,Handler的構造方法中都作了那些事情,看代碼
final Looper mLooper;
final MessageQueue mQueue;
final Callback mCallback;
final boolean mAsynchronous;
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*/
public Handler() {
this(null, false);
}
/**
* Use the {@link Looper} for the current thread with the specified callback interface
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
經過源碼能夠看到Handler的無參構造函數調用了兩個參數的構造函數,而在兩個參數的構造函數中就是將一些變量進行賦值。
看下下面的代碼
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
1
2
3
4
5
這裏是經過Looper中的myLooper方法來得到Looper實例的,若是Looper爲null的話就會拋異常,拋出的異常內容翻譯過來就是
沒法在未調用Looper.prepare()的線程內建立handler
從這句話中,咱們能夠知道,在調用Looper.myLooper()以前必需要先調用Looper.prepare()方法,如今來看下prepare方法中的內容,以下
/** 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 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));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
從上面代碼中能夠看到,prepare()方法調用了prepare(boolean quitAllowed)方法,prepare(boolean quitAllowed) 方法中則是實例化了一個Looper,而後將Looper設置進sThreadLocal中,到了這裏就有必要了解一下ThreadLocalle。
什麼是ThreadLocal
ThreadLocal 爲解決多線程程序的併發問題提供了一種新的思路。使用這個工具類能夠很簡潔地編寫出優美的多線程程序。當使用ThreadLocal 維護變量時,ThreadLocal 爲每一個使用該變量的線程提供獨立的變量副本,因此每個線程均可以獨立地改變本身的副本,而不會影響其它線程所對應的副本。
若是看完上面這段話仍是搞不明白ThreadLocal有什麼用,那麼能夠看下下面代碼運行的結果,相信看下結果你就會明白ThreadLocal有什麼做用了。
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ThreadLocal<Integer> mThreadLocal = new ThreadLocal<>();
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
Log.d(TAG, "onCreate: "+mThreadLocal.get());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mThreadLocal.set(5);
Thread1 thread1 = new Thread1();
thread1.start();
Thread2 thread2 = new Thread2();
thread2.start();
Thread3 thread3 = new Thread3();
thread3.start();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
mHandler.sendEmptyMessage(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
class Thread1 extends Thread {
@Override
public void run() {
super.run();
mThreadLocal.set(1);
Log.d(TAG, "mThreadLocal1: "+ mThreadLocal.get());
}
}
class Thread2 extends Thread {
@Override
public void run() {
super.run();
mThreadLocal.set(2);
Log.d(TAG, "mThreadLocal2: "+ mThreadLocal.get());
}
}
class Thread3 extends Thread {
@Override
public void run() {
super.run();
mThreadLocal.set(3);
Log.d(TAG, "mThreadLocal3: "+ mThreadLocal.get());
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
看下這段代碼運行以後打印的log
能夠看到雖然在不一樣的線程中對同一個mThreadLocal中的值進行了更改,但最後仍能夠正確拿到當前線程中mThreadLocal中的值。由此咱們能夠得出結論ThreadLocal.set方法設置的值是與當前線程進行綁定了的。
知道了ThreadLocal.set方法的做用,則Looper.prepare方法就是將Looper與當前線程進行綁定(當前線程就是調用Looper.prepare方法的線程)。
文章到了這裏咱們能夠知道如下幾點信息了
在對Handler進行實例化的時候,會對一些變量進行賦值。
對Looper進行賦值是經過Looper.myLooper方法,但在調用這句代碼以前必須已經調用了Looper.prepare方法。
Looper.prepare方法的做用就是將實例化的Looper與當前的線程進行綁定。
這裏就又出現了一個問題:在調用Looper.myLooper方法以前必須必須已經調用了Looper.prepare方法,即在實例化Handler以前就要調用Looper.prepare方法,可是咱們日常在主線程中使用Handler的時候並無調用Looper.prepare方法呀!這是怎麼回事呢?
其實,在主線程中Android系統已經幫咱們調用了Looper.prepare方法,能夠看下ActivityThread類中的main方法,代碼以下
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
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();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
上面的代碼中有一句
Looper.prepareMainLooper();
1
這句話的實質就是調用了Looper的prepare方法,代碼以下
public static void prepareMainLooper() {
prepare(false);//這裏調用了prepare方法
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
1
2
3
4
5
6
7
8
9
到這裏就解決了,爲何咱們在主線程中使用Handler以前沒有調用Looper.prepare方法的問題了。
讓咱們再回到Handler的構造方法中,看下
mLooper = Looper.myLooper();
1
myLooper()方法中代碼以下
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
1
2
3
4
5
6
7
其實就是從當前線程中的ThreadLocal中取出Looper實例。
再看下Handler的構造方法中的
mQueue = mLooper.mQueue;
1
這句代碼。這句代碼就是拿到Looper中的mQueue這個成員變量,而後再賦值給Handler中的mQueue,下面看下Looper中的代碼
final MessageQueue mQueue;
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
1
2
3
4
5
6
同過上面的代碼,咱們能夠知道mQueue就是MessageQueue,在咱們調用Looper.prepare方法時就將mQueue實例化了。
Handler的sendMessage方法都作了什麼
還記得文章開始時的兩個問題嗎?
Handler明明是在子線程中發的消息怎麼會跑到主線程中了呢?
Handler的發送消息handleMessage又是怎麼接收到的呢?
下面就分析一下Handler的sendMessage方法都作了什麼,看代碼
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* Time spent in deep sleep will add an additional delay to execution.
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
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);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
由上面的代碼能夠看出,Handler的sendMessage方法最後調用了sendMessageAtTime這個方法,其實,不管時sendMessage、sendEmptyMessage等方法最終都是調用sendMessageAtTime。能夠看到sendMessageAtTime這個方法最後返回的是*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);
}
1
2
3
4
5
6
7
這裏有一句代碼很是重要,
msg.target = this;
1
這句代碼就是將當前的Handler賦值給了Message中的target變量。這樣,就將每一個調用sendMessage方法的Handler與Message進行了綁定。
enqueueMessage方法最後返回的是**queue.enqueueMessage(msg, uptimeMillis);**也就是調用了MessageQueue中的enqueueMessage方法,下面看下MessageQueue中的enqueueMessage方法,代碼以下
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;
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;
}
}
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
上面的代碼就是將消息放進消息隊列中,若是消息已成功放入消息隊列,則返回true。失敗時返回false,而失敗的緣由一般是由於處理消息隊列正在退出。代碼分析到這裏能夠得出如下兩點結論了
Handler在sendMessage時會將本身設置給Message的target變量即將本身與發送的消息綁定。
Handler的sendMessage是將Message放入MessageQueue中。
到了這裏已經知道Handler的sendMessage是將消息放進MessageQueue中,那麼又是怎樣從MessageQueue中拿到消息的呢?想要知道答案請繼續閱讀。
怎樣從MessageQueue中獲取Message
在文章的前面,貼出了ActivityThread類中的main方法的代碼,不知道細心的你有沒有注意到,在main方法的結尾處調用了一句代碼
Looper.loop();
1
好了,如今能夠看看*Looper.loop();*這句代碼到底作了什麼了loop方法中的代碼以下
/**
* 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();//經過myLooper方法拿到與主線程綁定的Looper
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;//從Looper中獲得MessageQueue
// 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 (;;) {
//從消息隊列中不斷取出消息
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
//這句代碼是重點
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
上面的代碼,我已經進行了部分註釋,這裏有一句代碼很是重要
msg.target.dispatchMessage(msg);
1
執行到這句代碼,說明已經從消息隊列中拿到了消息,還記得msg.target嗎?就是Message中的target變量呀!也就是發送消息的那個Handler,因此這句代碼的本質就是調用了Handler中的dispatchMessage(msg)方法,代碼分析到這裏是否是有點小激動了呢!穩住!下面看下dispatchMessage(msg)這個方法,代碼以下
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
如今來一句句的來分析上面的代碼,先看下這句
if (msg.callback != null) {
handleCallback(msg);
}
1
2
3
msg.callback就是Runnable對象,當msg.callback不爲null時會調用 handleCallback(msg)方法,先來看下 handleCallback(msg)方法,代碼以下
private static void handleCallback(Message message) {
message.callback.run();
}
1
2
3
上面的代碼就是調用了Runnable的run方法。那什麼狀況下**if (msg.callback != null)**這個條件成立呢!還記得使用Handler的另外一種方法嗎?就是調用Handler的post方法呀!這裏說明一下,使用Handler實際上是有兩種方法的
使用Handler的sendMessage方法,最後在handleMessage(Message msg)方法中來處理消息。
使用Handler的post方法,最後在Runnable的run方法中來處理,代碼以下
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mTimeCycle,mStopCycle;
private Runnable mRunnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mTimeCycle = findViewById(R.id.btn_time_cycle);
mTimeCycle.setOnClickListener(this);
mStopCycle = findViewById(R.id.btn_stop_cycle);
mStopCycle.setOnClickListener(this);
mRunnable = new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "正在循環!!!", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(mRunnable, 1000);
}
};
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_time_cycle:
mHandler.post(mRunnable);
break;
case R.id.btn_stop_cycle:
mHandler.removeCallbacks(mRunnable);
break;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
第一種方法,咱們已經分析了,下面來分析一下第二種使用方式的原理,先看下Handler的post的方法作了什麼,代碼以下
/**
* Causes the Runnable r to be added to the message queue.
* The runnable will be run on the thread to which this handler is
* attached.
*
* @param r The Runnable that will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
由上面的代碼不難看出,post方法最終也是將Runnable封裝成消息,而後將消息放進MessageQueue中。下面繼續分析dispatchMessage方法中的代碼
else {
//if中的代碼實際上是和if (msg.callback != null) {handleCallback(msg);}
//原理差很少的,只不過mCallback是Handler中的成員變量。
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//當上面的條件都不成立時,就會調用這句代碼
handleMessage(msg);
}
1
2
3
4
5
6
7
8
9
10
11
上面的代碼就不分析了,我已經在代碼中進行了註釋,下面再看下**handleMessage(msg)**這個方法,代碼以下
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
1
2
3
4
5
其實,他就是一個空方法,具體的代碼讓咱們本身重寫這個方法進行處理。代碼分析到這裏,已經能夠給出下面問題的答案了。
Handler明明是在子線程中發的消息怎麼會跑到主線程中了呢?
Handler的發送消息handleMessage又是怎麼接收到的呢?
在子線程中Handler在發送消息的時候已經把本身與當前的message進行了綁定,在經過Looper.loop()開啓輪詢message的時候,當得到message的時候會調用 與之綁定的Handler的**handleMessage(Message msg)**方法,因爲Handler是在主線程建立的,因此天然就由子線程切換到了主線程。
總結
上面已經嗯將Handler的源碼分析了一遍,如今來進行一些總結:
一、Handler的工做原理
在使用Handler以前必需要調用Looper.prepare()這句代碼,這句代碼的做用是將Looper與當前的線程進行綁定,在實例化Handler的時候,經過Looper.myLooper()獲取Looper,而後再得到Looper中的MessageQueue。在子線程中調用Handler的sendMessage方法就是將Message放入MessageQueue中,而後調用Looper.loop()方法來從MessageQueue中取出Message,在取到Message的時候,執行 **msg.target.dispatchMessage(msg);**這句代碼,這句代碼就是從當前的Message中取出Handler而後執行Handler的handleMessage方法。
二、Handler、Message、MessageQueue以及Looper之間的關係
在介紹它們之間的關係以前,先說一下它們各自的做用。
Handler:負責發送和處理消息。
Message:用來攜帶須要的數據。
MessageQueue:消息隊列,隊列裏面的內容就是Message。
Looper:消息輪巡器,負責不停的從MessageQueue中取Message。
它們的關係以下圖(圖片來源於網上)
三、在子線程中使用Handler
在子線程中使用Handler的方式以下
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();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
上面的代碼來自官方的源碼。
結束語
本文將Handler的機制詳細講解了一遍,包括在面試中有關Handler的一些問題,在文章中也能找到答案。順便說下閱讀代碼應該注意的地方,在分析源碼以前應該知道你分析代碼的目的,就是你爲了獲得什麼答案而分析代碼;在分析代碼時切記要避輕就重,不要想着要搞懂每句代碼作了什麼,要找準大方向。文中的代碼已上傳到GitHub,能夠在這裏獲取,與Handler有關的源碼在我上傳的源碼的handler包中。
ps: 歷史文章中有乾貨哦!
轉載請註明出處:www.wizardev.cn ———————————————— 版權聲明:本文爲CSDN博主「wizardev」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接及本聲明。 原文連接:https://blog.csdn.net/fnhfire_7030/article/details/79518819