I have a service which creates a CountDownTimer
and then displays a Notification
and updates it according to CountDownTimer
.
The problem comes when I close the app. Even if CountDownTimer
is already half done, it will reset when app is completely closed.
This is the main part of Service
cass:
/*
Variables
*/
private NotificationManager notificationManager;
private CountDownTimer countDownTimer;
private String TAG = "NotificationService";
private int NOTIFICATION_COUNTDOWN = 0;
private int NOTIFICATION_RANOUT = 1;
private int reservationDuration;
/*
Callbacks
*/
@Override
public void onCreate() {
super.onCreate();
notificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
EventBus.getDefault().register(this);
reservationDuration = 15;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
countDownTimer = new CountDownTimer(1000 * 60 * 15, 1000 * 60) {
@Override
public void onTick(long millisUntilFinished) {
notificationManager.notify(NOTIFICATION_COUNTDOWN, createReservationActiveNotification(--reservationDuration));
}
@Override
public void onFinish() {
notificationManager.cancel(NOTIFICATION_COUNTDOWN);
stopSelf();
}
}.start();
return super.onStartCommand(intent, flags, startId);
}
The Service
seems to completely restart whenever the app is closed. Because even the reservationDuration variables resets to 15 (whcih is in onCreate) and the Notification
goes back to full time as soon as the app is completely destroyed/closed.
The value that you return from your override of the onStartCommand determines what happens to your service when it is killed, for example when your app is killed do to the need for more memory.
If you return START_NOT_STICKY your service will not be restarted after being killed until you explicitly start it via a start command.
Since you are returning
super.onStartCommand(intent, flags, startId);
you are getting the default of either START_STICKY or START_STICKY_COMPATIBILITY. Which is documented here:Here are the details for various return values for onStartCommand (from the documentation).