Skip to content

Instantly share code, notes, and snippets.

@AliAzaz
Last active January 10, 2020 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AliAzaz/5d9e2cfcf95a3335917de11d44e19a4a to your computer and use it in GitHub Desktop.
Save AliAzaz/5d9e2cfcf95a3335917de11d44e19a4a to your computer and use it in GitHub Desktop.
Location listener service
public class LocationService extends Service {
public static final String BROADCAST_ACTION = "GettingLoc";
private static final int TWO_MINUTES = 1000 * 60 * 2;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 2000; // in Milliseconds
public LocationManager locationManager;
public GPSLocationListener listener;
public Location previousBestLocation = null;
Intent intent;
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
@Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
@Override
public void onCreate() {
super.onCreate();
intent = new Intent();
intent.setAction(BROADCAST_ACTION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return START_STICKY;
}
listener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
listener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
listener);
return START_STICKY;
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else return isNewer && !isSignificantlyLessAccurate && isFromSameProvider;
}
/**
* Checks whether two providers are the same
*/
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public void onDestroy() {
// handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
locationManager.removeUpdates(listener);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public class GPSLocationListener implements LocationListener {
public void onLocationChanged(final Location loc) {
Log.i("Loc Service:", "Location changed");
// Get last location from shared preference
LocationModel locationModel = getLastLocation();
previousBestLocation = new Location("storedProvider");
previousBestLocation.setAccuracy(Float.parseFloat(locationModel.getAcc()));
previousBestLocation.setTime(Long.parseLong(locationModel.getTime()));
previousBestLocation.setLatitude(Float.parseFloat(locationModel.getLat()));
previousBestLocation.setLongitude(Float.parseFloat(locationModel.getLng()));
if (isBetterLocation(loc, previousBestLocation)) {
setLastLocation(new LocationModel(String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()),
String.valueOf(loc.getAccuracy()), String.valueOf(loc.getTime())));
intent.putExtra(LocationINFO.COLUMN_GPSLAT, loc.getLatitude());
intent.putExtra(LocationINFO.COLUMN_GPSLNG, loc.getLongitude());
intent.putExtra(LocationINFO.COLUMN_GPSACC, loc.getAccuracy());
sendBroadcast(intent);
} else {
intent.putExtra(LocationINFO.COLUMN_GPSLAT, loc.getLatitude());
intent.putExtra(LocationINFO.COLUMN_GPSLNG, loc.getLongitude());
intent.putExtra(LocationINFO.COLUMN_GPSACC, loc.getAccuracy());
sendBroadcast(intent);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment