Code Monkey home page Code Monkey logo

tempo's Introduction

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.nowOrNull()

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

Tip: Avoid using Tempo::nowOrNull() for critical operations that requires the time. Use Tempo::now() as it'll return a result whenever one is available.

You can observe all the events emitted by the library:

Tempo.addEventsListener { event -> Log.d("TempoEvent", event.toString()) }

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'
}

Release

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. By default Tempo will periodically sync itself when the app is running.

However, because Tempo will not sync while the app is not running then starting the app may require a full sync, which can take time. To be able to sync even when the app is not running and making sure the app will always have a fresh cache, Tempo also offers a scheduler using Android's WorkManager.

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

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

Then, add it during initialization:

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

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?

No official support for Java because Kotlin is now the official language for Android. However, it "should" work with Java.

  1. Do I need to add any Proguard rules to my project?

No. Tempo should work under a Proguarded app without any specific Proguard rule.

License

Copyright (c) 2020 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.

tempo's People

Contributors

allanhasegawa avatar skjolber avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tempo's Issues

Offline + Changing Device Time Problem

I tried a few things on the sample application which displays the System time and Tempo time.
When you run the app (Internet Connected), it shows the time correctly for Tempo time even if you go to Settings of Phone and change device time. Now if you turn off the Internet (Mobile data and Wifi) and run the app again, still it will work fine. Now closing the app again with the Internet off and then going to settings and changing device time, now try and open the app, Tempo time show blank because some exception is thrown. Is this the normal case or is it really a bug?

All NTP Request failed: RoundTrip time exceeded

Found issue from production crashlytics. Proguard enabled, so complete error may/may not be visible. Still this is the crash log available.

Fatal Exception: io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. 
Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | 
io.tempo.time_sources.SlackSntpTimeSource$AllRequestsFailure: All NTP requests failed: [RoundTrip time exceeded allowed threshold: took 1907, but max is 1000; RoundTrip time exceeded allowed threshold: took 1888, but max is 1000; Error transmitting request/response; RoundTrip time exceeded allowed threshold: took 1922, but max is 1000; RoundTrip time exceeded allowed threshold: took 1884, but max is 1000]
   at io.reactivex.plugins.RxJavaPlugins.onError + 367(RxJavaPlugins.java:367)
   at io.reactivex.internal.operators.single.SingleTimeout$TimeoutMainObserver.onError + 152(SingleTimeout.java:152)
   at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onError + 69(SingleMap.java:69)
   at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onError + 69(SingleMap.java:69)
   at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onSuccess + 60(SingleMap.java:60)
   at io.reactivex.internal.operators.single.SingleFlatMap$SingleFlatMapCallback$FlatMapSingleObserver.onSuccess + 111(SingleFlatMap.java:111)
   at io.reactivex.internal.operators.single.SingleZipArray$ZipCoordinator.innerSuccess + 119(SingleZipArray.java:119)
   at io.reactivex.internal.operators.single.SingleZipArray$ZipSingleObserver.onSuccess + 170(SingleZipArray.java:170)
   at io.reactivex.internal.operators.single.SingleOnErrorReturn$OnErrorReturn.onSuccess + 82(SingleOnErrorReturn.java:82)
   at io.reactivex.internal.operators.single.SingleObserveOn$ObserveOnSingleObserver.run + 81(SingleObserveOn.java:81)
   at io.reactivex.Scheduler$DisposeTask.run + 578(Scheduler.java:578)
   at io.reactivex.internal.schedulers.ScheduledRunnable.run + 66(ScheduledRunnable.java:66)
   at io.reactivex.internal.schedulers.ScheduledRunnable.call + 57(ScheduledRunnable.java:57)
   at java.util.concurrent.FutureTask.run + 237(FutureTask.java:237)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201 + 152(ScheduledThreadPoolExecutor.java:152)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run + 265(ScheduledThreadPoolExecutor.java:265)
   at java.util.concurrent.ThreadPoolExecutor.runWorker + 1112(ThreadPoolExecutor.java:1112)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run + 587(ThreadPoolExecutor.java:587)
   at java.lang.Thread.run + 818(Thread.java:818)



