Skip to content
This repository has been archived by the owner on Aug 8, 2023. It is now read-only.

Commit

Permalink
[android] do not post stale state message when new option provided bu…
Browse files Browse the repository at this point in the history
…t the component is stopped
  • Loading branch information
LukasPaczos committed Feb 19, 2019
1 parent ff5a607 commit 4597756
Showing 1 changed file with 28 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.mapbox.mapboxsdk.location;

import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;

import java.lang.ref.WeakReference;

/**
* Class controls the location stale state when the {@link android.location.Location} hasn't
* been updated in 'x' amount of time. {@link LocationComponentOptions#staleStateTimeout()} can be used to
Expand All @@ -14,25 +17,19 @@ class StaleStateManager {
private boolean isEnabled;
private final OnLocationStaleListener innerOnLocationStaleListeners;
@NonNull
private final Handler handler;
private final StaleMessageHandler handler;
private boolean isStale = true;
private long delayTime;

private final int staleStateMessage = 1;

StaleStateManager(OnLocationStaleListener innerListener, LocationComponentOptions options) {
innerOnLocationStaleListeners = innerListener;
handler = new Handler();
handler = new StaleMessageHandler(this);
isEnabled = options.enableStaleState();
delayTime = options.staleStateTimeout();
}

@NonNull
private Runnable staleStateRunnable = new Runnable() {
@Override
public void run() {
setState(true);
}
};

void setEnabled(boolean enabled) {
if (enabled) {
setState(isStale);
Expand All @@ -54,7 +51,9 @@ void updateLatestLocationTime() {

void setDelayTime(long delayTime) {
this.delayTime = delayTime;
postTheCallback();
if (handler.hasMessages(staleStateMessage)) {
postTheCallback();
}
}

void onStart() {
Expand All @@ -69,7 +68,7 @@ void onStop() {

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

private void setState(boolean stale) {
Expand All @@ -80,4 +79,21 @@ private void setState(boolean stale) {
}
}
}

private static class StaleMessageHandler extends Handler {

private final WeakReference<StaleStateManager> managerWeakReference;

private StaleMessageHandler(StaleStateManager staleStateManager) {
this.managerWeakReference = new WeakReference<>(staleStateManager);
}

@Override
public void handleMessage(Message msg) {
StaleStateManager manager = managerWeakReference.get();
if (manager != null) {
manager.setState(true);
}
}
}
}

0 comments on commit 4597756

Please sign in to comment.