0

I need to running thread every one second. But when application killed, the thread must be still alive.

My thread task is used for increment Unix Timestamp (that synchronized when the first time application running from our server time) by one every second. I need to create this task because in some device, date time can changed unpredictable (maybe low on battery, hard reset, dropped or something else).

My Activity must be get that Unix Timestamp value when it needed.

From SO, Alarm Manager is not a good choice,

I would recommend you not to use an AlarmManager for 30 seconds, as some have suggested. Because 30 seconds is too short. it will drain the battery. For AlarmManager use a minimum 1 minute with RTC.

Other people suggest using Timer Task or ScheduledExecutorService, what the best thread to fit my need?

Thanks.

Community
  • 1
  • 1
Yohanim
  • 3,319
  • 9
  • 52
  • 92
  • Hey friend, why is this being done in a thread? I would suggest to initiate a service for this. so that it can run independently. – JVN Aug 05 '15 at 05:50
  • Currently, this task running with IntentService, I just thinking what a best way to achieve this. – Yohanim Aug 05 '15 at 06:44
  • try to start a service and then from that start a thread. and do your time based process in that thread. you can use Thread.Sleep(time_in_seconds) in a while loop inside the thread to get the thread working in proper period of time ( base on time_in_seconds value) – JVN Aug 05 '15 at 13:35

1 Answers1

0

You would never achieve that. Any process could be killed by System. And task running every seconds is horrible (like AlarmManager said).

One idea is: save your server time and device time such as SystemClock.elapsedRealtime() . (do not use System.currentTimeMillis() for this purpose. ... this is display time for user and can be changed by user or something). When you need time later, get elapsedRealtime() again and compare with stored elapsedRealtime(), and add this diff to stored server time. You will get desired time.

Or simply ask current time to your server , depends on needs :).

If you want to care hard reset I think that you should have database on your server to manage the first time when user launches app.

ytRino
  • 1,450
  • 15
  • 28
  • Hi, thanks for your reply. We can't ask current time from our server because sometimes the device not connected to the network. So I think I need to create own timing system. – Yohanim Aug 05 '15 at 06:42