Make sure the Android handler has callbacks

I have code that sets a timer, but if the user sets a timer while using it, I need to remove the runnable that starts the timer, and start it again. But when no handler callback handler exists, and this code is called, it crashes my application. So I need to check if the handler works, if so, then finish it and restart, but, looking at the documentation and other Stackoverflow questions, I don’t see if this is possible.

Here is my code, I commented on the code, which should only be executed if there is a handler executable file:

submitTimer.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { String s = timer.getText().toString(); if(!s.equals("")) { //I NEED TO CHECK A RUNNABLE HANDLER EXISTS AND IF SO THEN RUN THIS CODE, IF NOT IGNORE THIS CODE Map.handler.removeCallbacks(Map.getRunnable()); Map.runnable.run(); //I NEED TO CHECK A RUNNABLE HANDLER EXISTS AND IF SO THEN RUN THIS CODE, IF NOT IGNORE THIS CODE int l = Integer.parseInt(s); Map.timerinmins = l; timer.setHint("Current Timer is "+Map.timerinmins); timer.setText(""); Toast.makeText(Preferences.this, "Timer is set!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(Preferences.this, "No value was entered", Toast.LENGTH_SHORT).show(); } } }); 

Can someone help me figure out a way to check the current state of the handlers?

+7
source share
2 answers

If you want, you can send an empty message on the first callback, and then check this message in the handler. This empty message may indicate that there is a callback. Deleting this message later could be used similarly to see if there is a callback. You do not have an appropriate situation, such as this, but I thought that at least I would try to share the opportunity.

 ... Map.handler.sendEmptyMessage(CALLBACK_PRESENT_INTEGER); ... if(Map.handler.hasMessages(CALLBACK_PRESENT_INTEGER) ... Map.handler.removeMessage(CALLBACK_PRESENT_INTEGER); ... 

This is probably not ideal, but could be a potential solution if you have access to your handler from where your callback is being used. Not sure if there is a direct way to find out.

+4
source

Turning to Jay Snayder , answer:

Since there are cases in which Map.handler.hasMessages(CALLBACK_PRESENT_INTEGER) returns false, even if Map.handler.sendEmptyMessage(CALLBACK_PRESENT_INTEGER) was called (also with me), it might be safer to use a boolean value to determine if the handler has reverse challenges or not.
So, the logic of the code is something very simple:

 ... boolean callbackPresent = false; ... if(!callbackPresent) { // do what you have to do in case the handler doesn't have callbacks // right before adding a callback to the handler, call: callbackPresent = true; } else { // do what you have to do in case the handler has callbacks // right before removing the callbacks from the handler, call: callbackPresent = false; } ... 

I use this solution in the application and it works great.

+3
source

All Articles