Android HandlerThread分析[通俗易懂]

之前Handler分析的文章有分析过,子线程Thread中是不能直接使用Handler的,需要调用Looper.prepare()方法,因此Android就为我们提供了Handler和Thread结合的方法HandlerThread方法,我们先来看下HandlerThread的源码:publicclassHandlerThreadextendsThread{intmP…

大家好,又见面了,我是你们的朋友全栈君。

之前Handler 分析的文章有分析过,子线程Thread中是不能直接使用Handler的,需要调用Looper.prepare()方法,因此Android就为我们提供了Handler和Thread结合的方法HandlerThread方法,我们先来看下HandlerThread的源码:

public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    Looper mLooper;
    private @Nullable Handler mHandler;

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

    /**
     * Constructs a HandlerThread.
     * @param name
     * @param priority The priority to run the thread at. The value supplied must be from
     * {@link android.os.Process} and not from java.lang.Thread.
     */
    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }

    /**
     * Call back method that can be explicitly overridden if needed to execute some
     * setup before Looper loops.
     */
    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;
    }

    /**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason isAlive() returns false, this method will return null. If this thread
     * has been started, this method will block until the looper has been initialized.
     * @return The looper.
     */
    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;
    }

    /**
     * @return a shared {@link Handler} associated with this thread
     * @hide
     */
    @NonNull
    public Handler getThreadHandler() {
        if (mHandler == null) {
            mHandler = new Handler(getLooper());
        }
        return mHandler;
    }
    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;
    }

    /**
     * Returns the identifier of this thread. See Process.myTid().
     */
    public int getThreadId() {
        return mTid;
    }
}

很简单的源码HandlerThread继承Thread主要看:

@Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();//手动为子线程创建了looper
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();//开始轮询
        mTid = -1;
    }

可以看到run方法中为子线程创建了looper,并把对象放到线程中,然后通过Looper.loop();开启循环消息。

其他方法:

getThreadHandler: 获取当前线程的handler

quit:清空所有消息

quitSafely:只情况延时消息 

getLooper:获取线程中的looper对象

 

我们看下HandlerThread的使用:

private void startThread(){
    HandlerThread handlerThread = new HandlerThread("thread_one");
    handlerThread.start();
    workHandler = new Handler(handlerThread.getLooper()){//子线程handler
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                Thread.sleep(1000);//子线程中处理耗时操作
                mainHandler.sendEmptyMessage(0);//处理完后发送消息给主线程更新UI

            }catch (Exception e){

            }
        }
    };

    workHandler.sendEmptyMessage(0);

    mainHandler = new Handler(){//主线程handler
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mBtn.setText("start");//主线程中更新UI
        }
    };
}

例子中我们看到我们通过handlerThread.getLooper()获取子线程的looper然后与workHandler,我们知道handler的线程是依赖与与之关联的looper线程,所以workHandler是子线程的handler.

然后我们new 一个未传looper的handler,默认与主线程关联,所以mainHandler是主线程的handler.

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/127757.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号