探究Android異步消息的處理之Handler詳解

博文出處:探究Android異步消息的處理之Handler詳解,歡迎大家關注我的博客,謝謝!

在學習Android的路上,大家肯定會遇到異步消息處理,Android提供給我們一個類來處理相關的問題,那就是Handler。相信大家大多都用過Handler了,下面我們就來看看Handler最簡單的用法:

public class FirstActivity extends AppCompatActivity {

    public static final String TAG = "FirstActivity";
    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Log.i(TAG, "handler receive msg.what = " + msg.what);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //這里做相關操作
                handler.sendEmptyMessage(0);
            }
        }).start();
    }

}

上面代碼實現了在子線程中發出一個消息,然后在主線程中接收消息。Handler其他類似的用法在這就不過多敘述了。下面我們來看看Handler到底是怎么實現異步消息處理的吧!

先來看看我們new一個Handler的對象到底發生了什么(只截取了關鍵源碼):

public Handler() {
        this(null, false);
    }
    
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;
    }

可以看到我們平常寫的 new Handler();其實是調用了另外一個構造方法,并且判斷了mLooper是不是為空,為空則拋出一個異常"Can't create handler inside thread that has not called Looper.prepare()",mLooper其實是一個Looper類的成員變量,官方文檔上對Looper類的解釋是 Class used to run a message loop for a thread.也就是說Looper用于在一個線程中傳遞message的。 然后我們根據異常的提示知道要在new一個Handler的對象之前必須
先調用Looper.prepare()。那接下來就只能先去看看Looper.prepare()方法了:

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;
    final Thread mThread;

    private Printer mLogging;

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

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

    /**
     * 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();
        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.recycleUnchecked();
        }
    }

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

prepare()方法就是將一個sThreadLocal和新建的Looper對象相綁定,同時mQueue成員變量也創建了新的MessageQueue對象,MessageQueue這個類就是用于存儲Message的隊列。在prepare()方法的注釋上寫著在調用prepare()方法之后還要調用loop()方法,我們再看loop方法,可以看到方法里寫了一個for的死循環,主要用于在MessageQueue里不斷地去取Message,如果msg為空,則阻塞;不然會調用msg.target.dispatchMessage(msg)這個方法。dispatchMessage()這個方法我會在后面講解,先暫時放一邊不管。

好了,捋一捋思路,當你在新建一個Handler對象時,要先確保調用了Looper.prepare()方法,然后調用Looper.loop()方法讓MessageQueue這個隊列“動”起來。這樣你就成功地創建了一個Handler的對象。然后我們再使用Handler的sendMessage系列方法來發送一個消息。下面我們就來看看sendMessage系列方法里到底干了什么:

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

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

為什么我就貼出一個方法呢?這是因為Handler一系列的sendMessage方法基本上最后都是調用了sendMessageAtTime這個方法。從源碼中我們看到主要就是干了把Message加入隊列這個事,并把當前的Handler對象賦給了msg的target。再聯系上面的Looper.loop方法,我們大概就懂了。好了,我們回過頭來看看上面的msg.target.dispatchMessage(msg)主要的功能。其實就是調用了Handler的dispatchMessage方法:

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

我們看到了一行熟悉的代碼:handleMessage(msg),這不正是我們再創建Handler對象時重寫的那個方法么!好了,這一切的邏輯我們似乎已經搞清了:首先調用Looper.prepare()創建一個Looper對象,然后handler發送消息后把消息加入到MessageQueue里,因為之前調用了Looper.loop(),所以MessageQueue在不斷地做出隊的操作,然后再根據message的target變量分發消息,回到handler的handleMessage()方法。

也許有人會有疑問了,為什么在主線程中創建Handler對象可以直接使用而不需要調用Looper.prepare()和Looper.loop()兩個方法呢?這是因為在ActivityThread里面已經調用了,下面附上ActivityThread的源碼:

/** 
 * This manages the execution of the main thread in an 
 * application process, scheduling and executing activities, 
 * broadcasts, and other operations on it as the activity 
 * manager requests. 
 * 
 * {@hide} 
 */  
public final class ActivityThread {  
  
    static ContextImpl mSystemContext = null;  
  
    static IPackageManager sPackageManager;  
      
    // 創建ApplicationThread實例,以接收AMS指令并執行  
    final ApplicationThread mAppThread = new ApplicationThread();  
  
    final Looper mLooper = Looper.myLooper();  
  
    final H mH = new H();  
  
    final HashMap<IBinder, ActivityClientRecord> mActivities  
            = new HashMap<IBinder, ActivityClientRecord>();  
      
    // List of new activities (via ActivityRecord.nextIdle) that should  
    // be reported when next we idle.  
    ActivityClientRecord mNewActivities = null;  
      
