androidservicelocation

How to check if Location Services are enabled?


I'm developing an app on Android OS. I don't know how to check if Location Services are enabled or not.

I need a method that returns "true" if they are enabled and "false" if not (so in the last case I can show a dialog to enable them).


Solution

  • You can use the below code to check whether gps provider and network providers are enabled or not.

    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
        new AlertDialog.Builder(context)
            .setMessage(R.string.gps_network_not_enabled)
            .setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton(R.string.Cancel,null)
            .show();    
    }
    

    And in the manifest file, you will need to add the following permissions

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>