新聞中心
在Android應(yīng)用程序進(jìn)程啟動(dòng)過(guò)程的源代碼分析一文中,我們分析了Android應(yīng)用程序進(jìn)程的啟動(dòng)過(guò)程。

為巴州等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及巴州網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、巴州網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
Android應(yīng)用程序進(jìn)程在啟動(dòng)的時(shí)候, 會(huì)在進(jìn)程中加載ActivityThread類,并且執(zhí)行這個(gè)類的main函數(shù)。
應(yīng)用程序的消息循環(huán)過(guò)程就是在這個(gè)main函數(shù)里面實(shí)現(xiàn)的。
我們來(lái)看看這個(gè)函數(shù)的實(shí)現(xiàn),它定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
- [java] view plaincopypublic final class ActivityThread {
- ......
- public static final void main(String[] args) {
- ......
- looper.prepareMainLooper();
- ......
- ActivityThread thread = new ActivityThread();
- thread.attach(false);
- ......
- Looper.loop();
- ......
- thread.detach();
- ......
- }
- }
這個(gè)函數(shù)做了兩件事情,一是在主線程中創(chuàng)建了一個(gè)ActivityThread實(shí)例,二是通過(guò)Looper類使主線程進(jìn)入消息循環(huán)中,這里我們只關(guān)注后者。
首先看Looper.prepareMainLooper函數(shù)的實(shí)現(xiàn),這是一個(gè)靜態(tài)成員函數(shù),定義在frameworks/base/core/java/android/os/Looper.java文件中:
- [java] view plaincopypublic class Looper {
- ......
- private static final ThreadLocal sThreadLocal = new ThreadLocal();
- final MessageQueue mQueue;
- ......
- /** 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 final void prepare() {
- if (sThreadLocal.get() != null) {
- throw new RuntimeException("Only one Looper may be created per
- thread");
- }
- sThreadLocal.set(new Looper());
- }
- /** Initialize the current thread as a looper, marking it as an
- application's main
- * looper. The main looper for your application is created by the Android
- environment,
- * so you should never need to call this function yourself.
- * {@link #prepare()}
- */
- public static final void prepareMainLooper() {
- prepare();
- setMainLooper(myLooper());
- if (Process.supportsProcesses()) {
- myLooper().mQueue.mQuitAllowed = false;
- }
- }
- private synchronized static void setMainLooper(Looper looper) {
- mMainLooper = looper;
- }
- /**
- * Return the Looper object associated with the current thread. Returns
- * null if the calling thread is not associated with a Looper.
- */
- public static final Looper myLooper() {
- return (Looper)sThreadLocal.get();
- }
- private Looper() {
- mQueue = new MessageQueue();
- mRun = true;
- mThread = Thread.currentThread();
- }
- ......
- }
網(wǎng)頁(yè)名稱:Android應(yīng)用程序消息處理機(jī)制(Looper、Handler)分析(2)
網(wǎng)頁(yè)網(wǎng)址:http://www.5511xx.com/article/coedjpg.html


咨詢
建站咨詢
