19

According to the Android documentation:

The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework that automatically handles location providers, user movement, and location accuracy than the platform location API in android.location.

But using the fused location provider (from location APIs in Google Play services) I do not know how to check if the user has the location enabled or disabled.

Using the old android.location it was easy:

locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

But I don´t want to use both Google Play Services fused location provider and old android location.

How could I check if the location is enabled by the user using the Fused Location Provider?

Thanks in advance.

Josu Garcia de Albizu
  • 1,128
  • 2
  • 12
  • 22

5 Answers5

38

This android developer training tutorial could help - here's the basics:

Code to run in your Activity onCreate():

 // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    mGoogleApiClient.connect();

    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult locationSettingsResult) {

            final Status status = locationSettingsResult.getStatus();
            final LocationSettingsStates LS_state = locationSettingsResult.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(LocationByGPS.this, REQUEST_CHECK_SETTINGS);

                    } catch (IntentSender.SendIntentException e) {
                        // Ignore the error.
                    }
                    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;
            }
        }
    });

Override this Method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
    switch (requestCode) {
        case REQUEST_CHECK_SETTINGS:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    // All required changes were successfully made
                    GetUserLocation();//FINALLY YOUR OWN METHOD TO GET YOUR USER LOCATION HERE
                    break;
                case Activity.RESULT_CANCELED:
                    // The user was asked to change settings, but chose not to

                    break;
                default:
                    break;
            }
            break;
    }
}

Remember to Implement these in your class:

public class MyClass extends AppCompatActivity implements
    ActivityCompat.OnRequestPermissionsResultCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener{

  protected static final int REQUEST_CHECK_SETTINGS = 0x1;


  /* 
     your code i.e. with the above code etc....
 */

 }

Good explanation here in this Google developer link.

Cheers!

Advait Saravade
  • 3,029
  • 29
  • 34
S bruce
  • 1,514
  • 3
  • 16
  • 24
  • I have edited my answer by adding code and another useful link. – S bruce Mar 02 '16 at 19:01
  • Looks good - I did a bit of cleanup and fixed your links, but otherwise that's a solid answer. Thanks for taking the advice, and good luck! – Mogsdad Mar 02 '16 at 19:06
  • where is LocationByGPS.this ? – Nabeel K Apr 10 '16 at 11:23
  • You even fixed several errors contained in the official Android Developer tutorial, awesome. – scai Dec 27 '16 at 10:42
  • @NabeelK This is the outer class, probably your SomethingActivity class. See the official tutorial. – scai Dec 27 '16 at 10:44
  • it is clear answer. but it look check location only in create method. is that possible to check this in every time in app. or where sould be added to check everytime location enable or not. if not show dialog – mehmet Mar 14 '17 at 19:23
  • The example code here is to help you see how the concept works. You can always customise as needed in your implementation. If you are always gonna need to implement after onCreate() then you can create and call it from a custom method or class. – S bruce Mar 15 '17 at 08:07
  • I need to check these setting on a background service.How to get result on service for this. – Akash Bisariya Aug 31 '17 at 05:27
17

See SettingsApi: check your location request then ensure that the device's system settings are properly configured for the app's location needs.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Aryan Najafi
  • 2,496
  • 27
  • 29
8

As now in 2020

Latest , Best and shortest way is

    public boolean isLocationEnabled()
    {
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// This is new method provided in API 28
                    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                    return lm.isLocationEnabled();
                } else {
// This is 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);

                }
    }
Mayank Sharma
  • 2,735
  • 21
  • 26
  • How to enable gps without redirecting the user to configurations? I mean, pop up an alertDialog or snackBar to enable GPS when user clicks on "OK" button. – Aliton Oliveira Dec 01 '19 at 16:04
  • 1
    `LocationManagerCompat.isLocationEnabled(context.getSystemService(Context.LOCATION_SERVICE) as LocationManager)` So you don't have to check the SDK Version. – TeKo Jul 10 '20 at 11:28
  • @TeKo My Android JAVA doesn't know "as" - I just use the normal cast... – The incredible Jan Jun 30 '23 at 12:54
2

You can also check like this:

LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean isEnabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
Elletlar
  • 3,136
  • 7
  • 32
  • 38
0

If use FusedLocationProviderClient, first we need check Location is enabled in device.

private fun isLocationEnabled(): Boolean {
    val activity: Activity? = this.activity
    val lm = activity?.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
    if (lm != null) {
        val enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lm.isLocationEnabled
        } else {
            lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
                    || lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
        }
        Log.d(TAG, "isLocationServiceEnabled", enabled)
        return enabled
    }
    return false
}

And then, check LocationSettings.

val request = LocationRequest.create()
        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)

val settingRequest = LocationSettingsRequest.Builder()
        .addLocationRequest(request)
        .build()
// check Location settings for the request
LocationServices.getSettingsClient(context)
        .checkLocationSettings(settingRequest)
        .addOnSuccessListener {
            // OK!!
            // fusedLocationProviderClient.requestLocationUpdates
        }
        .addOnFailureListener {  exception ->
            if (exception  is ResolvableApiException) {
                try {
                    exception.startResolutionForResult(activity, RC_LOCATION_SETTINGS)
                } catch (ex: IntentSender.SendIntentException) {
                    // ignore
                }
            } else {
                // handle other errors
                showFusedDisabledDialog()
            }
        }

also, please check below link.

https://developer.android.com/training/location/change-location-settings

Brownsoo Han
  • 4,549
  • 3
  • 20
  • 20