    // Number of activities that are currently visible on-screen.  
    int mNumVisibleActivities = 0;  
      
    final HashMap<IBinder, Service> mServices  
            = new HashMap<IBinder, Service>();  
      
    Application mInitialApplication;  
  
    final ArrayList<Application> mAllApplications  
            = new ArrayList<Application>();  
  
    static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal<ActivityThread>();  
    Instrumentation mInstrumentation;  
  
    static Handler sMainThreadHandler;  // set once in main()  
  
    static final class ActivityClientRecord {  
        IBinder token;  
        int ident;  
        Intent intent;  
        Bundle state;  
        Activity activity;  
        Window window;  
        Activity parent;  
        String embeddedID;  
        Activity.NonConfigurationInstances lastNonConfigurationInstances;  
        boolean paused;  
        boolean stopped;  
        boolean hideForNow;  
        Configuration newConfig;  
        Configuration createdConfig;  
        ActivityClientRecord nextIdle;  
  
        String profileFile;  
        ParcelFileDescriptor profileFd;  
        boolean autoStopProfiler;  
  
        ActivityInfo activityInfo;  
        CompatibilityInfo compatInfo;  
        LoadedApk packageInfo; //包信息,通過調用ActivityThread.getPapckageInfo而獲得  
  
        List<ResultInfo> pendingResults;  
        List<Intent> pendingIntents;  
  
        boolean startsNotResumed;  
        boolean isForward;  
        int pendingConfigChanges;  
        boolean onlyLocalRequest;  
  
        View mPendingRemoveWindow;  
        WindowManager mPendingRemoveWindowManager;  
  
        ...  
    }  
  
  
    private class ApplicationThread extends ApplicationThreadNative {  
  
        private void updatePendingConfiguration(Configuration config) {  
            synchronized (mPackages) {  
                if (mPendingConfiguration == null ||  
                        mPendingConfiguration.isOtherSeqNewer(config)) {  
                    mPendingConfiguration = config;  
                }  
            }  
        }  
  
        public final void schedulePauseActivity(IBinder token, boolean finished,  
                boolean userLeaving, int configChanges) {  
            queueOrSendMessage(  
                    finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,  
                    token,  
                    (userLeaving ? 1 : 0),  
                    configChanges);  
        }  
  
        // we use token to identify this activity without having to send the  
        // activity itself back to the activity manager. (matters more with ipc)  
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,  
                ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,  
                Bundle state, List<ResultInfo> pendingResults,  
                List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,  
                String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {  
            ActivityClientRecord r = new ActivityClientRecord();  
  
            r.token = token;  
            r.ident = ident;  
            r.intent = intent;  
            r.activityInfo = info;  
            r.compatInfo = compatInfo;  
            r.state = state;  
  
            r.pendingResults = pendingResults;  
            r.pendingIntents = pendingNewIntents;  
  
            r.startsNotResumed = notResumed;  
            r.isForward = isForward;  
  
            r.profileFile = profileName;  
            r.profileFd = profileFd;  
            r.autoStopProfiler = autoStopProfiler;  
  
            updatePendingConfiguration(curConfig);  
  
            queueOrSendMessage(H.LAUNCH_ACTIVITY, r);  
        }  
  
        ...  
    }  
  
    private class H extends Handler {  
  
        public void handleMessage(Message msg) {  
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));  
            switch (msg.what) {  
                case LAUNCH_ACTIVITY: {  
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");  
                    ActivityClientRecord r = (ActivityClientRecord)msg.obj;  
  
                    r.packageInfo = getPackageInfoNoCheck(  
                            r.activityInfo.applicationInfo, r.compatInfo);  
                    handleLaunchActivity(r, null);  
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
                } break;  
                ...  
            }  
            if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));  
        }  
         
        ...  
    }  
  
    public static ActivityThread currentActivityThread() {  
        return sThreadLocal.get();  
    }  
  
   
    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());  
  
        Process.setArgV0("<pre-initialized>");  
  
        Looper.prepareMainLooper();  
  
        // 創建ActivityThread實例  
        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");  
    }  
}  

可以看到上面的main方法里的181行和198行已經調用了prepare和loop的方法。因此在主線程中使用Handler不需要再調用prepare和loop方法了。

好了,今天該講的差不多了,就到這吧。

由于第一次寫講解源碼的博客,不便之處請大家多多包涵。有問題的可以在下面評論。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,565評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,115評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,577評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,514評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,234評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,621評論 1 326
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,641評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,822評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,380評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,128評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,319評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,879評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,548評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,970評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,229評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,048評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,285評論 2 376

推薦閱讀更多精彩內容