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.

 

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

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • POJ – 2965 – The Pilots Brothers' refrigerator (高效贪心!!)[通俗易懂]

    POJ – 2965 – The Pilots Brothers' refrigerator (高效贪心!!)

    2022年2月4日
    40
  • Google凭借Buzz进军社交网络

    Google凭借Buzz进军社交网络《纽约时报》网络版今日发表分析文章称,谷歌周二发布社交网络工具GoogleBuzz,望借此与Facebook、Twitter等社交网络行业巨头竞争。     以下是文章主要内容:  面对不计其数的社交网络服务而不知所措?谷歌愿意帮忙——再多给你一个“选择”。谷歌周二发布GoogleBuzz,用户又将多一个传递信息与想法的平台。  不出预料,GoogleBuzz

    2022年10月15日
    7
  • mysql数据库备份和还原的命令_Mysql数据库备份和还原常用的命令

    mysql数据库备份和还原的命令_Mysql数据库备份和还原常用的命令Mysql数据库备份和还原常用的命令是进行Mysql数据库备份和还原的关键,没有命令,什么都无从做起,更谈不上什么备份还原,只有给系统这个命令,让它去执行,才能完成Mysql数据库备份和还原的操作,下面就是操作的常用命令。一、备份命令1、备份MySQL数据库的命令mysqldump-hhostname-uusername-ppassworddatabasename>backupf…

    2022年5月4日
    57
  • 启用shift后门的方法_shift按五次怎么取消

    启用shift后门的方法_shift按五次怎么取消一、什么是shift后门?shift后门是黑客希望以后方便进入服务器而在没有密码的情况下为进入服务器系统而设置的一个后门。其操作就是在不知道管理员密码的情况下,连续按5次shift键来启动粘滞键,已进入服务器的系统程序管理器。二、shift后门的制作?其制作有很多种,下面介绍一种常用的,可以明白其原理自己扩展:在cmd窗口,敲打命令如下:copyc:\windows\ex

    2026年1月19日
    5
  • P750 内存插槽

    P750 内存插槽查看p750内存插槽占用情况lscfg-vp|grep-pDIMMMemoryDIMM:RecordName……………..VINIFlagField………………XXMSHardwareLocationCode……U78A0.001.DNWKM02-P1-C13-C2…

    2022年6月15日
    32
  • Eclipse中使用SVN教程「建议收藏」

    Eclipse中使用SVN教程「建议收藏」此文章对Myeclipse同样适用。一.在Eclipse里下载Subclipse插件方法一:从EclipseMarketplace里面下载具体操作:打开Eclipse–>Help–>EclipseMarketplace–>在Find中输入subclipse搜索–>找到subclipse点击install方法二:从InstallNewSoftware里下载具体操作:打

    2022年9月26日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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