handler理解再学习之二


Handler对象与其调用者在同一线程中,如果在Handler中设置了延时操作,则调用线程也会堵塞。每个Handler对象都会绑定一个Looper对象,
每个Looper对象对应一个消息队列(MessageQueue)。如果在创建Handler时不指定与其绑定的Looper对象,系统默认会将当前线程的Looper绑定到该Handler上。
在主线程中,可以直接使用new Handler()创建Handler对象,其将自动与主线程的Looper对象绑定;
在非主线程中直接这样创建Handler则会报错,因为Android系统默认情况下非主线程中没有开启Looper,而Handler对象必须绑定Looper对象。
这种情况下,需先在该线程中手动开启Looper(Looper.prepare()-->Looper.loop()),然后将其绑定到Handler对象上;
或者通过Looper.getMainLooper(),获得主线程的Looper,将其绑定到此Handler对象上。
Handler发送的消息都会加入到Looper的MessageQueue中。
一说Handler包含两个队列:线程队列和消息队列;使用Handler.post()可以将线程对象加入到线程队列中;使用Handler.sendMessage()可以将消息对象加入到消息队列中。
通过源码分析证实,Handler只有一个消息队列,即MessageQueue。通过post()传进去的线程对象将会被封装成消息对象后传入MessageQueue。
使用post()将线程对象放到消息队列中后,当Looper轮询到该线程执行时,实际上并不会单独开启一个新线程,而仍然在当前Looper绑定的线程中执行,
Handler只是调用了该线程对象的run()而已。如,在子线程中定义了更新UI的指令,若直接开启将该线程执行,则会报错;而通过post()将其加入到主线程的Looper中并执行,就可以实现UI的更新。
使用sendMessage()将消息对象加入到消息队列后,当Looper轮询到该消息时,就会调用Handler的handleMessage()来对其进行处理。
再以更新UI为例,使用这种方法的话,就先将主线程的Looper绑定在Handler对象上,重载handleMessage()来处理UI更新,然后向其发送消息就可以了。

     */
    public final boolean hasCallbacks(Runnable r) {
获取一个新的Message示例后,把 Runnable 变量的值赋值给 callback属性
//通过post()传进去的线程对象将会被封装成消息对象后传入MessageQueue 
        return mQueue.hasMessages(this, r, null);
    }
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);//callback存在 即是post 线程,走 message.callback.run(); 
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
    
    public class HandlerThread extends Thread {    注意与IntentService 不一样 ,HandlerThread 只会休眠,不停止。
        @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();  1、准备 Looper MessageQueue
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop(); 2 消息循环获取。
        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();加锁死循环wait()堵塞;
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }
    继承Thread,getLooper()加锁死循环wait()堵塞;
run()加锁等待Looper对象创建成功,notifyAll()唤醒;
唤醒后,getLooper返回由run()中生成的Looper对象; 典型的同步操作。

    没有handler??? 因此需要自创建。 三者缺一不可。
    为何主线程没有,有的!:
       Looper.prepareMainLooper();
     只有主线程才用这个函数,普通线程应该使用prepare(),初始化一个Looper对象
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
        private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }//sThreadLocal 中包含Looper 及当前线程对象键值对,KEY 是 当前对象, value是 Looper
        sThreadLocal.set(new Looper(quitAllowed));
    }
        ActivityThread thread = new ActivityThread();
        thread.attach(false);//通过与AMS binder调用attachApplication 绑定process 

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();//得到一个主线程对应的Handler对象,
            ActivityThread 中有自带主线程handler ,处理activity生命周期任务,我们再加一个handler 跟它就是默认共一个消息队列
        }

        Looper.loop();//死循环,为何没卡 ?底层采用 poll机制 没有消息就让出CPU ,有就wakeup
最后注意:

  Context等对象——>Handler——>Message(target)——>Message Queue(链表)——>Looper——>ThreadLocalMap——>Thread.
     从引用链可以看到被handler和Message引用的对象最终被Thread持有,如果Message没有被执行,一直在Message Queue中,
     会一直被Thread持有。如果Thread没有被销毁,会导致其持有的ThreadLocalMap不会被销毁,所以会导致内存泄漏,特别是UI线程,
     生命周期和APP相同。所以需要在不再使用Message时,要把Message Remove掉

    public void quit() {//looper 退出 调用quit ,消息队列中所有消息都要清除,在线程结束时要调用线程looper的quit,否则可能造成内存泄漏
        mQueue.quit(false);
    }
    public void quitSafely() {
        mQueue.quit(true);
    }
   if (safe) {
        removeAllFutureMessagesLocked();//这个时间点以后的消息也要移除。
       } else {
        removeAllMessagesLocked();
    }
    解决方案:
将 Handler 定义成静态的内部类,在内部持有Activity的弱引用,并在Acitivity的onDestroy()中调用handler.removeCallbacksAndMessages(null)及时移除所有消息。

        MessageQueue.IdleHandler idleHandler=new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                Log.d("yz"," idle do nothing  ");
                return false;
            }
        };
        handler=new Handler();
        handler.getLooper().getQueue().addIdleHandler(idleHandler);
                // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();//当前队列将进入阻塞等待消息时调用该接口回调,即队列空闲,当MessageQueue中无可处理的Message时回调 ,返回true就是单次回调后不删除,下次进入空闲时继续回调该方法,false只回调单次
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }
同步屏障机制

通过上面的学习,我们知道用Handler发送的Message后,MessageQueue的enqueueMessage()按照 时间戳升序 将消息插入到队列中,而Looper则按照顺序,每次取出一枚Message进行分发,一个处理完到下一个。

这时候,问题来了:有一个紧急的Message需要优先处理怎么破?

你可能或说直接sendMessage()不就可以了,不用等待立马执行,看上去说得过去,不过可能有这样一个情况:

一个Message分发给Handler后,执行了耗时操作,后面一堆本该到点执行的Message在那里等着,这个时候你sendMessage(),还是得排在这堆Message后,等他们执行完,再到你!

对吧?Handler中加入了「同步屏障」这种机制,来实现「异步消息优先执行」的功能。
添加一个异步消息的方法很简单:

1、Handler构造方法中传入async参数,设置为true,使用此Handler添加的Message都是异步的;
2、创建Message对象时,直接调用setAsynchronous(true)

 Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }//如果设置了msg.isAsynchronous 为true,上面消息遍历不走,直接走下面,优先级提高
                //往消息队列中插入一个Barrier,那么队列中执行时间在这个Barrier以后的同步消息都会被这
                //个Barrier拦截住无法执行,直到我们调用removeBarrier移除了这个Barrier
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
            }
        void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            //同步屏障:往消息队列插入一个同步屏障消息,这时候消息队列中的同步消息不会被处理,而是优先处理异步消息。
            //消息队列中do while循环,遍历链表,直到找到异步消息msg.isAsynchronous()才跳出循环交给Handler去处理这个异步消息
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(//将线程放到队列,等待,最后的doFrame中执行TraversalRunnable
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
        反向操作即移除屏障。
     void unscheduleTraversals() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
            mChoreographer.removeCallbacks(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
        }
    }
      }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值