Caused by io.tempo.time_sources.SlackSntpTimeSource$AllRequestsFailure: All NTP requests failed: [RoundTrip time exceeded allowed threshold: took 1907, but max is 1000; RoundTrip time exceeded allowed threshold: took 1888, but max is 1000; Error transmitting request/response; RoundTrip time exceeded allowed threshold: took 1922, but max is 1000; RoundTrip time exceeded allowed threshold: took 1884, but max is 1000]
   at io.tempo.time_sources.SlackSntpTimeSource$requestTime$3.apply + 92(SlackSntpTimeSource.java:92)
   at io.tempo.time_sources.SlackSntpTimeSource$requestTime$3.apply + 40(SlackSntpTimeSource.java:40)
   at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onSuccess + 57(SingleMap.java:57)
   at io.reactivex.internal.operators.single.SingleFlatMap$SingleFlatMapCallback$FlatMapSingleObserver.onSuccess + 111(SingleFlatMap.java:111)
   at io.reactivex.internal.operators.single.SingleZipArray$ZipCoordinator.innerSuccess + 119(SingleZipArray.java:119)
   at io.reactivex.internal.operators.single.SingleZipArray$ZipSingleObserver.onSuccess + 170(SingleZipArray.java:170)
   at io.reactivex.internal.operators.single.SingleOnErrorReturn$OnErrorReturn.onSuccess + 82(SingleOnErrorReturn.java:82)
   at io.reactivex.internal.operators.single.SingleObserveOn$ObserveOnSingleObserver.run + 81(SingleObserveOn.java:81)
   at io.reactivex.Scheduler$DisposeTask.run + 578(Scheduler.java:578)
   at io.reactivex.internal.schedulers.ScheduledRunnable.run + 66(ScheduledRunnable.java:66)
   at io.reactivex.internal.schedulers.ScheduledRunnable.call + 57(ScheduledRunnable.java:57)
   at java.util.concurrent.FutureTask.run + 237(FutureTask.java:237)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201 + 152(ScheduledThreadPoolExecutor.java:152)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run + 265(ScheduledThreadPoolExecutor.java:265)
   at java.util.concurrent.ThreadPoolExecutor.runWorker + 1112(ThreadPoolExecutor.java:1112)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run + 587(ThreadPoolExecutor.java:587)
   at java.lang.Thread.run + 818(Thread.java:818)

UndeliverableException

Looks like some error inside Tempo to suddenly crashes our app in production.

ErrnoException: sendto failed: EPERM (Operation not permitted)
at libcore.io.Linux.sendtoBytes(Linux.java)
at libcore.io.Linux.sendto(Linux.java:227)
at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:307)
at libcore.io.IoBridge.sendto(IoBridge.java:542)
at java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:125)
...
(17 additional frame(s) were not displayed)

IOException: sendto failed: EPERM (Operation not permitted)
at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:576)
at libcore.io.IoBridge.sendto(IoBridge.java:544)
at java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:125)
at java.net.DatagramSocket.send(DatagramSocket.java:723)
at io.tempo.internal.AndroidSntpClient$requestTime$2.invoke(AndroidSntpClient.kt:89)
...
(15 additional frame(s) were not displayed)

AllRequestsFailure: All NTP requests failed: [Error transmitting request/response; Error transmitting request/response; Error transmitting request/response; Error transmitting request/response; Error transmitting request/response]
at io.tempo.time_sources.SlackSntpTimeSource$requestTime$3.apply(SlackSntpTimeSource.kt:92)
at io.tempo.time_sources.SlackSntpTimeSource$requestTime$3.apply(SlackSntpTimeSource.kt:40)
at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onSuccess(SingleMap.java:57)
at io.reactivex.internal.operators.single.SingleFlatMap$SingleFlatMapCallback$FlatMapSingleObserver.onSuccess(SingleFlatMap.java:111)
at io.reactivex.internal.operators.single.SingleZipArray$ZipCoordinator.innerSuccess(SingleZipArray.java:119)
...
(11 additional frame(s) were not displayed)

UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | io.tempo.time_sources.SlackSntpTimeSource$AllRequestsFailure: All NTP requests failed: [Error transmitting request/response; Error transmitting request/response; Error transmitting request/response; Error transmitting request/response; Error transmitting request/response]
at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:367)
at io.reactivex.internal.operators.single.SingleTimeout$TimeoutMainObserver.onError(SingleTimeout.java:152)
at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onError(SingleMap.java:69)
at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onError(SingleMap.java:69)
at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onSuccess(SingleMap.java:60)
...
(13 additional frame(s) were not displayed)

The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | io.tempo.time_sources.SlackSntpTimeSource$AllRequestsFailure: All NTP requests failed: [Error transmitting request/response; Error transmitting request/response; Error transmitting request/response; Error transmitting request/response; Error transmitting request/response]

AndroidSntpClient UndeliverableException

I have a lot of crashes in my app remote logs, but I can't reproduce them in local. Any suggestion?
This is the crash report:

