HTTP

MessageQueue.IdleHandler线程空闲时执行的

2017-10-26  本文已影响10人  a9d59df7fe05

先看IdleHanlder接口定义:

/*** 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.

*/

bool eanqueueIdle();

}

Activity的生命周期中并没有界面绘制完成的回调,而根据文档我们知道,这个接口就可以当成是

界面绘制完成的回调,我们可以这样用

Looper.myQueue().addIdleHandler(newMessageQueue.IdleHandler() {

@Override public boolean queueIdle(){

//dosomething

return false;

}

});

对于有Looper的线程也可以用该接口在空闲时执行相关代码,比如HandlerThread:

HandlerThread handlerThread=new HandlerThread("test");

try{

      Field field = Looper.class.getDeclaredField("mQueue");

      field.setAccessible(true);

      MessageQueue queue = (MessageQueue) field.get(handlerThread.getLooper());

      queue.addIdleHandler(newMessageQueue.IdleHandler() {

               @Override

               public boolean queueIdle(){//dosomething

               } 

          return true;

          } });

}catch(Exception e) {

 e.printStackTrace();

}

上一篇 下一篇

猜你喜欢

热点阅读