androidservicebroadcastreceiverlocationlistener

Android: Call Method when BroadcastReceiver hasn't had OnReceive trigger for N seconds


I am developing an app that needs constant/accurate location updates (User is evaluating infrastructure and will be taking photos of damage tagged to their location). Since I need to have the locationlistener running across multiple activities I followed this answer here and used a broadcast receiver to get the updates.

However, I realized that there's not really any consensus on how to check if the GPS signal is lost. I did notice that when I move indoors/lose signal the onReceive() ceases to activate.

Is there a way I can check if the OnReceive() function has failed to trigger in the last N seconds? Ideally I could have my locationlistener set with an update frequency of 1 Hz (1 per second), so if I go more than 10 seconds with no updates I can then indicate to the user that they are no longer receiving updates.


Solution

  • Since I need to have the locationlistener running across multiple activities I followed this answer here and used a broadcast reciever to get the updates.

    You would not necessarily need to use a BroadcastReceiver. The LocationListener approach can be used across multiple activities. You just need the listener and the stuff that manages it to be outside of any activity (e.g., some sort of repository, supplying data to your viewmodels via LiveData).

    Is there a way I can check if the OnRecieve() function has failed to trigger in the last N seconds?

    Step #1: Start an N-second timer when you register for location updates, such as using schedule() on a ScheduledExecutorService, or Single.timer() from RxJava

    Step #2: When onReceive() is called, cancel the existing timer (e.g., cancel() on the ScheduledFuture you get from schedule()) and schedule a fresh N-second timer

    Step #3: If you get control from the timer (e.g., your Callable or Runnable supplied to schedule() is invoked), you know that N seconds elapsed without having been called with onReceive()