How can I get the correct current date and time for an Android device while the device is disconnected

I am creating an Android application and in this application users can save some tasks. These tasks are stored in the device, and when the user goes to the Internet, the tasks will be synchronized with the server. I need to know the correct date and time when the user saves the task. Codes such as Calendar.getInstance()or new Date()return the device time, and if the device time is incorrect, save the task with the wrong date. It is important for this application to work offline. And because of the hustling of this application, it is possible that the user is changing the time of the device as intended. Sorry for my bad english.

+4
source share
1 answer

So, I end up with this script. In this scenario, the user most often connects to the Internet only once for each reboot of the device.

I try to connect to the NTP server when the user boots up ( BOOT_COMPLETED BroadcastReceiver) or the network status changes ( CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED BroadcastReceiver), and then I save this date SystemClock.elapsedRealtime()in the database as well. After that, when I want to have the correct date, I just get a new one SystemClock.elapsedRealtime()and calculate the difference of this value and the elapsedRealtime value from the database and add this difference to the date that I store in the database.

+3
source

Source: https://habr.com/ru/post/1613942/


All Articles