HandlerThread解析

Posted 丛林小阁楼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HandlerThread解析相关的知识,希望对你有一定的参考价值。

HandlerThread是一种具有消息循环的线程。HandlerThread可以接收消息并处理消息,并执行一些耗时操作,这样UI线程就可以把一些耗时的操作命令发送给HandlerThread,由该线程处理后再发送到主线程返回。这样主线程用于分发和显示,而子线程用于逻辑处理和运算。

HandlerThread使用的样例:

package com.fxb.handlerthead;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener{

    private static final String TAG = "HandlerThreadTest";
    private static final int WHAT_CALUCULATE = 0x1001;
    private static final int WHAT_RESULT = 0x1002;

    private TextView tvShow;
    private Button btnStart;
    private HandlerThread handlerThread;
    private Handler mainHandler, subHandler;
    private int count;

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

        mainHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };
        initThread();
    }

    private void initView(){
        tvShow = (TextView)findViewById(R.id.tvShow);
        btnStart = (Button)findViewById(R.id.btnStart);

        btnStart.setOnClickListener(this);
    }

    private void initThread(){
        handlerThread = new HandlerThread("myHandlerThread");
        handlerThread.start();

        subHandler = new Handler(handlerThread.getLooper()){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == WHAT_CALUCULATE){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    final int num1 = msg.arg1;
                    final int num2 = msg.arg2;
                    final int result = num1 + num2;
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            tvShow.setText(num1+" + "+num2+" = "+result);
                        }
                    });
                }
            }
        };
    }


    @Override
    public void onClick(View v) {
        if(v == btnStart){
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    count++;
                    Message msg = subHandler.obtainMessage(WHAT_CALUCULATE, count, count + 1);
                    msg.sendToTarget();

                    mainHandler.postDelayed(this, 1000);
                }
            }, 1000);
        }
    }
}

当点击Start按钮后,延时500ms后会在tvShow上显示1 + 2 = 3,1s后显示2 + 3 = 5,依次递增。

 

HandlerThread源码

import android.os.Looper;

public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    Looper mLooper;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }

    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

    public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }

        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }

    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

    public int getThreadId() {
        return mTid;
    }
}

getLooper()时,如果没有创建好,则会阻塞,创建好后会唤醒,然后返回。

以上是关于HandlerThread解析的主要内容,如果未能解决你的问题,请参考以下文章

HandlerThread解析

Android培训HandlerThread的使用及源码解析

android源码解析之-->HandlerThread

HandlerThread 的使用及其源码完全解析

HandlerThread原理与应用

Android 多线程之IntentService 完全详解