Fatal Exception: io.reactivex.exceptions.UndeliverableException: io.tempo.internal.AndroidSntpClient$InetException: Error getting the host (time.google.com) inet address.
at io.reactivex.plugins.RxJavaPlugins.onError(SourceFile:367)
at io.reactivex.internal.operators.single.SingleFromCallable.subscribeActual(SourceFile:50)
at io.reactivex.Single.subscribe(SourceFile:3310)
at io.reactivex.internal.operators.single.SingleSubscribeOn$SubscribeOnObserver.run(SourceFile:89)
at io.reactivex.Scheduler$DisposeTask.run(SourceFile:579)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(SourceFile:66)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(SourceFile:57)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)

Caused by io.tempo.internal.AndroidSntpClient$InetException: Error getting the host (time.google.com) inet address.
at io.tempo.internal.AndroidSntpClient.queryHostAddress(SourceFile:55)
at io.tempo.time_sources.SlackSntpTimeSource$requestTime$1.call(SourceFile:52)
at io.tempo.time_sources.SlackSntpTimeSource$requestTime$1.call(SourceFile:39)
at io.reactivex.internal.operators.single.SingleFromCallable.subscribeActual(SourceFile:44)
at io.reactivex.Single.subscribe(SourceFile:3310)
at io.reactivex.internal.operators.single.SingleSubscribeOn$SubscribeOnObserver.run(SourceFile:89)
at io.reactivex.Scheduler$DisposeTask.run(SourceFile:579)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(SourceFile:66)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(SourceFile:57)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)

Some Questions and feature requests

  1. Is there ever a need to call Tempo.stop() ?
  2. Is is possible to have a function to completely clear all currently scheduled work requests?
  3. Can we have an api to add worker constraints to the WorkManagerScheduler e.g. below
val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .setRequiresBatteryNotLow(true)
            .build()
  1. Is there a need for autoSyncConfig, if i have already a WorkManagerScheduler?

Document proguard rules (if any)

I'm obfuscating my application, and it would be helpful if the docs contained a note on the correct proguard configuration (or if no special configuration is requird).

TempoEvent.Initialized event not sent

Hey,

I'm using Tempo 1.1.0-alpha01 in one of my apps (Kotlin 1.4.30, Coroutines 1.4.3). Tempo.initialize() is being called during the execution of the onCreate-Method of its MainActivity. Prior to calling Tempo.initialize() an event listener is registered which listens for the TempoEvent.Initialized event. In case this event occurs, the remaining app components are being initialized, because they need a synchronized time. The code is as follows:

override fun onCreate(savedInstanceState: Bundle?) {
    Tempo.addEventsListener { event ->
        log.debug("[Tempo] Event received: ${event.javaClass.name}")
        if (event is TempoEvent.Initialized) {
            Tempo.nowOrNull()?.let { now ->
                // Initialize components
            }
        }
    }

    Tempo.initialize(
        application = application,
        timeSources = listOf(SlackSntpTimeSource(ntpPool = Constants.SERVER_URL))
    )
}

The problem I'm facing right now is that in some cases the TempoEvent.Initialized event does not seem to be sent although the time has been synchronized successfully. Thus the app doesn't start. Here's a log of the situation:

2021-06-01 09:21:54.381 [Tempo] Event received: io.tempo.TempoEvent$Initializing
2021-06-01 09:21:54.383 [Tempo] Event received: io.tempo.TempoEvent$SchedulerSetupSkip
2021-06-01 09:21:54.383 [Tempo] Event received: io.tempo.TempoEvent$SyncStart
2021-06-01 09:21:54.383 [Tempo] Event received: io.tempo.TempoEvent$TSSyncRequest
2021-06-01 09:21:54.464 [Tempo] Event received: io.tempo.TempoEvent$CacheRestored
2021-06-01 09:21:54.672 D/SharedPreferencesImpl: Time required to fsync /data/user/0/com.doks.dronectrl/shared_prefs/tempo-bucket.xml: [<1: 0, <2: 0, <4: 0, <8: 0, <16: 0, <32: 0, <64: 0, <128: 0, <256: 0, <512: 1, <1024: 0, <2048: 0, <4096: 0, <8192: 0, <16384: 0, >=16384: 0]
2021-06-01 09:21:54.673 [Tempo] Event received: io.tempo.TempoEvent$CacheSaved
2021-06-01 09:21:54.675 [Tempo] Event received: io.tempo.TempoEvent$TSSyncSuccess
2021-06-01 09:21:54.676 [Tempo] Event received: io.tempo.TempoEvent$SyncSuccess

As one can see from the log, the time has been synchronized (TempoEvent.SyncSuccess) but the TempoEvent.Initialized is not being sent (or received).

Any help or idea would be appreciated!

Thanks and best regards,

Jens

AndroidX Support

Hi Allan, I'm close to being able to turn Jetifier off in my app and was curious if you'd be open to updating Tempo's Android support libs to use AndroidX? Happy to help with a CR if you're open to it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.