Handler 使用

Handler 使用

一、Handler和Looper关联

1、子线程内先调用Looper.prepare();
2、再创建Handler,
3、Looper.loop(); 让Looper开始工作

二、Looper

Looper创建

一个线程只能创建一个Looper,且把Looper 存到ThreadLocal中;

    private static void prepare(boolean quitAllowed) {
   
        if (sThreadLocal.get() != null) {
   
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

Looper构造函数创建MassageQueue;

//Looper 关联主线程时为false   
private Looper(boolean quitAllowed) {
   
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

Handler构造函数会关联Looper

public Handler(Callback callback, boolean async) {
   
        if (FIND_POTENTIAL_LEAKS) {
   
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
   
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
   
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

其中mLooper = Looper.myLooper();获取本线程ThreadLocal中的Looper

/**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
   
        return sThreadLocal.get();
    }

Looper.loop是个死循环;

不断从消息队列中读取消息,取出消息进行分发;但阻塞是在queue.next();
退出条件-msg=null(MessageQueue 返回空);

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值