1

I'd like to create an application to count how long user start the count timer. I created a sample. - My application has a button, when user clicks it, a Service is start - When Service start, it will set a variable noOfSeconds=0 to SharePreference and it start a timer to increase variable noOfSeconds for every seconds.

When my app is suspended (user go to other app or home screen), it works well. However, when it is suspended long time (over 2 hours), the noOfSeconds is wrong.

I guest that Android OS kill my suspended activity and background service when they are inactive long time.

Do you have any sample code to make a timer tick run in very long time?

Thanh
  • 31
  • 5

1 Answers1

1

To make an app run in the background for a long time, you use a foreground service, show a notification in the status bar and hold a WakeLock. This way your app is much unlikely to be killed.

BTW, if your app simply shows the time when users come back to your app, why not store start time and calculate difference in the next launch?

Dewey Reed
  • 4,353
  • 2
  • 27
  • 41
  • Thanks for your answer @dewey-reed Regard your suggestion, I can't use it. Because after user start the timer, then inactive it. User manually change the time of phone => it make my timer show wrong number of seconds Could you share me the source code using foreground service with timer? I tried it before but it's not working. Thanks in advance! – Thanh Sep 25 '18 at 02:54
  • 1
    https://stackoverflow.com/a/15620527/5507158 said `System.nanoTime()` won't be affected the time of phone. As for foreground service, the official doc is helpful. https://developer.android.com/guide/components/services#Foreground and https://developer.android.com/training/scheduling/wakelock – Dewey Reed Sep 25 '18 at 03:09
  • I tried to use `System.nanoTime()`. However, it is inaccuracy. – Thanh Sep 25 '18 at 14:30
  • It returns nano secondds rather than seconds. Did you try `SystemClock.elapsedRealtime()` like that link said? – Dewey Reed Sep 26 '18 at 01:51