简体   繁体   中英

Android running thread every 1 Second to Increment Unix Timestamp

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM