Bonjour,
J'ai un soucis avec l'utilisation de la géolocalisation dans mon application. Voici mon problème: lorsque j'active ma position GPS sur mon téléphone et je lance l'application, tout marche très bien. Mais, si ma position n'est pas activée, l'application échoue.
Ma question est comment mettre une condition dans le code suivant pour demander à l'utilisateur d'activer sa position au cas où ce n'est pas activée afin d'éviter l'échec de l'application ?Voici mon code :
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
// I suppressed the missing-permission warning because this wouldn't be executed in my case without location services being enabled
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
Toast.makeText(MainActivity.this, "Veuillez vérifier voir si votre Position est activée pour la géolocalisation", Toast.LENGTH_LONG).show();
return;
}
else{
android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
double userLat = lastKnownLocation.getLatitude();
double userLong = lastKnownLocation.getLongitude();
try{
Geocoder geo = new Geocoder(this.getApplicationContext(),Locale.getDefault());
List<Address>adresses = geo.getFromLocation(userLat,userLong,1);
if(adresses.isEmpty()){
Toast.makeText(MainActivity.this, "La localisation n'est pas disponible"+userLong, Toast.LENGTH_LONG).show();
}
else{
if(adresses.size() > 0){
String lieu = "Votre adresse : "+adresses.get(0).getFeatureName()+", "+adresses.get(0).getSubAdminArea()+", "+adresses.get(0).getAdminArea()+", "+adresses.get(0).getCountryName();
feature_1.setText(lieu);
}
}
} catch (IOException e) {
e.printStackTrace();
}
String lat = String.valueOf(userLat);
String lon = String.valueOf(userLong);
}
Merci d'avance