TrueTime for Android


Source link: https://github.com/instacart/truetime-android

TrueTime for Android

Make sure to check out our counterpart too: TrueTime, an NTP library for Swift.

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. TrueTime gives you that.

You can read more about the use case in our blog post.

In a recent conference talk, we explained how the full NTP implementation works with Rx. Check the video and slides out for implementation details.

How is TrueTime calculated?

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. Each time "now" is requested subsequently, we account for that offset and return a corrected Date object.

Also, once we have this 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 your users have a memory starved device.

Installation

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.instacart.truetime-android:library-extension-rx:<release-version>'

// or if you want the vanilla version of Truetime:
  compile 'com.github.instacart.truetime-android:library:<release-version>' 
}

Usage

Vanilla version

Importing 'com.github.instacart.truetime-android:library:<release-version>' should be sufficient for this.

TrueTime.build().initialize();

initialize must be run on a background thread. If you run it on the main thread, you will get a NetworkOnMainThreadException

You can then use:

Date noReallyThisIsTheTrueDateAndTime = TrueTime.now();

... #winning

Rx-ified Version

If you're down to using RxJava then we go all the way and implement the full NTP. Use the nifty initializeRx() api which takes in an NTP pool server host.

TrueTimeRx.build()

.initializeRx("time.google.com")

.subscribeOn(Schedulers.io())

.subscribe(date -> {

 Log.v(TAG, "TrueTime was initialized and we have a time: " + date);

}
, throwable -> {

 throwable.printStackTrace();

}
);

Now, as before:

TrueTimeRx.now();
 // return a Date object with the "true" time.

What is nifty about the Rx version?

  • as against just SNTP, you get full NTP (read: far more accurate time)
  • the NTP pool address you provide is resolved into multiple IP addresses
  • we query each IP multiple times, guarding against checks, and taking the best response
  • if any one of the requests fail, we retry that failed request (alone) for a specified number of times
  • we collect all the responses and again filter for the best result as per the NTP spec

Notes/tips:

  • Each initialize call makes an SNTP network request. TrueTime needs to be initialized only once ever, per device boot. Use TrueTime's withSharedPreferences option to make use of this feature and avoid repeated network request calls.
  • Preferable use dependency injection (like Dagger) and create a TrueTime @Singleton object
  • You can read up on Wikipedia the differences between SNTP and NTP.
  • TrueTime is also available for iOS/Swift

Troubleshooting/Exception handling:

When you execute the TrueTime initialization, you are very highly 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.

Why does this happen?

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.

How do I handle or protect against this in my application?

It's pretty simple:

  • keep retrying the request, until you get a successful one. Yes it does happen eventually :)
  • Try picking a better NTP pool server. In our experience time.apple.com has worked best

Or 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 TrueTimeRx, we go the whole nine yards and implement the complete NTP Spec (we resolve the DNS for the provided NTP host to single IP addresses, shoot multiple requests to that single IP, guard against the above mentioned checks, retry every single failed request, filter the best response and persist that to disk). If you don't use TrueTimeRx, you don't get these benefits.

We welcome PRs for folks who wish to replicate the functionality in the vanilla TrueTime version. We don't have plans of re-implementing that functionality atm in the vanilla/simple version of TrueTime.

Do also note, if TrueTime fails to initialize (because of the above exception being thrown), then an IllegalStateException is thrown if you try to request an actual date via TrueTime.now().

License

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. 

Resources

Typesafe way to use intents and bundles in android.

Masked-Edittext android library EditText widget wrapper add masking and formatting input text functionality.

AndResGuard is a tool to proguard resource for Android, just like ProGuard in Java. It can change res/drawable/wechat to r/d/a, and rename the resource file wechat.png to a.png. Finally, it repackages the apk with 7zip, which can reduce the package size obviously.

Simple Android Utility Methods.

Cross-platform mobile app development for iOS and Android. Build native UI's with full hardware access using Java.

Run a method once or repeat after some iterations. Super simple, One liners.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes