Step 1. Add the JitPack repository to your build file
Add it in your root settings.gradle at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
Add it in your settings.gradle.kts at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
}
Add to pom.xml
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Add it in your build.sbt at the end of resolvers:
resolvers += "jitpack" at "https://jitpack.io"
Add it in your project.clj at the end of repositories:
:repositories [["jitpack" "https://jitpack.io"]]
Step 2. Add the dependency
dependencies {
implementation 'com.github.videro:mutime:v0.3-videro'
}
dependencies {
implementation("com.github.videro:mutime:v0.3-videro")
}
<dependency>
<groupId>com.github.videro</groupId>
<artifactId>mutime</artifactId>
<version>v0.3-videro</version>
</dependency>
libraryDependencies += "com.github.videro" % "mutime" % "v0.3-videro"
:dependencies [[com.github.videro/mutime "v0.3-videro"]]
NTP client for Android. Calculate the date and time "now" impervious to manual changes to device clock time.
In certain applications it becomes important to get the real or "true" date and time.
On most devices, if the clock has been changed manually,
then a new Date()
instance gives you a time impacted by local settings.
Users may do this for a variety of reasons, like being in different timezones, trying to be punctual by setting their clocks 5 – 10 minutes early, etc. Your application or service may want a date that is unaffected by these changes and reliable as a source of truth. MuTime gives you that.
Originally a fork, now a major rewrite of Instacart's TrueTime library.
You can read more about the use case in Instacart's blog post.
We use Jitpack to host the library.
Add this to your application's build.gradle
file:
repositories {
maven {
url "https://jitpack.io"
}
}
dependencies {
compile 'com.github.medavox:MuTime:<release-version>'
}
The current release version is v0.3
.
//optionally enable the disk cache
MuTime.enableDiskCaching(/*Context*/ this);//this hardens MuTime against clock changes and reboots
MuTime.requestTimeFromServer("time.google.com");//use any ntp server address here, eg "time.apple.com"
//get the real time in unix epoch format (milliseconds since midnight on 1 january 1970)
try {
long theActualTime = MuTime.now();//throws MissingTimeDataException if we don't know the time
}
catch (MissingTimeDataException e) {
Log.e("MuTime", "failed to get the actual time:+e.getMessage());
}
requestTimeFromServer(String)
must be run on a background thread.
If you run it on the main (UI) thread, you will get a
NetworkOnMainThreadException
If you use the Ntp class then you get full NTP.
Use the performNtpAlgorithm(InetAddress...)
method, or alternatively resolve an NTP pool server to Inetaddress
es automatically with resolveNtpPoolToIpAddresses(String)
. You can even resolve multiple NTP servers with resolveMultipleNtpHosts(String...)
.
//gather NTP data from multiple hosts
Ntp.performNtpAlgorithm(Ntp.resolveMultipleNtpHosts("pool.ntp.org", "time.google.com", "time.apple.com") );
Now, as before:
try {
long theActualTime = mu.now();//throws MissingTimeDataException if we don't know the time
}
catch (MissingTimeDataException e) {
Log.e("MuTime", "failed to get the actual time:+e.getMessage());
}
It's pretty simple actually. We make a request to an NTP server that gives us the actual time. We then establish the delta between device uptime and uptime at the time of the network response. On each subsequent request for the true time "now", we compute the correct time from that offset.
Once we have this offset information, it's valid until the next time you boot your device. This means if you enable the disk caching feature, after a single successful NTP request you can use the information on-disk directly without ever making another network request. This applies even across application kills -- which can happen frequently if a user has a memory starved device.
I needed a way of providing reliable time for another app, preserving the correct time across 1) android clock adjustments by the user and 2) device reboots. Although the NTP client implementation in TrueTime's library is more sophisticated than Google's hidden Android SntpClient, I needed even more reliable time-keeping for my use case. It was also apparent (at the time of forking) that instacart/Kaushik Gopal's plans for future development did not fit with my own needs (judging from development branches).
MuTime implements a more 'stubborn'
Persistence
solution, which preserves information about the correct time even after clock changes and device reboots.
It's a beefed-up version of TrueTime's Disk Cache functionality.
The public API has been revampe, and the underlying codebase largely rewritten, to improve maintainability (in my humble opinion).
requestTimeFromServer(String)
call makes an SNTP network request.
MuTime needs to do this only once -- barring any , if you use MuTime's withSharedPreferences
When you execute the MuTime initialization, you are very likely to get an InvalidNtpServerResponseException
because of root delay violation or root dispersion violation the first time.
This is an expected occurrence as per the NTP Spec and needs to be handled.
The NTP protocol works on UDP:
It has no handshaking dialogues, and thus exposes the user's program to any unreliability of the underlying network and so there is no guarantee of delivery, ordering, or duplicate protection
UDP is suitable for purposes where error checking and correction is either not necessary or is performed in the application, avoiding the overhead of such processing at the network interface level. Time-sensitive applications often use UDP because dropping packets is preferable to waiting for delayed packets, which may not be an option in a real-time system
(Wikipedia's page, emphasis our own)
This means it is highly plausible that we get faulty data packets. These are caught by the library and surfaced to the API consumer as an InvalidNtpServerResponseException
. See this portion of the code for the various checks that we guard against.
These guards are extremely important to guarantee accurate time and cannot be avoided.
If MuTime fails to initialise (because of the above exception being thrown), then a
MissingTimeDataException
is thrown if you try to request an actual date via MuTime.now()
.
It's pretty simple:
time.apple.com
has worked bestOr if you want the library to just handle that, use the Rx-ified version of the library (note the -rx suffix):
compile 'com.github.instacart.truetime-android:library-extension-rx:<release-version>'
With MuTimeRx, we go the whole nine yards and implement the complete NTP Spec.
We:-
If you don't use MuTimeRx, you don't get these benefits.
Original Work (c) Instacart/Kaushik Gopal 2016-2017
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.