From 4d2f930fa4346220600d27c0b2ef9a78fe15b8f7 Mon Sep 17 00:00:00 2001 From: Phillip Hsu Date: Thu, 15 Sep 2016 13:36:45 -0700 Subject: [PATCH] Restart chronometer in notification when service recreated after process is killed --- .../StopwatchNotificationService.java | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/philliphsu/clock2/stopwatch/StopwatchNotificationService.java b/app/src/main/java/com/philliphsu/clock2/stopwatch/StopwatchNotificationService.java index 4d2cd32..2d8d5ad 100644 --- a/app/src/main/java/com/philliphsu/clock2/stopwatch/StopwatchNotificationService.java +++ b/app/src/main/java/com/philliphsu/clock2/stopwatch/StopwatchNotificationService.java @@ -40,6 +40,23 @@ public class StopwatchNotificationService extends ChronometerNotificationService // if the process is killed, this service remains alive. } + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + // The base implementation returns START_STICKY, so this null intent + // signifies that the service is being recreated after its process + // had ended previously. + if (intent == null) { + // Start the ticking again, leaving everything else in the notification + // as it was. + Log.d(TAG, "Recreated service, starting chronometer again."); + startChronometer(); + } + // If this service is being recreated and the above if-block called through, + // then the call to super won't run any commands, because it will see + // that the intent is null. + return super.onStartCommand(intent, flags, startId); + } + @Override public void onDestroy() { super.onDestroy(); @@ -168,8 +185,15 @@ public class StopwatchNotificationService extends ChronometerNotificationService quitCurrentThread(); if (running) { - long startTime = mPrefs.getLong(StopwatchFragment.KEY_START_TIME, SystemClock.elapsedRealtime()); - startNewThread(0, startTime); + startChronometer(); } } + + /** + * Reads the value of KEY_START_TIME and passes it to {@link #startNewThread(int, long)} for you. + */ + private void startChronometer() { + long startTime = mPrefs.getLong(StopwatchFragment.KEY_START_TIME, SystemClock.elapsedRealtime()); + startNewThread(0, startTime); + } }