當創建handler時,該handler就綁定了當前創建handler的線程。
一.在子線程使用Handler方式為:
Runnable runnable = new Runnable(){
public void run(){
Looper.PRepare();
Handler handler = new Handler();
Looper.loop();
}
};
我們來分析一下,為什么要這么使用:
1. 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));    }它實例化了一個Looper,并且和當前線程綁定,也就是實例化一個Looper綁定到當前子線程。2.Handler handler = new 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。3. 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            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            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.recycle();        }    }我們可以發現for(;;)的死循環,queue.next()從MessageQueue隊列中取消息,msg.target.dispatchMessage(msg); 其中msg.target一般是handler(下文會提到),然后由handler來分發消息。
 public void dispatchMessage(Message msg) {        if (msg.callback != null) {            handleCallback(msg);        } else {            if (mCallback != null) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);        }    }這里我看看到了熟悉的代碼handleMessage();先不看msg.callback和mCallback當我們實例化handler,重寫handleMessage(),會在handlerMessage里面處理自己的邏輯(比如更新Ui等)
二:下面我們看看在UI線程使用handler的方式
Handler handler = new Handler();
handler.sendMessage();
這里有一個問題:為什么UI線程沒有調用 Looper.prepare()和Looper.loop();
帶著這個問題,我們來看看UI線程的源碼;
下面是ActivityThread的主函數入口:
public static void main(String[] args) {        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());        Security.addProvider(new AndroidKeyStoreProvider());        Process.setArgV0("<pre-initialized>");        Looper.prepareMainLooper();        ActivityThread thread = new ActivityThread();        thread.attach(false);        if (sMainThreadHandler == null) {            sMainThreadHandler = thread.getHandler();        }        AsyncTask.init();        if (false) {            Looper.myLooper().setMessageLogging(new                    LogPrinter(Log.DEBUG, "ActivityThread"));        }        Looper.loop();        throw new RuntimeException("Main thread loop unexpectedly exited");    }我們可以看到主線程已經創建了Looper,因此,在主線程使用handler時不需要Looper.prepare();三 new Handler(Looper.getMainLooper()) 這種情況是,使用主線程的Looper
比如在子線程里面初始化handler,需要更新ui,那么就可以這么用。
新聞熱點
疑難解答