274

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).

tshepang
  • 12,111
  • 21
  • 91
  • 136
Meroelyth
  • 5,310
  • 9
  • 42
  • 52
  • 3
    I know this is an old topic, but for those who may follow... Google has released an API for this; see https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi – Peter McLennan Aug 15 '15 at 03:02
  • [I have answer similar question here with codes.](http://stackoverflow.com/questions/32423157/android-check-if-location-services-enabled-using-fused-location-provider/35753050?noredirect=1#comment59185157_35753050) Check it out. Very helpful. – S bruce Mar 02 '16 at 19:16
  • FYI: SettingsApi is deprecated now. Use https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient instead. – Rajiv May 19 '20 at 06:49

24 Answers24

414

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"/>
GAMA
  • 5,958
  • 14
  • 79
  • 126
Shankar Agarwal
  • 34,573
  • 7
  • 66
  • 64
  • Thank you for the code. Checking for location manager: `lm.getAllProviders().contains(LocationManager.GPS_PROVIDER)` (or `NETWORK_PROVIDER`) would make sure that you do not throw the user to a settings page where there is no network option. – petter Nov 16 '13 at 16:32
  • 27
    Also: `Settings.ACTION_SECURITY_SETTINGS` should be `Settings.ACTION_LOCATION_SOURCE_SETTINGS` – petter Nov 16 '13 at 17:12
  • 2
    you could check to see if the phone is in airplane mode and handle it.... http://stackoverflow.com/questions/4319212/how-can-one-detect-airplane-mode-on-android – John Apr 15 '15 at 19:29
  • @JeetenParmar I used the second answer in the John's link. – Accollativo Apr 20 '15 at 13:15
  • 2
    I had some issues with lm.isProviderEnabled(LocationManager.GPS_PROVIDER) which used to return always false. This seems to occur when you use the new version of Play Services: that one which shows a dialog where you may turn on your gps right from the dialog, without showing the settings activity. When user turns gps from that dialog, that statement returns always false, even when gps is on – Marcelo Noguti Sep 18 '15 at 14:21
  • 11
    also should not put empty, confusing, useless try-catch blocks – Chisko Aug 18 '16 at 05:30
  • Is this code supposed to compile out of the box? There are bunch of compile time errors once I place this code inside onCreate method: https://ibb.co/k61pXJZ – TheBestPlayer Mar 21 '23 at 12:58
231

I use this code for checking:

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);
    }


} 
Oleksandr
  • 6,226
  • 1
  • 46
  • 54
Slava Fir
  • 2,411
  • 1
  • 15
  • 7
  • 7
    For clarity, might want to return false in catch block. Else initialize locationMode to Settings.Secure.LOCATION_MODE_OFF. – RyanLeonard Oct 27 '14 at 23:44
  • For me, `locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);` has a value of 0, possible indicating `LOCATION_MODE_OFF`? – Joe Maher Mar 10 '15 at 05:15
  • 2
    This is a good answer because it works with both the old and new Android location APIs. – Diederik Jun 10 '15 at 10:25
  • Nice, but not that useful as this requires API 19 or greater (Android 4.4, aka KitKat). – SMBiggs Jul 13 '15 at 23:00
  • 2
    LOCATION_PROVIDERS_ALLOWED - [link](http://developer.android.com/reference/android/provider/Settings.Secure.html#LOCATION_PROVIDERS_ALLOWED) This constant was deprecated in API level 19. We must use LOCATION_MODE and MODE_CHANGED_ACTION (or PROVIDERS_CHANGED_ACTION) – Choletski Aug 03 '15 at 12:49
  • 3
    This answer should have been accepted as the correct answer. locationManager.isProviderEnabled() method is not reliable on my 4.4 device (and as I saw other developers had the same problem on other OS versions too). In my case it returns true for GPS in each case (it doesn't matter if location services are enabled or not). Thanks for this great solution! – strongmayer Aug 11 '15 at 22:49
  • add a test if context != null – Laurent Russier Nov 30 '15 at 14:47
  • 2
    This didn't work on my test device, Samsung SHV-E160K, android 4.1.2, API 16. Although i make the GPS offline, this function still return true. I tested on Android Nougat, API 7.1 it works – HendraWD Nov 23 '16 at 09:11
  • Definitively this should be the correct answer. The answer marked as correct only detects high accuracy location services. – svprdga Jan 02 '20 at 16:07
  • How this method should be called? I do not get what I should pass to this method as an argument? What is context? – TheBestPlayer Mar 21 '23 at 12:47
83

As now in 2020

Latest, Best and shortest way is

@SuppressWarnings("deprecation")
public static Boolean isLocationEnabled(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        // This is a new method provided in API 28
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return lm.isLocationEnabled();
    } else {
        // This was deprecated in API 28
        int mode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
                Settings.Secure.LOCATION_MODE_OFF);
        return (mode != Settings.Secure.LOCATION_MODE_OFF);
    }
}
CoolMind
  • 26,736
  • 15
  • 188
  • 224
