Giter Site home page Giter Site logo

homayoonahmadi / realtime Goto Github PK

View Code? Open in Web Editor NEW
3.0 1.0 1.0 159 KB

Reliable time library for Android. Initialize the current time using one of several time providers (like GPS, NTP, or a server's date header) and get current reliable time impervious to device clock changes by the user until the next device boot.

Java 100.00%
android current-date gps-time ntp-server reliable-datetime

realtime's Introduction

RealTime

platform API Jitpack

RealTime is a reliable time library for Android. Just initialize the current time using one of several time providers like GPS, NTP servers, or your own server and get current reliable time impervious to device clock changes by the user until the next device boot.

Introduction Video

RealTime.introduction.mp4

Features

  • RealTime provides 3 different time providers:
    • Location providers [Using GPS]
    • NTP servers [Network Time Protocol servers]
    • Your custom-defined server [Using date header]
  • RealTime detects device reboot and will reinitialize dateTime automatically after rebooting
  • RealTime will detect network detection status changes and location provider ON/OFF changes and requests for the current time if it has not been initialized yet

How to add dependency:

Step 1. Add the JitPack repository to your build.gradle file

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

Step 2. Add the dependency

dependencies {
    implementation 'com.github.homayoonahmadi:RealTime:1.3.0'
}

How to use

Add this to onCreate method of your Application class:

RealTime.builder(this)
      .withGpsProvider()
      .withNtpServer("time.nist.gov")
      .withNtpServer("time.google.com")
      .withNtpServer("time.windows.com")
      .withTimeServer("https://bing.com")
      .withTimeServer("https://google.com")
      .setLoggingEnabled(BuildConfig.DEBUG)
      .setSyncBackoffDelay(30, TimeUnit.SECONDS)
      .build(date -> Log.d(TAG, "RealTime is initialized, current dateTime: " + date));

Then everywhere you need reliable time first you need to check if RealTime is initialized or not:

if (RealTime.isInitialized()) {
    // Get current dateTime:
    Date  = RealTime.now();

    // You can show it in a text view
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, dd MMMM yyyy HH:mm:ss z", Locale.ENGLISH);
    binding.txtDateTime.setText(simpleDateFormat.format(date));
} else {
    binding.txtDateTime.setText("RealTime is not initialized yet.");
}

Notes

  • If you want to use a custom server, ensure the server's time is correct and reliable.
  • RealTime tries to get time using a retry with delay strategy if the current network doesn't have an internet connection yet.
  • RealTime will not add location permissions to manifest automatically. If you want to use a GPS provider, add the required permissions to your manifest:
<manifest ... >
  <!-- Always include this permission -->
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

  <!-- Include only if your app benefits from precise location access. -->
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>

NTP servers tested:

time.nist.gov
time-a.nist.gov
time.google.com
time.windows.com
1.us.pool.ntp.org
ir.pool.ntp.org

Methods

  • RealTime class methods
method description
withNtpServer(String ntpHost) This function will enable and set the URL of the NTP server.
withTimeServer(String serverHost) This function will enable and set the URL of the custom server.
withGpsProvider() This function enables gps provider if required permissions exist in the manifest.
setLoggingEnabled(boolean enabled) Sets if logs need to be logged in.
build() Starts to initialize RealTime using enabled providers.
build(OnRealTimeInitializedListener listener) Starts to initialize RealTime using enabled providers and will call onInitializedListener's onInitialized(Date date) interface.
isInitialized() Returns true if RealTime is initialized or false otherwise.
now() Returns current reliable dateTime if the class has initialized.
clearCachedInfo() This function clears all cached data so RealTime tries to initialize dateTime again.

realtime's People

Contributors

homayoonahmadi avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Forkers

salan1

realtime's Issues

null pointer exception

hi, i am experiencing some null pointer exception using your code for tests.

Here the stack trace registered by crashlytics

Fatal Exception: java.lang.NullPointerException: Attempt to invoke interface method 'void com.android.okhttp.internal.http.HttpStream.writeRequestHeaders(com.android.okhttp.Request)' on a null object reference at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:606) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:475) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getHeaders(HttpURLConnectionImpl.java:167) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getHeaderFields(HttpURLConnectionImpl.java:227) at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getHeaderFields(DelegatingHttpsURLConnection.java:179) at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getHeaderFields(HttpsURLConnectionImpl.java:30) at ir.programmerplus.realtime.RealTime.fetchTimeServer(RealTime.java:380) at ir.programmerplus.realtime.RealTime.lambda$requestTimeServer$1(RealTime.java:345) at io.reactivex.internal.operators.single.SingleFromCallable.subscribeActual(SingleFromCallable.java:44) at io.reactivex.Single.subscribe(Single.java:3394) at io.reactivex.internal.operators.single.SingleToFlowable.subscribeActual(SingleToFlowable.java:37) at io.reactivex.Flowable.subscribe(Flowable.java:14409) at io.reactivex.Flowable.subscribe(Flowable.java:14356) at io.reactivex.internal.operators.flowable.FlowableRepeatWhen$WhenReceiver.onNext(FlowableRepeatWhen.java:101) at io.reactivex.internal.operators.flowable.FlowableRetryWhen.subscribeActual(FlowableRetryWhen.java:62) at io.reactivex.Flowable.subscribe(Flowable.java:14409) at io.reactivex.internal.operators.flowable.FlowableSingleSingle.subscribeActual(FlowableSingleSingle.java:39) at io.reactivex.Single.subscribe(Single.java:3394) at io.reactivex.internal.operators.single.SingleDoOnDispose.subscribeActual(SingleDoOnDispose.java:38) at io.reactivex.Single.subscribe(Single.java:3394) at io.reactivex.internal.operators.single.SingleSubscribeOn$SubscribeOnObserver.run(SingleSubscribeOn.java:89) at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:579) at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66) at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57) at java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:307) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:644) at java.lang.Thread.run(Thread.java:1012)

i'm using a initialization in a try/catch block but exception will be still raised
try {
RealTime.builder(this)
// .withGpsProvider()
.withNtpServer("time.nist.gov")
.withNtpServer("time.google.com")
.withNtpServer("time.windows.com")
.withTimeServer("https://bing.com")
.withTimeServer("https://google.com")
.setLoggingEnabled(BuildConfig.DEBUG)
// .setSyncBackoffDelay(60, TimeUnit.SECONDS)
.build(date -> Log.d("REALTIME", "RealTime is initialized, current dateTime: " + date));
} catch (Exception e) {}

Thank you in advantance for reply!

Bye

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.