Comment vérifier si les Services de Localisation sont activés?

je développe une application sur Android OS. Je ne sais pas comment vérifier si les services de localisation sont activés ou non.

j'ai besoin d'une méthode qui retourne" true "si elle est activée et" false " si non (donc dans le dernier cas je peux afficher un dialogue pour les activer).

177
demandé sur Tshepang 2012-04-25 12:14:49

16 réponses

vous pouvez utiliser le code ci-dessous pour vérifier si le fournisseur gps et les fournisseurs réseau sont activés ou non.

LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}

try {
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}

if(!gps_enabled && !network_enabled) {
    // notify user
    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
    dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub
                Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivity(myIntent);
                //get gps
            }
        });
    dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub

            }
        });
    dialog.show();      
}

et dans le fichier manifest, vous devrez ajouter les permissions suivantes

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
299
répondu Shankar Agarwal 2018-07-05 06:54:43

j'utilise ce code pour vérifier:

public static boolean isLocationEnabled(Context context) {
    int locationMode = 0;
    String locationProviders;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);

        } catch (SettingNotFoundException e) {
            e.printStackTrace();
            return false;
        }

        return locationMode != Settings.Secure.LOCATION_MODE_OFF;

    }else{
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return !TextUtils.isEmpty(locationProviders);
    }


} 
206
répondu Slava Fir 2016-11-23 13:37:15

vous pouvez utiliser ce code pour orienter les utilisateurs vers les paramètres, où ils peuvent activer GPS:

    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.gps_not_found_title);  // GPS not found
        builder.setMessage(R.string.gps_not_found_message); // Want to enable?
        builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                owner.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        });
        builder.setNegativeButton(R.string.no, null);
        builder.create().show();
        return;
    }
28
répondu lenik 2012-04-25 08:17:34

après la réponse ci-dessus, dans L'API 23, vous devez ajouter les vérifications de permissions" dangereuses "ainsi que la vérification du système lui-même:

public static boolean isLocationServicesAvailable(Context context) {
    int locationMode = 0;
    String locationProviders;
    boolean isAvailable = false;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }

        isAvailable = (locationMode != Settings.Secure.LOCATION_MODE_OFF);
    } else {
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        isAvailable = !TextUtils.isEmpty(locationProviders);
    }

    boolean coarsePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED);
    boolean finePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);

    return isAvailable && (coarsePermissionCheck || finePermissionCheck);
}
13
répondu ZaBlanc 2016-04-15 16:15:44

Oui, vous pouvez vérifier ci-dessous le code:

public boolean isGPSEnabled(Context mContext) 
{
    LocationManager lm = (LocationManager)
    mContext.getSystemService(Context.LOCATION_SERVICE);
    return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

avec la permission dans le fichier manifeste:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
7
répondu Arun kumar 2016-02-12 12:43:38

Si aucun fournisseur n'est activé, le "passif" est le meilleur fournisseur retourné. Voir https://stackoverflow.com/a/4519414/621690

    public boolean isLocationServiceEnabled() {
        LocationManager lm = (LocationManager)
                this.getSystemService(Context.LOCATION_SERVICE);
        String provider = lm.getBestProvider(new Criteria(), true);
        return (StringUtils.isNotBlank(provider) &&
                !LocationManager.PASSIVE_PROVIDER.equals(provider));
    }
6
répondu Risadinha 2017-05-23 10:31:09

Cette clause if vérifie si les services de localisation sont disponibles dans mon opinion:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        //All location services are disabled

}
6
répondu tsemann 2014-09-12 16:19:44

comme L'a indiqué Peter McClennan, Google dispose d'une API qui fonctionne extrêmement bien avec le nouveau fournisseur de localisation fusionnée. Un exemple complètement travaillé est à Google Sample Code at Github vous n'avez pas besoin de coder un dialogue utilisateur pour leur demander de modifier les paramètres comme il est fait automatiquement avec l'API.

4
répondu Hugh Whelan 2015-12-20 16:03:43

j'utilise cette façon pour NETWORK_PROVIDER mais vous pouvez ajouter et pour GPS .

LocationManager locationManager;