Mayank Sharma
  • 2,735
  • 21
  • 26
  • 2
    Excellent ! But even better, get rid of casting and directly pass `LocationManager.class` in `getSystemService` method because call requires API 23 ;-) – Mackovich Jun 06 '19 at 08:52
  • 16
    Or you could use [LocationManagerCompat](https://developer.android.com/reference/androidx/core/location/LocationManagerCompat) instead. :) – Mokkun Oct 08 '19 at 06:49
  • 2
    Use return lm != null && lm.isLocationEnabled(); instead of return lm.isLocationEnabled(); – Dr. DS Apr 10 '20 at 19:45
  • Thanks! `Settings.Secure.*` require API 19. – CoolMind Jan 20 '21 at 12:10
  • this code works for my use case, but i am not able to listen to changes. When Mode is Device only and User disables the Location Services. Receiver is not triggered for MODE_CHANGED_ACTION. But for all other mode changes it is triggered. – soan saini May 12 '21 at 05:06
74

Migrate to AndroidX and use

implementation 'androidx.appcompat:appcompat:1.3.0'

and use LocationManagerCompat

In Java

private boolean isLocationEnabled(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return LocationManagerCompat.isLocationEnabled(locationManager);
}

In Kotlin

private fun isLocationEnabled(context: Context): Boolean {
    val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return LocationManagerCompat.isLocationEnabled(locationManager)
}
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Sunny
  • 839
  • 7
  • 14
  • 1
    This works for all Android Versions since Android 1.0. But note `Before API version LOLLIPOP [API Level 21], this method would throw SecurityException if the location permissions were not sufficient to use the specified provider.` So if you don't have permission for the network or the gps provider, it might throw an exception, depending on which is enabled. Check the source code for more info. – xuiqzy Mar 04 '20 at 09:37
  • @xuiqzy, thanks! Does it mean we should first request location permission? – CoolMind Jan 20 '21 at 12:15
  • Thanks for noting this @xuiqzy, this is now fixed in more recent versions of the compat lib. – sooniln Mar 29 '21 at 16:07
  • Thanks to @xuiqzy! I had an exception on `appcompat:1.2.0` version but from `1.3.0` the error disappeared – remain4life May 27 '21 at 06:58
39

You may use this code to direct users to Settings, where they can enable GPS:

    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
        new AlertDialog.Builder(context)
            .setTitle(R.string.gps_not_found_title)  // GPS not found
            .setMessage(R.string.gps_not_found_message) // Want to enable?
            .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));
                }
            })
            .setNegativeButton(R.string.no, null)
            .show();
    }
lenik
  • 23,228
  • 4
  • 34
  • 43
  • 2
    Many thanks, but I don't need the code to check GPS but just location services. – Meroelyth Apr 25 '12 at 08:19
  • 1
    location services are always available, but the different providers might be unavailable. – lenik Apr 25 '12 at 08:22
  • 5
    @lenik, some devices provide a setting (under "Settings > Personal > Location services > Access to my location") which seems to enable/disable location detection altogether, even if specific providers are enabled. I saw this first-hand with a phone I was testing with, and even though both Wifi and GPS were enabled they appeared dead... to my app. Unfortunately, I since enabled the setting and can no longer reproduce the original scenario, even when disabling that "Access to my location" setting. So I can't say if that setting affects the `isProviderEnabled()` and `getProviders(true)` methods. – The Awnry Bear Mar 13 '14 at 09:06
  • 1
    ...I just wanted to throw that out there in case someone else runs into the same issue. I'd never seen the setting before on other devices I've tested with. It seems to be a system-wide location-detection kill switch of sorts. If anyone has any experience regarding how the `isProviderEnabled()` and `getProviders(true)` methods respond when such a setting is enabled (or disabled, depending on how you look at it), I'd be greatly curious to know what you've encountered. – The Awnry Bear Mar 13 '14 at 09:10
15

Working off the answer above, in API 23 you need to add "dangerous" permissions checks as well as checking the system's itself:

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);
}
ZaBlanc
  • 4,679
  • 1
  • 35
  • 38
9

Yes you can check below is the code:

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

with the permission in the manifest file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
GoRoS
  • 5,183
  • 2
  • 43
  • 66
Arun kumar
  • 1,894
  • 3
  • 22
  • 28
7

If no provider is enabled, "passive" is the best provider returned. See 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));
    }
Community
  • 1
  • 1
Risadinha
  • 16,058
  • 2
  • 88
  • 91
7

On Android 8.1 or lower the user can enable "Battery saving" mode from
Settings > Location > Mode > Battery Saving.
This mode only uses WiFi, Bluetooth or mobile data instead of GPS to determine the user location.

That's why you have to check if the network provider is enabled and locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) is not enough.

If you are using androidx this code will check which SDK version you are running and call the corresponding provider:

public boolean isLocationEnabled(Context context) {
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return manager != null && LocationManagerCompat.isLocationEnabled(manager);
}
Juan Cruz Soler
  • 8,172
  • 5
  • 41
  • 44
6

This if clause easily checks if location services are available in my opinion:

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

}
E_X
  • 3,722
  • 1
  • 14
  • 15
tsemann
  • 121
  • 1
  • 9
4

To get current Geo location in android google maps,you should turn on your device location option.To check whether the location is on or not,you can simple call this method from your onCreate() method.

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();
    }
}
Ashana.Jackol
  • 3,064
  • 28
  • 22
4

I use such way for NETWORK_PROVIDER but you can add and for GPS.

LocationManager locationManager;

In onCreate I put

   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();
    } 

And method of checking

protected boolean isLocationEnabled(){
    String le = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) getSystemService(le);
    if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        return false;
    } else {
        return true;
    }
}
P. Dm
  • 125
  • 12
  • 4
    You dont need if-then-else, you can just return `locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); ` – LadyWoodi Feb 14 '17 at 13:18
4

This is a very useful method that returns "true" if the Location services are enabled:

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;
}
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
4

For 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)
 }

dialog

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()
}

call like this

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

Hint: the dialog needs the following imports (android studio should handle this for you)

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

And in the manifest you need the following permissions

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
kuzdu
  • 7,124
  • 1
  • 51
  • 69
3

i use first code begin create method 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 intent 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();
    }

enter image description here

Pong Petrung
  • 1,437
  • 17
  • 14
2
private boolean isGpsEnabled()
{
    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
Rahul
  • 479
  • 3
  • 18
2

You can request the location updates and show the dialog together, like GoogleMaps doas also. Here is the 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;
            }
        }
    });
}

If you need more info check the LocationRequest class.

bendaf
  • 2,981
  • 5
  • 27
  • 62
  • Hello, I have been struggling since last two days to get the current location of the user. I need the current lat long of the user, I know that can be done using google api client. But how to integrate marshmallow permission in it. Plus if the the location services of the user are turned of, how to enable it. Can you help? – Chetna Sep 05 '16 at 05:52
  • Hi! you have a lot of question, what I cannot answer in comments. Please ask a new question so I can answer it more officially! – bendaf Sep 05 '16 at 08:45
  • I have posted my question here: http://stackoverflow.com/questions/39327480/how-to-get-users-current-location-in-android – Chetna Sep 05 '16 at 09:23
2

Can do in simplest way

private boolean isLocationEnabled(Context context){
int mode =Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
                        Settings.Secure.LOCATION_MODE_OFF);
                final boolean enabled = (mode != android.provider.Settings.Secure.LOCATION_MODE_OFF);
return enabled;
}
Vinayak
  • 6,056
  • 1
  • 32
  • 30
2
public class LocationUtil {
private static final String TAG = LocationUtil.class.getSimpleName();

public static LocationManager getLocationManager(final Context context) {
    return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}

public static boolean isNetworkProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

public static boolean isGpsProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.GPS_PROVIDER);
}

// Returns true even if the location services are disabled. Do not use this method to detect location services are enabled.
private static boolean isPassiveProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
}

public static boolean isLocationModeOn(final Context context) throws Exception {
    int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
    return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}

public static boolean isLocationEnabled(final Context context) {
    try {
        return isNetworkProviderEnabled(context) || isGpsProviderEnabled(context)  || isLocationModeOn(context);
    } catch (Exception e) {
        Log.e(TAG, "[isLocationEnabled] error:", e);
    }
    return false;
}

public static void gotoLocationSettings(final Activity activity, final int requestCode) {
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    activity.startActivityForResult(intent, requestCode);
}

public static String getEnabledProvidersLogMessage(final Context context){
    try{
        return "[getEnabledProvidersLogMessage] isNetworkProviderEnabled:"+isNetworkProviderEnabled(context) +
                ", isGpsProviderEnabled:" + isGpsProviderEnabled(context) +
                ", isLocationModeOn:" + isLocationModeOn(context) +
                ", isPassiveProviderEnabled(ignored):" + isPassiveProviderEnabled(context);
    }catch (Exception e){
        Log.e(TAG, "[getEnabledProvidersLogMessage] error:", e);
        return "provider error";
    }
}

}

Use isLocationEnabled method to detect the location services are enabled.

https://github.com/Polidea/RxAndroidBle/issues/327# page will give more information why not to use passive provider, instead use location mode.

alperk01
  • 183
  • 1
  • 7
1

If you are using AndroidX, use below code to check Location Service is enabled or not:

fun isNetworkServiceEnabled(context: Context) = LocationManagerCompat.isLocationEnabled(context.getSystemService(LocationManager::class.java))
btimalsina
  • 11
  • 3
  • `getSystemService(LocationManager::class.java)` requires API 23. Better use `context.getSystemService(Context.LOCATION_SERVICE)` instead. – CoolMind Jan 20 '21 at 12:23
1

Method 1: API 28 and above

fun isLocationEnabled(): Boolean {
    val locationManager = context.getSystemService(LocationManager::class.java)
    return locationManager.isLocationEnabled
}

Method 2:

fun isLocationEnabled(): Boolean {
    val locationManager = context.getSystemService(LocationManager::class.java)
    return LocationManagerCompat.isLocationEnabled(locationManager)
}

which calls the first method for API 28 else it calls

return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    || locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
0

To check for network provider you just need to change the string passed to isProviderEnabled to LocationManager.NETWORK_PROVIDER if you check the return values for both GPS provider and NETwork provider - both false means no location services

gheese
  • 1,170
  • 1
  • 11
  • 17
0
    LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    boolean gps_enabled = false;
    boolean network_enabled = false;

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

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

    if(!gps_enabled && !network_enabled) {
        // notify user
        new AlertDialog.Builder(this)
                .setMessage("Please turn on Location to continue")
                .setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }

                }).
                setNegativeButton("Cancel",null)
                .show();
    }
0
You can also use extension function.
------------------------------------

fun Context.isLocationEnabled(): Boolean{
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return LocationManagerCompat.isLocationEnabled(locationManager)}