summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/plugins/locationlayer/StaleStateManager.java
blob: 5c180b5c47fe018d59af50f9f0671375d57251a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.mapbox.mapboxsdk.plugins.locationlayer;

import android.os.Handler;

/**
 * Class controls the location layer stale state when the {@link android.location.Location} hasn't
 * been updated in 'x' amount of time. {@link LocationLayerOptions#staleStateTimeout()} can be used to
 * control the amount of time before the locations considered stale.
 * {@link LocationLayerOptions#enableStaleState()} is available for disabling this behaviour.
 */
class StaleStateManager {

  private final OnLocationStaleListener innerOnLocationStaleListeners;
  private final Handler handler;
  private boolean isStale = true;
  private long delayTime;

  StaleStateManager(OnLocationStaleListener innerListener, long delayTime) {
    innerOnLocationStaleListeners = innerListener;
    this.delayTime = delayTime;
    handler = new Handler();
    innerOnLocationStaleListeners.onStaleStateChange(true);
  }

  private Runnable staleStateRunnable = new Runnable() {
    @Override
    public void run() {
      isStale = true;
      innerOnLocationStaleListeners.onStaleStateChange(true);
    }
  };

  boolean isStale() {
    return isStale;
  }

  void updateLatestLocationTime() {
    if (isStale) {
      isStale = false;
      innerOnLocationStaleListeners.onStaleStateChange(false);
    }
    postTheCallback();
  }

  void setDelayTime(long delayTime) {
    this.delayTime = delayTime;
    postTheCallback();
  }

  void onStart() {
    if (!isStale) {
      postTheCallback();
    }
  }

  void onStop() {
    handler.removeCallbacksAndMessages(null);
  }

  private void postTheCallback() {
    handler.removeCallbacksAndMessages(null);
    handler.postDelayed(staleStateRunnable, delayTime);
  }
}