Skip to content

Instantly share code, notes, and snippets.

@fnovoac
Created July 7, 2018 14:22
Show Gist options
  • Save fnovoac/a37054b60bac5ecbd07513389b5cb98c to your computer and use it in GitHub Desktop.
Save fnovoac/a37054b60bac5ecbd07513389b5cb98c to your computer and use it in GitHub Desktop.
import android.annotation.SuppressLint;
import android.arch.lifecycle.LiveData;
import android.content.Context;
import android.location.Location;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
public class CurrentLocationListener extends LiveData<Location> {
private static final String TAG = "CurrentLocationListener";
private static final int ONE_SECOND = 1000;
private static CurrentLocationListener mInstance;
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest;
public static CurrentLocationListener getInstance(Context appContext) {
if (mInstance == null) {
mInstance = new CurrentLocationListener(appContext);
}
return mInstance;
}
@SuppressLint("MissingPermission")
private CurrentLocationListener(Context appContext) {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(appContext);
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null)
setValue(location);
}
});
createLocationRequest();
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(ONE_SECOND);
mLocationRequest.setFastestInterval(ONE_SECOND);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@SuppressLint("MissingPermission")
@Override
protected void onActive() {
super.onActive();
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
}
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
if (location != null)
setValue(location);
}
}
};
@Override
protected void onInactive() {
super.onInactive();
if (mLocationCallback != null)
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment