Reputation: 1646
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.
Upvotes: 0
Views: 1466
Reputation: 899
In order to achieve this I used an AlarmManager instead of the handler at, its working now, this is an extract of the code I'm using:
@Override
protected void onHandleIntent(Intent intent) {
Log.d(Constants.TAG, "onHandleIntent");
...
restartService();
Log.d(Constants.TAG, "finish");
}
private void restartService() {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent queryIntent = new Intent(context, ServiceClass.class);
PendingIntent pendingQueryIntent = PendingIntent.getService(context, 0, queryIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
// schedule the intent for future delivery
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + Constants.RESTART_TIME, pendingQueryIntent);
}
In this way I'm able to restart the service no matter if the user closes the app using home, back or swipe from recent apps, the only way it stops working is if the uses forces the app to stop.
Hope it helps
Upvotes: 0
Reputation: 2910
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.
Upvotes: 2