Reputation: 3469
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.
Upvotes: 6
Views: 3018
Reputation: 2833
For others who have the same problem, there is a powerful library named TrueTime. To use it add it to your project dependencies:
implementation 'com.github.instacart.truetime-android:library-extension-rx:3.5'
in onCreate method of your Application
class [if you use RxJava]:
TrueTimeRx.build()
.withLoggingEnabled(true)
.withSharedPreferencesCache(this)
.initializeRx("1.us.pool.ntp.org")
.subscribeOn(Schedulers.io())
.subscribe(date -> Log.v("TrueTime", "TrueTime initialized, time: " + date),
throwable -> Log.e("TrueTime", "TrueTime exception: ", throwable)
);
And for use:
if (TrueTimeRx.isInitialized()) {
Date reliableDateNow = TrueTimeRx.now();
// use the current date
}
How it works:
It uses NTP protocol to initialize datetime from network only once. And calculates datetime using SystemClock.elapsedRealtime(). If device is rebooted it will reinit the time using specified NTP servers.
Github repository: https://github.com/instacart/truetime-android/
Upvotes: 0
Reputation: 3469
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.
Upvotes: 6