user2618875
user2618875

Reputation: 890

Android handler remove send message not working

Android handler remove previous send message from the handler message queue. Remember I don't want to use removeCallbacks (Runnable r);

Send broadcast intents
- To send the message

      Intent i = new Intent(my_action);  
      sendBroadcast(i);  

- To cancel any previous message

Intent i = new Intent(my_action);  
i.putExtra("a","a"); 
sendBroadcast(i);

public class TestBroadCast extends BroadcastReceiver {

    Handler h = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // Do my stuff
        }
    };
    Message msg = h.obtainMessage();
    @Override
    public void onReceive(Context context, Intent intent) {

        if ("a".equals(intent.getStringExtra("a"))){
            // Handle intent to cancel message
            msg.what = 1;
            h.removeMessages(1);
        } else {
            // Handle intent to do my stuff
            msg.what = 1;
            h.sendMessageDelayed(msg, 10000);
        }
    }
}

But after this removeMessages is not working.

Upvotes: 1

Views: 1945

Answers (2)

HunkD
HunkD

Reputation: 76

You should move your handler to Application class, here's the reason why:

Your BroadcastReceiver creates multiple handler instances after getting broadcast each time, so Message.target assigned different Handler instance from h.obtainMessage(). Therefore, Handler.removeMessages() will be failed to remove message after checking Message.target. Here's the related source code of how Messagequeue.removeMessages() and check target handler:

while (p != null && p.target == h && p.what == what
   && (object == null || p.obj == object)) {
   Message n = p.next;
   mMessages = n;
   p.recycleUnchecked();
   p = n;
}

Upvotes: 0

Ali
Ali

Reputation: 12684

You can't reuse a Message I've tried that in the past and it doesn't work, you should obtain a new one.

Remove:

Message msg = h.obtainMessage();

Modify:

else { 
        // Handle intent to do my stuff 
        Message msg = h.obtainMessage();
        msg.what = 1;
        h.sendMessageDelayed(msg, 10000);
    } 

You also should make your Handler static, I suspect that is the reason for your problems. The BroadcastReceiver may be short lives and be created and destroyed before your handler fires.

Upvotes: 1

Related Questions