Skip to content

Instantly share code, notes, and snippets.

@oyamo
Forked from Ephygtz/GPSLocation.java
Created April 16, 2019 12:25
Show Gist options
  • Save oyamo/e873858006bb2efc04cfa3f164b24ca2 to your computer and use it in GitHub Desktop.
Save oyamo/e873858006bb2efc04cfa3f164b24ca2 to your computer and use it in GitHub Desktop.
double mLatitude = 0.0;
double mLongitude = 0.0;
private FusedLocationProviderClient mFusedLocationClient;
// mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// ^ to be instatiated inside onCreate method
public void fetchGPS() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
double lat = location.getLatitude();
double lon = location.getLongitude();
mLatitude = lat;
mLongitude = lon;
}
});
}
static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2000;
boolean mLocationPermissionGranted = false;
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
//getDeviceLocation();
fetchGPS();
}
}
}
// updateLocationUI();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment