android Handler的基本使用方法和介绍(二)

一、HandlerThread是什么

用于防止Looper拿到空指针,下面让我们来看看,它是如何操作的吧

1.Looper getLooper()方法

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

2.handlerThread.run()方法

public void run() {
        mTid = Process.myTid();
        Looper.prepare();//创建一个Looper对象
        synchronized (this) {
            mLooper = Looper.myLooper();//把Looper对象复制给MyLooper
            notifyAll();//通知notify方法,MyLooper就能唤醒在等待当前线程的对象,Handler就能拿到对象,则不会报出空指针问题
        }//线程同步之间的判断
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

二、总结

   总结: 因此在开发中,可以用handlerThread去模拟一个异步任务的一种操作,只需在主线程中给子线程发送消息,让子线程去处理一些耗时的操作(例如:下载网络图片、更新数据库)只要在handlerThread‘中去创建一个Looper,再与一个默认的Handler进行关联,所有的handleMessage方法都是在子线程中去调用。在设计时,可以减轻考虑开启几个线程,开启线程之后,再异步任务中添加要执行的任务(要考虑存储结构),什么时候添加、移除、传递开发的负担。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值