Android - Removing anonymous Runnables from Handler

     Android's Handler has convenient APIs to remove messages after they are posted to a looper thread. Messages are identified by an integer and this makes it easy to remove them via removeMessages(int) However, this doesn't work with Runnables which aren't associated with a message type. Besides, applications might want to remove multiple Runnables of a specific type.

    Handler has an API removeCallbacks(Runnable r) to remove the runnable but this requires that application book keep the runnable and needs more work when multiple instances are posted to the handler. Besides, applications tend to post anonymous Runnables.

   Fortunately, Handler has another API to remove all messages and runnable removeCallbacksAndMessages(Object token) corresponding to the specified token. The same token can be associated with multiple runnables and serves the purpose with ease.

   However, there isn't a straightforward API to post a Runnable along with a token. This needs a little more work but is better than book keeping runnables.

                   postAtTime(Runnable r, Object token, long uptimeMillis)


         Binder mRunnableToken = new Binder();
         Handler mHandler = new Handler();

        mHandler.postAtTime(new Runnable() {

            @Override
            public void run() {
                return;
            }

        }, mRunnableToken, SystemClock.uptimeMillis());

From here on, the token runnableToken can be used to remove the anonymous runnables.

        mHandler.removeCallbacksAndMessages(mRunnableToken);

No comments: