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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With