Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if handler has callback

Tags:

android

In my Application I have created a dialog on a button click and started handler on dialog creation now I want to remove handler's callbacks after dialog dismissed and on activity so I have created a handler on oncreate method of activity which continously checks for flag that I set true when dialog dismisses and when flag become true handler's callback should be removed but handler's callbacks are not removed.

final Handler handler_Alerts = new Handler();
    Runnable r_Alerts = new Runnable() {
    public void run() {
       if(Flag){
            handler1.removeCallbacks(rhandler1);
           }
  Toast.makeText(getApplicationContext(), "In Handler", Toast.LENGTH_SHORT).show();
    handler_Alerts.postDelayed(this, 1000);
                  }
        };

    handler_Alerts.postDelayed(r_Alerts, 1000);
like image 587
ashokk Avatar asked Jun 05 '13 09:06

ashokk


People also ask

What is Handler callback?

Custom code that defines the callout logic. Used by the operational server to call out to third-party systems or to implement conditional security, event notification, or more processing steps.

What is Handler in Android example?

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.

What is use of handler in Android?

In android Handler is mainly used to update the main thread from background thread or other than main thread. There are two methods are in handler. Post() − it going to post message from background thread to main thread using looper.

What is Handler in Kotlin?

What is the use of handler class in Android? There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.


2 Answers

There is no way to check if it has a particula runnable. You can call

handler_Alerts.removeCallbacks(r_Alerts); 

to remove any instance of r_Alerts inside the Handler queue, or

handler_Alerts.removeCallbacks(null);

to remove all the runnable in its queue

like image 182
Blackbelt Avatar answered Oct 03 '22 23:10

Blackbelt


Do not have the reputation to comment, but Blackbelt's:

handler_Alerts.removeCallbacks(null);

should not work according to developer website, since the passed Runnable cannot be null. Instead call:

handler_Alerts.removeCallbacksAndMessages(null);

to remove all callbacks and messages.

like image 31
Rimov Avatar answered Oct 03 '22 21:10

Rimov