Handler、Looper、MessageQueue之間的關(guān)系和HandlerThread,IntentService的實(shí)踐

  1. Handler、Looper和MessageQueue的關(guān)系
  • Handler用來處理事件,和發(fā)送事件
  • MessageQueue用來存放Handler發(fā)送的Message,一個(gè)MessageQueue可以包含多個(gè)Massage
  • Looper用來取事件,交由Handler處理
  • 一個(gè)線程對(duì)應(yīng)一個(gè)Looper
  • 一個(gè)Looper對(duì)應(yīng)一個(gè)MessageQueue,Looper內(nèi)置一個(gè)MessageQueue對(duì)象
  • 一個(gè)Looper可以和多個(gè)Handler綁定
  1. HandlerThread的使用
  • HandlerThread繼承自Thread,會(huì)創(chuàng)建一個(gè)looper做消息循環(huán)。

  • 在使用結(jié)束時(shí)應(yīng)該調(diào)用quit()函數(shù)結(jié)束looper

  • 使用示例:

        private void initThread()
        {
            mHandlerThread = new HandlerThread("HandlerThread");
            mHandlerThread.start();
    
            mThreadHandler = new Handler(mHandlerThread.getLooper())
            {
                @Override
                public void handleMessage(Message msg)
                {
                    update();
    
                    if (isUpdateInfo)
                        mThreadHandler.sendEmptyMessage(MSG_UPDATE_INFO);
                }
            };
    
        }
        
       private void update() {
            try
            {
                //模擬耗時(shí)
                Thread.sleep(2000);
                mMainHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        String result = "每隔2秒更新數(shù)據(jù)";
                        result += Math.random();
                        tvMain.setText(result);
                    }
                });
    
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
    
        }
    
    
  1. IntentService的實(shí)踐:

    • 眾所周知Service是運(yùn)行在主線程的,而Android sdk 基于HandlerThread實(shí)現(xiàn)了一個(gè)運(yùn)行在異步線程的Service——IntentService。
    • 源碼展示:
    
            @Override
            public void onCreate() {
                // TODO: It would be nice to have an option to hold a partial wakelock
                // during processing, and to have a static startService(Context, Intent)
                // method that would launch the service & hand off a wakelock.
        
                super.onCreate();
                HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
                thread.start();
        
                mServiceLooper = thread.getLooper();
                mServiceHandler = new ServiceHandler(mServiceLooper);
            }
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容