Can `android.os.Handler.postDelayed` fail?

Viewed 120

I would like to run a function periodically every 5 seconds in a foreground service. I use android.os.Handler.postDelayed for that, like this:

private Handler handler = new Handler();
private Runnable updater = new Runnable() {
    @Override
    public void run() {

        // Do some work

        scheduleTask();
    }
};

private void scheduleTask() {
    handler.postDelayed(updater, 5000);
}

@Override
public void onCreate() {
    super.onCreate();

    scheduleTask();
}

@Override
public void onDestroy() {
    super.onDestroy();

    handler.removeCallbacks(updater);
}

Is it possible for the handler.postDelayed to fail? Can the OS just cancel the delayed request? How to catch that? I need this to run stable for days.

1 Answers

If the app is in the foreground then there is no chance that the handler gets cancelled. It only gets cancelled when the app is running in background for some time or the Main thread has been destroyed.

For reference you can read the android developers documentation https://developer.android.com/reference/android/os/Handler

Related