Dans onCreate j'ai mis

   isLocationEnabled();
   if(!isLocationEnabled()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(R.string.network_not_enabled)
                .setMessage(R.string.open_location_settings)
                .setPositiveButton(R.string.yes,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        })
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    } 

et méthode de contrôle

protected boolean isLocationEnabled(){
    String le = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) getSystemService(le);
    if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        return false;
    } else {
        return true;
    }
}
3
répondu P. Dm 2015-12-10 11:28:12

c'est une méthode très utile qui retourne " true " si les Location services sont activés:

public static boolean locationServicesEnabled(Context context) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps_enabled = false;
        boolean net_enabled = false;

        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG,"Exception gps_enabled");
        }

        try {
            net_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG,"Exception network_enabled");
        }
        return gps_enabled || net_enabled;
}
3
répondu Jorgesys 2016-02-09 23:53:15

pour obtenir Geo actuel emplacement dans android Google maps,vous doit activer l'emplacement de votre appareil option.Pour vérifier si l'emplacement est activé ou non,vous pouvez simplement appeler cette méthode à partir de votre méthode onCreate() .

private void checkGPSStatus() {
    LocationManager locationManager = null;
    boolean gps_enabled = false;
    boolean network_enabled = false;
    if ( locationManager == null ) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }
    try {
        gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex){}
    try {
        network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex){}
    if ( !gps_enabled && !network_enabled ){
        AlertDialog.Builder dialog = new AlertDialog.Builder(MyActivity.this);
        dialog.setMessage("GPS not enabled");
        dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //this will navigate user to the device location settings screen
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
        AlertDialog alert = dialog.create();
        alert.show();
    }
}
2
répondu Ashana.Jackol 2014-11-19 04:23:34

vous pouvez demander les mises à jour de localisation et afficher le dialogue ensemble, comme GoogleMaps doas aussi. Voici le code:

googleApiClient = new GoogleApiClient.Builder(getActivity())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).build();
googleApiClient.connect();

LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);

builder.setAlwaysShow(true); //this is the key ingredient

PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
    @Override
    public void onResult(LocationSettingsResult result) {
        final Status status = result.getStatus();
        final LocationSettingsStates state = result.getLocationSettingsStates();
        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                // All location settings are satisfied. The client can initialize location
                // requests here.
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                // Location settings are not satisfied. But could be fixed by showing the user
                // a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    status.startResolutionForResult(getActivity(), 1000);
                } catch (IntentSender.SendIntentException ignored) {}
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                // Location settings are not satisfied. However, we have no way to fix the
                // settings so we won't show the dialog.
                break;
            }
        }
    });
}

si vous avez besoin de plus d'information, consultez la classe LocationRequest .

2
répondu bendaf 2016-04-05 07:39:09

pour kotlin

 private fun isLocationEnabled(mContext: Context): Boolean {
    val lm = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) || lm.isProviderEnabled(
            LocationManager.NETWORK_PROVIDER)
 }

dialogue

private fun showLocationIsDisabledAlert() {
    alert("We can't show your position because you generally disabled the location service for your device.") {
        yesButton {
        }
        neutralPressed("Settings") {
            startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
        }
    }.show()
}

appelez comme ça

 if (!isLocationEnabled(this.context)) {
        showLocationIsDisabledAlert()
 }

Conseil: le dialogue a besoin des importations suivantes (android studio devrait s'occuper de cela pour vous)

import org.jetbrains.anko.alert
import org.jetbrains.anko.noButton

et dans le Manifeste vous avez besoin des permissions suivantes

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
2
répondu kuzdu 2018-06-29 12:14:14

pour vérifier le fournisseur de réseau, vous avez juste besoin de changer la chaîne passée à isProviderEnabled à LocationManager.NETWORK_PROVIDER si vous cochez les valeurs de retour pour GPS provider et NETwork provider - les deux faux signifie Aucun service de localisation

0
répondu gheese 2012-11-22 16:48:09
private boolean isGpsEnabled()
{
    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
0
répondu Rahul 2014-08-13 11:11:35

j'utilise le premier code commencer créer méthode 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;
        }
    }

and I check Condition if ture Open the map and false give intention_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();
    }

enter image description here

0
répondu Pong Petrung 2018-02-26 12:08:14