Tempo


Source link: https://github.com/AllanHasegawa/Tempo

Tempo

A Kotlin library for Android to get the current time from multiple sources: SNTP, GPS; or your own time source.

Why is it important?

System.currentTimeMillis() [...] can be set by the user [...] so the time may jump backwards or forwards unpredictably.

-- https://developer.android.com/reference/android/os/SystemClock.html. July, 2017.

You can check how Tempo works in this blog post.

Basic usage

Initialize the library in your Application class:

class MyApp : Application {

  override fun onCreate() {

Tempo.initialize(this)

...
  
}
 
}
 

After the library is initialized, you can get the time with:

val timeNowInMs = Tempo.now() 

Tempo::now() will return either a Long or a null. A null is returned when Tempo has not been initialized yet. When initialized, Tempo::now() returns the current unix epoch time in milliseconds.

You can observe all the events emitted by the library:

Tempo.observeEvents().subscribe {

  if (it is Tempo.Initialized) {

Log.i("Tempo", "Initialized!")
  
}
 
}
 

Dependency

Add the snippet below in your root build.gradle at the end of repositories:

allprojects {

  repositories {

...

maven {
 url 'https://jitpack.io' 
}

  
}
 
}
 

Then, add the dependency to your module:

dependencies {

  compile 'com.github.AllanHasegawa.Tempo:tempo:x.y.z' 
}
 

Time Sources

Tempo comes with two sources for time: SlackSntpTimeSource and AndroidGPSTimeSource.

SlackSntpTimeSource

The SlackSntpTimeSource is the default time source. Tempo is using a SNTP client implementation from the Android Framework. However, it's named "slack" because we are not enforcing a minimum roundtrip delay. The main reason behind this decision is because users with poor connection (very common on mobile) may never get a low enough roundtrip delay to successfully complete a SNTP request; retrying will just waste battery and increate data consumption. Therefore, this is the recommended time source to be used for Android.

This time source requires an active internet connection to work.

AndroidGPSTimeSource

The AndroidGPSTimeSource uses the device's GPS to get the current time. The accuracy will vary depending on the GPS.

This time source is in a separated module because it adds the ACCESS_FINE_LOCATION permission. Only use this module if you need this functionality.

To include it in your project, include the dependency:

compile 'com.github.AllanHasegawa.Tempo:tempo-android-gps-time-source:x.y.z' 

Then, add it during initialization:

Tempo.initialize(this,
timeSources = listOf(SlackSntpTimeSource(), AndroidGPSTimeSource(this)) 

Warning: If you are targeting Android SDK 23 or higher, you will have to request for the GPS permission at runtime.

Custom time source

You can create your own time source. Implement the io.tempo.TimeSource interface and then add it during initialization:

val customTs = MyCustomTs() Tempo.initialize(this,
timeSources = listOf(customTs)) 

Schedulers

A device's clock slowly drifts away from an accurate time. Therefore, Tempo also offers an scheduler to automatically sync its time.

To add, first include its module to your gradle build file:

compile 'com.github.AllanHasegawa.Tempo:tempo-android-job-scheduler:x.y.z' 

Then, add it during initialization:

Tempo.initialize(this,
scheduler = AndroidJobScheduler(this, periodicIntervalMinutes = 60L)) 

This module uses the awesome android-job library. Unfortunately it also means we are also using the GcmNetworkManager dependency–a really heavy dependency. That's why you have to add it manually if you want it.

FAQ

  1. What happens if the application gets destroyed?

By default, Tempo survives an application's process death. It accomplishes it by saving its state in the app's shared preference storage.

  1. What happens if the user reboots the device?

We invalidate all cache and a complete sync is required.

  1. What happens if the user has no internet access, no GPS, and rebooted his phone?

Then you should use a fallback strategy, like System.currentTimeMillis().

  1. Will Tempo ever support Java?

If there's enough interest. Open an issue if you would like to use it with Java.

License

Copyright (c) 2017 Allan Yoshio Hasegawa  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

Storm was created with intention to be easy to use ORM solution for Android platform. While working for a corporate client we realised that the available tools either expect too much to be done manually, or are super-complicated or just want entities to extend their own.

Simple wrapper library in Kotlin is designed to save secret to local shared preferences using Android default security and Android Keystore. KeystoreCompat ensures handling LockScreen and compatibility among diversity of Android versions.

A light-weight utility library that does the following things:

  • To check internet connection.
  • Validation for empty EditText boxes.
  • Validation for mobile number.
  • Validate EditText values against user defined patterns (e.g mobile number patterns).
  • Validate length of EditText values.
  • Validation for special characters in EditText values.
  • To show Toast messages.

This is an Android Library for developer to use customized calendar with all type of views and features, like Month View, Week View, Day View, Agenda, Add Events, Add Holiday etc. So all of these features contain in one calendar.

A View for cropping images that is similar to Instagram's crop. Also an Activity for cropping is included.

ApiResponse simplifies handling standardized API JSON responses. It follows the API response format as produced by Api Response Builder library.

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