Skip to content Skip to sidebar Skip to footer

Restart A Handler.postDelayed In Java

@Override public void onUserInteraction() { Handler handler = new Handler(); handler.postDelayed(new Runnable () { public void run() { finish();

Solution 1:

You can use a boolean object, example:

@Override
public void onUserInteraction() {
    isStarted = true;
    Handler handler = new Handler();
    handler.postDelayed(new Runnable () {
        public void run() {
          if(isStarted){
            finish();
            }
         }
    }, 5000);

}

or you can make something like this:

Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        finish();
    }
};

public static Handler myHandler = new Handler();
private static final int TIME_TO_WAIT = 5000;

@Override
public void onUserInteraction() {
    restart();
}

public void start() {
    myHandler.postDelayed(myRunnable, TIME_TO_WAIT);
}

public void stop() {
    myHandler.removeCallbacks(myRunnable);
}

public void restart() {
    myHandler.removeCallbacks(myRunnable);
    myHandler.postDelayed(myRunnable, TIME_TO_WAIT);
}

Solution 2:

Store the runnable and handler in a field and reuse them

Handler handler;
Runnable runnable = new Runnable () {
    public void run() {
        finish();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    handler = new Handler();
    handler.postDelayed(runnable, 5000);
}

@Override
public void onUserInteraction() {
    handler.removeCallbacks(null);
    handler.postDelayed(runnable, 5000);
}

Solution 3:

Create a handler and keep its reference as global variable

private Runnable runnable;
private Handler newHandler;

newHandler = new Handler();
runnable = new Runnable() {
    @Override
    public void run() {
        try {
            //update UI
            newHandler.postDelayed(runnable,100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};
newHandler.post(runnable);

And on user Interaction

@Override
public void onUserInteraction() {
    super.onUserInteraction();
   newHandler.removeCallbacks(runnable);
    //Do some task
    if(//task done){
     newHandler.postDelayed(runnable,100);
     }
}

Solution 4:

It was not work for me until I used Handler's removeCallbacksAndMessages(Object token) method.

On kotlin

private var restartingHandler = Handler()
private var runnable: () -> Unit = {}

fun start() {
    restartingHandler.postDelayed(runnable, 5000L)
}

fun restart() {
    restartingHandler.removeCallbacks(runnable)
    restartingHandler.removeCallbacksAndMessages(null)

    restartingHandler.postDelayed(runnable, 5000L)
}

fun stop() {
    restartingHandler.removeCallbacks(runnable)
    restartingHandler.removeCallbacksAndMessages(null)
}

Post a Comment for "Restart A Handler.postDelayed In Java"