Search code examples
javaandroidmultithreadingandroid-asynctaskthread-safety

Deleting sent messages in UI thread


Let me elaborate a little bit more for example if I have this code:

This object is created by the main UI thread:

Handler handler= new Handler();

Then I use:

handler.postDelayed(new Runnable(){
}, 1000);

My question is, can I cancel that action so that if posted to the main thread's message queue?


Solution

  • You can remove previously posted Runnables using the removeCallbacks() method on the Handler used to post them. You will need to have the exact reference to the Runnable posted.

    In your code, you post a Runnable while declaring it anonymously inline. If you do that, won't retain a reference to that Runnable. Instead, you can store the reference to that new Runnable in a member variable or something that won't be forgotten by the time you want to remove it.

    private Runnable r;  // assign before use
    private Handler h;   // assign before use
    
    private void schedule() {
        h.postDelayed(r, 99999);
    }
    
    private void cancel() {
        h.removeCallbacks(r);
    }