1. 程式人生 > >Android非同步訊息機制

Android非同步訊息機制

Android的非同步訊息機制在Android系統中的重要性讀者應該都很清楚,無論是在平時開發中,還是筆試、面試中,這方面的內容都是無法避免的。Android提供了Handler和Looper來滿足執行緒間通訊,而MessageQueue則是用來存放執行緒放入的訊息。下面我們就結合原始碼分析一下這三者的關係。

(1)Handler的基本使用方式:

public class MainActivity extends AppCompatActivity {

    private MyTextView title;

    private static final String TAG = MainActivity.class.getSimpleName();

    private static final int HANDLER1 = 1;

    /**
     * 在主執行緒中定義Handler,並實現對應的handleMessage方法
     */
    public static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == HANDLER1) {
                Log.i(TAG, "接收到handler訊息...");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        title = (MyTextView) findViewById(R.id.title);
        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        // 在子執行緒中傳送非同步訊息
                        mHandler.sendEmptyMessage(HANDLER1);
                    }
                }.start();
            }
        });
    }
}

相信上面的用法大家都很熟悉,但現在有個問題,如果想把Handler放到子執行緒中使用,是怎麼樣子的呢?下面我們看一段程式碼。

public class MainActivity extends AppCompatActivity {

    private MyTextView title;

    private static final String TAG = MainActivity.class.getSimpleName();

    private static final int HANDLER1 = 1;

    /**
     * 在主執行緒中定義Handler,並實現對應的handleMessage方法
     */

    Handler mHandler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        title = (MyTextView) findViewById(R.id.title);
        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.sendEmptyMessage(HANDLER1);
            }
        });
        new Thread() {
            @Override
            public void run() {
                // 在子執行緒中傳送非同步訊息
                mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == HANDLER1) {
                            Log.i(TAG, "接收到handler訊息...");
                        }
                    }
                };
            }
        }.start();
    }

}

點選按鈕執行後會報下面的錯。

E/AndroidRuntime: FATAL EXCEPTION: Thread-95
              Process: com.eyck.androidsample, PID: 2552
              java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                  at android.os.Handler.<init>(Handler.java:200)
                  at android.os.Handler.<init>(Handler.java:114)
                  at com.eyck.androidsample.MainActivity$2$1.<init>(MainActivity.java:0)
                  at com.eyck.androidsample.MainActivity$2.run(MainActivity.java:41)

根據提示資訊我們可以很清晰的看到,在初始化Handler物件之前需要先呼叫Looper.prepare()方法,那麼我們就加上這句程式碼再執行一次。

new Thread() {
            @Override
            public void run() {
                // 在子執行緒中傳送非同步訊息
                Looper.prepare();
                mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == HANDLER1) {
                            Log.i(TAG, "接收到handler訊息...");
                        }
                    }
                };
                Looper.loop();
            }
        }.start();

這次執行就不會報錯了,說明程式在初始化Handler之前需要呼叫Looper.prepare(),那麼主執行緒為什麼能直接初始化Handler?相信有的讀者已經想到,是不是在初始化主執行緒時系統已經幫我們,我們來到應用程式的入口,在APP初始化時會執行ActivityThread的main()方法:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, “ActivityThreadMain”);
SamplingProfilerIntegration.start();

    // 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());

    AndroidKeyStoreProvider.install();

    // 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");
}

可以看到這裡呼叫了Looper.prepareMainLooper();和Looper.loop();兩個方法。接下來我們看一下Handler的原始碼。

首先就是Looper.prepareMainLooper();

public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

可以看到在prepareMainLooper()中呼叫了prepare(false);方法。

接下來看一下Looper.prepare();
public static void prepare() {
prepare(true);
}

可以看到,上面兩個方法都呼叫了prepare(boolean quitAllowed);那接下來我們就來看一下這個方法。

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));
}

可以看到Looper中有一個ThreadLocal的成員變數,關於ThreadLocal在這裡不做詳細說明,它的主要作用是為每個使用該變數的執行緒提供一個獨立的變數副本,所以每一個執行緒都可以獨立的改變自己的副本,而不會影響其他執行緒所對應的副本。而且從中我們也可以看出在每個執行緒中Looper.prepare()只能呼叫一次,不然就會丟擲”Only one Looper may be created per thread”異常。

接下來我們繼續看new Looper(quitAllowed);

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

可以清楚的看到在構造方法中,初始化了一個MessageQueue物件,以及獲取了當前的執行緒。

按著程式碼的順序,接下來我們看一下Handler的構造方法

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;
}

在Handler的構造方法中,主要對一些相關的變數進行初始化。我們再看一下mLooper = Looper.myLooper();這句程式碼

public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

通過上面的程式碼我們可以清晰看到Looper.myLooper();就是從sThreadLocal中得到我們之前儲存的Looper物件,這樣就和前面的sThreadLocal.set(new Looper(quitAllowed));聯絡起來了。

接下來我們再看一下sendEmptyMessage();

在Handler中有這麼幾個方法:

sendMessage(Message msg);
sendEmptyMessage(int what);
sendMessageDelayed(msg, 0);
sendEmptyMessageDelayed(what, 0);

最後都呼叫了sendMessageAtTime(Message msg, long uptimeMillis)這個方法

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);
}

接下來來到enqueueMessage(queue, msg, uptimeMillis);

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;//this==handler==msg.target
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

可以看到這裡的msg.target就是Handler物件,queue物件就是我們的Handler內部維護的Looper物件關聯的MessageQueue物件。

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;
}

可以看到這裡Message.next按照時間將所有的Message連線起來。

接下來繼續看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 traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        try {
            msg.target.dispatchMessage(msg);
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }

        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();
    }
}

這一段程式碼中有一個for的死迴圈,在死迴圈中不斷獲取MessageQueue中的訊息,Message msg = queue.next(); // might block,接下來如果獲取到不為空的訊息,就會呼叫msg.target.dispatchMessage(msg);進行訊息的分發,我們在前面已經介紹過msg.target就是一個Handler物件,也就是接下來就會呼叫Handler中的dispatchMessage(msg);

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

可以清晰的看到,這裡呼叫了handleMessage(msg);,這個方法不正是我們在MainActivity裡面呼叫的回撥介面嗎?

關於Android非同步訊息相關的就分析到這裡,如果有什麼不足的地方,希望讀者指出,謝謝。