Search code examples
androidhandlerrunnablepostdelayed

Handler postdelayed is not fired after given delay interval when quitting the app in android?


Code Snippet:

Handler handler= new Handler();
handler.postDelayed(networkRunnable,
                10000);

/**
 * A runnable will be called after the 10 second interval
 */
Runnable networkRunnable= new Runnable() {
    @Override
    public void run() {
        //Not fired if I quit the app before 10 seconds after 1 second. 
    }
};

Setting Handler post delayed to trigger after 10 seconds. If I quit the app in between 1 to 10 seconds the run method never called.

Please help me on this.

Thanks in advance.


Solution

  • The Android runtime aggressively manages process lifetime, destroying processes as their entry points are closed (i.e. when the last activity is finished, for example). Having said that, I don't know of any execution environment in which the code above will execute the callback reliably without additional logic.

    If you want the call-out to fire for sure, you will need to register a Service with the Android core and use the service thread's Handler to schedule the call-out. Android will (usually) keep the Service running and your call-out will be fired later. You should then also unregister the service in the call-out to free up system resources.