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.
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.