異步通信,消息傳遞
public class HandlerActivity extends AppCompatActivity {
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(HandlerActivity.this, "接收到了消息", Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler);
}
public void onClickView(View v) {
switch (v.getId()) {
case R.id.button: {
Thread thread = new Thread() {
@Override
public void run() {
Message msg = Message.obtain();
handler.sendMessage(msg);
}
};
thread.start();
break;
}
}
}
}
這個界面只有一個Button, 點擊事件是:啟動一個線程,在這個線程里使用handler,發(fā)送一個消息;這個消息不帶任何數據。
Message: 這個可以使用new來生成,但是最好還是使用Message.obtain()來獲取一個實例。這樣便于消息池的管理。
handler初始化的時候,我們復寫了handleMessage方法,這個方法用來接收,子線程中發(fā)過來的消息。
創(chuàng)新互聯(lián)憑借在網站建設、網站推廣領域領先的技術能力和多年的行業(yè)經驗,為客戶提供超值的營銷型網站建設服務,我們始終認為:好的營銷型網站就是好的業(yè)務員。我們已成功為企業(yè)單位、個人等客戶提供了成都做網站、網站制作服務,以良好的商業(yè)信譽,完善的服務及深厚的技術力量處于同行領先地位。
public class HandlerActivity extends AppCompatActivity {
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d("child", "----" + Thread.currentThread().getName());
}
};
Handler childHandler = null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler);
Thread child = new Thread("child thread") {
@Override
public void run() {
Looper.prepare();
childHandler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
Log.d("child", "----" + Thread.currentThread().getName() + ", " + msg.obj);
}
};
Looper.loop();
}
};
child.start();
}
public void onClickView(View v) {
switch (v.getId()) {
case R.id.button: {
Thread thread = new Thread() {
@Override
public void run() {
Message msg = Message.obtain();
handler.sendMessage(msg);
}
};
thread.start();
break;
}
case R.id.button1: {
if (childHandler != null) {
Message msg = Message.obtain(childHandler);
msg.obj = "123---" + SystemClock.uptimeMillis();
childHandler.sendMessage(msg);
} else {
Log.d("-----", "onClickView: child Handler is null");
}
break;
}
}
}
}
主線程向子線程發(fā)送消息時,我們需要使用的是handler,但是這個handler是需要在子線程中實例化,否則子線程無法接收到消息。
在child thread中準備的工作:
Looper.loop()調用
假如我們直接在子線程中直接實例化一個handler,而不傳入Looper實例。程序會直接拋出異常:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
這個異常是在hanlder源碼:
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;
}
出現(xiàn)的,從這里可知,在線程中實例化一個handler需要一個Looper實例。
首先看Looper源碼中是怎么寫的。Looper的構造方法是私有的,這樣我們只能通過Looper的靜態(tài)方法來實例化一個Looper.在Looper類中還有一個ThreadLocal
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
這個方法返回了一個存放在ThreadLocal
Looper.prepare源碼:
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));
}
方法很簡單,就是檢查sThreadLocal里面是否有有值,然后將Looper的實例存放到ThreadLocal,如果不為空,直接就是 RuntimeException 異常。這也保證了一個線程中只能有一個Looper實例。因此,Looper.prepare方法只能調用一次。
在這個程序中,可以大概理解成線程間數據的隔離。意思就是我存放在ThreadLocal中的數據,只能在我本線程中可以獲得到值,在其他線程中獲取不到(其他線程中獲取的是null)。
這樣就能得出,其他線程中的Looper,在本線程中通過Looper.myLooper()獲取不到數據。
通過查找Android源碼,可以知道在ActivityThread中main方法里面,UI線程已經初始化了Looper.prepareMainLooper();這樣就在UI線程中有Looper實例了。當然在main方法的下面,也調用了Looper.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 (;;) {**
**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();
**}**
}
這個方法里面,我們需要注意到:
msg.target.dispatchMessage(msg);
for循環(huán)是一個死循環(huán),這個需要一直取出MessageQueue隊列中的數據,也就是剛才所列的第三個 queue.next方法。這個方法會阻塞,直到有消息從消息隊列中取出來。
next方法源碼:
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
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 && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
Handler 通過sendMessage方法發(fā)送消息。這個方法最終調用的是
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
參數:MessageQueue queue則是Handler中mQueue變量,這個變量在Handler(Callback callback, boolean async)初始化完成。它是Looper中一個final MessageQueue的變量,在初始化Looper的時候,就開始初始化MessageQueue。這也是一個線程中只有一個MessageQueue的原因.
Message msg 是封裝的消息。
long uptimeMillis 延遲發(fā)送時間。
之前分析looper.loop方法的時候,說了msg.target.dispatchMessage, 這個target就是在這個方法里面賦值的。
從這個方法里面,可以知道handler的sendMessage,只是把消息(Message實例)添加到了queue隊列中。
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;
}
通過handler發(fā)送Message,將Message壓入MessageQueue隊列中;而Looper.loop方法又在不停的循環(huán)這個消息隊列,取出壓入MessageQueue的Message, 然后dispatchMessage分發(fā),最終會調用handler.handleMessage方法來處理發(fā)送過來的Message.