Skip to content

Instantly share code, notes, and snippets.

@pratikbutani
Created June 14, 2019 13:07
Show Gist options
  • Save pratikbutani/8171ef0ebbd9fbadaf12e8408a446998 to your computer and use it in GitHub Desktop.
Save pratikbutani/8171ef0ebbd9fbadaf12e8408a446998 to your computer and use it in GitHub Desktop.
Location Helper Activity to get continuously updates of location in your child activity. Just extend this activity in your every child activity where you want to get updates.
public abstract class LocationHelperActivity extends AppCompatActivity {
private static final String TAG = "LocationHelperActivity";
private static final int PERMISSION_REQUEST_CODE = 200;
public static final long INTERVAL = 1000 * 3 * 60; // 3 = 3 minutes
public static final long FASTEST_INTERVAL = 1000 * 60; // 60 = 60 seconds = 1 minutes
public String mCurrentLatitude = "";
public String mCurrentLongitude = "";
// GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
protected FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onResume() {
super.onResume();
if (!CommonUses.checkForLocationEnabled(this)) {
final android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(LocationHelperActivity.this);
dialog.setMessage(getString(R.string.alert_gps_title));
dialog.setCancelable(false);
dialog.setPositiveButton(getString(R.string.button_open_settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}
startLocationUpdates();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!checkLocationPermission()) {
ActivityCompat.requestPermissions(this,
new String[]{ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
initGoogleClient();
}
/**
* All about permission
*/
private boolean checkLocationPermission() {
int result3 = ContextCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION);
int result4 = ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION);
return result3 == PackageManager.PERMISSION_GRANTED &&
result4 == PackageManager.PERMISSION_GRANTED;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0) {
boolean coarseLocation = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean fineLocation = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (coarseLocation && fineLocation)
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
protected void onPause() {
super.onPause();
try {
stopLocationUpdates();
} catch (Exception e) {
Crashlytics.logException(e);
}
}
private void initGoogleClient() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(50);
/*
BUILDING GOOGLE API CLIENT
*/
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mCurrentLocation = locationResult.getLastLocation();
if (mCurrentLocation != null) {
double latitude = mCurrentLocation.getLatitude();
double longitude = mCurrentLocation.getLongitude();
//Latlong = getFormattedLocationInDegree(location.getLatitude(), location.getLongitude());
mCurrentLatitude = String.valueOf(latitude);
mCurrentLongitude = String.valueOf(longitude);
onNewLocation(latitude, longitude);
Log.i(TAG, "Last Location Request :" + mCurrentLatitude + "," + mCurrentLongitude);
}
}
};
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
try {
Log.d(TAG, "update started.......................");
mFusedLocationClient
.getLastLocation()
.addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mCurrentLocation = task.getResult();
if (mCurrentLocation != null) {
double latitude = mCurrentLocation.getLatitude();
double longitude = mCurrentLocation.getLongitude();
mCurrentLatitude = String.valueOf(latitude);
mCurrentLongitude = String.valueOf(longitude);
Log.i(TAG, "Updated Location Request :" + mCurrentLocation.getLatitude() + "," + mCurrentLocation.getLongitude());
onNewLocation(latitude, longitude);
}
} else {
Log.w(TAG, "Failed to get location.");
}
}
});
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
} catch (SecurityException unlikely) {
Log.e(TAG, "Lost location permission. Could not request updates. " + unlikely);
}
}
}
protected void updateLocation() {
startLocationUpdates();
}
private void stopLocationUpdates() {
try {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
Log.d(TAG, "Location update stopped .......................");
} catch (Exception e) {
Crashlytics.logException(e);
}
}
protected void onNewLocation(double latitude, double longitude){ }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment