How to check if Handler has an active task?
is that possible to check has the postDelayed() was called or not?
One quick fix, in method assign some boolean
variable to true and then just perform checking.
There is no direct API to achieve this but you can do a work around for this by using the sendEmptyMessage
function. Hope this will help.
handler.sendEmptyMessage(some_integer);//Do this when you add the call back.
if(handler.hasMessages(some_integer))
handler.removeMessages(some_integer);//Do this after removing the call back.
Handler.post()
is just a convenience wrapper method for sendMessageDelayed()
, so if you wish to check whether a handler has a specific pending Runnable that is still actively running, or whether the postDelayed()
was called with a specific Runnable, then try using the following class:
public class HandlerWithID extends Handler {
public final boolean postDelayed (int runnableID, long delayMillis, Runnable r) {
Message m = Message.obtain(this, r);
m.what = runnableID;
return sendMessageDelayed(m, delayMillis);
}
public final boolean post(int runnableID, Runnable r) {
return postDelayed(runnableID, 0, r);
}
public final boolean hasActiveRunnable(int runnableID) {
return hasMessages(runnableID);
}
}
Handler when posting a Runnable obtains the Message with "what" field == 0, so in theory you could call hasMessages(0)
, but you cannot check if it has given pending Runnable - for example when posting r0 and r1 you cannot check if r0 is pending or not.