Original link: https://xuyisheng.top/idlehandler/
In Android, Handler is a very frequently used thing. The input event mechanism and system state are all transferred through Handler. In Handler, there is something that is rarely mentioned but very useful, that is IdleHandler , its source code is as follows.
/** * 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(); }
From the comments, we can find that this is a static interface of IdleHandler, a callback that can be executed when there is no message in the message queue or when the message in the queue has not yet reached the execution time.
This function is very useful in some important but not urgent scenarios. For example, we want to do some processing on the home page, but we don’t want to affect the original initialization logic and avoid freezing, then we need to wait for the system to be idle. It’s time to perform our operations again. At this time, we can call back through IdleHandler.
Its use is also very simple, the code example is as follows.
Looper.myQueue().addIdleHandler { // Do something false }
In the Handler’s message loop, once there are no messages to be processed in the queue, the interface will call back, that is, when the Handler is idle.
This interface has a return value, indicating whether it needs to be executed continuously. If it returns true, the callback in IdleHandler will be executed once the Handler is idle, and if it returns false, it will only be executed once.
When it returns true, the processing of the loop can be removed by means of removeIdleHandler. If it is false, it will be removed by itself after processing.
In summary, the use of IdleHandler mainly includes the following scenarios.
- Low-priority task processing: Replace the Handler.postDelayed method that was used before to not affect performance during initialization, and automatically obtain idle timing through IdleHandler.
- Cycle processing tasks when Idle: By controlling the return value, when the system is idle, an operation is repeated continuously.
However, it should be noted that if the Handler is too busy, the execution timing of the IdleHandler may be delayed for a long time, so pay attention to the processing timing of some more important processing logic.
In many third-party libraries, IdleHandler is used, such as LeakCanary, its memory dump analysis process is processed in IdleHandler, so as to avoid the impact on the main thread.
This article is reprinted from: https://xuyisheng.top/idlehandler/
This site is for inclusion only, and the copyright belongs to the original author.