IdleHandler源码分析-使用场景

Idlehandler是一个接口,存在于MessageQueue里,官方文档说,当一个线程在阻塞状态,等待其他信息都时候,会被回调。很多文档都说它是当Activity得UI线程执行完毕得一个回调,可以进行一些初始化和优化的操作。比如:当界面绘制完毕,获取view得宽高。

  /**
     * Callback interface for discovering when a thread is going to block
     * waiting for more messages.
     */
    public static interface IdleHandler {
        /**
         * Called when the message queue has run out of messages and will now
         * wait for more.  Return true to keep your idle handler active, false
         * to have it removed.  This may be called if there are still messages
         * pending in the queue, but they are all scheduled to be dispatched
         * after the current time.
         */
        boolean queueIdle();
    }

下面看下源码得调用;

ActivityThread.class

    void scheduleGcIdler() {
        if (!mGcIdlerScheduled) {
            mGcIdlerScheduled = true;
            //mGcIdler是IdleHandler得子类。主要做一些GC回收工作
            Looper.myQueue().addIdleHandler(mGcIdler);
        }
        mH.removeMessages(H.GC_WHEN_IDLE);
    }


  public void addIdleHandler(@NonNull IdleHandler handler) {
        if (handler == null) {
            throw new NullPointerException("Can't add a null IdleHandler");
        }
        synchronized (this) {
            mIdleHandlers.add(handler);
        }
  }

    

 

你可能感兴趣的:(android框架解析)