Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get correct current date and time for android device while device is offline

I create an android app and in this app, users can save some tasks. Those tasks are saved in device and when user go online, tasks will be sync to server. I need to know the correct date and time when user save the task. Codes like Calendar.getInstance() or new Date() return device time and if device time was not correct, task save with wrong date. It's important for this app to work offline. And Because of bushiness of this app, It is possible that user change device time in purpose.

like image 466
Hossein Rashno Avatar asked Sep 27 '22 08:09

Hossein Rashno


1 Answers

So I end up with a scenario for which a user at most will connect to internet just once per every device reboot.

I try to connect to a NTP server when user boots (BOOT_COMPLETED BroadcastReceiver) or Network states changed (CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED BroadcastReceiver) and then I store that date and SystemClock.elapsedRealtime() in the database. After that when ever I want to have the correct date, I just get new SystemClock.elapsedRealtime() and calculate the difference of this value and the elapsedRealtime value from database and add that difference to date that I store in database.

like image 116
Hossein Rashno Avatar answered Sep 30 '22 06:09

Hossein Rashno