Я використовую перший код, почати створювати метод isLocationEnabled
private LocationManager locationManager ;
protected boolean isLocationEnabled(){
String le = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(le);
if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
return false;
} else {
return true;
}
}
і я перевіряю Стан, якщо тире Відкрити карту та помилково дати наміру ACTION_LOCATION_SOURCE_SETTINGS
if (isLocationEnabled()) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationClient = getFusedLocationProviderClient(this);
locationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// GPS location can be null if GPS is switched off
if (location != null) {
onLocationChanged(location);
Log.e("location", String.valueOf(location.getLongitude()));
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("MapDemoActivity", e.toString());
e.printStackTrace();
}
});
startLocationUpdates();
}
else {
new AlertDialog.Builder(this)
.setTitle("Please activate location")
.setMessage("Click ok to goto settings else exit.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
})
.show();
}