Search code examples
androidandroid-gps

Android. Prompt access device's location


In my old Android (Samsung S3 mini) It wasn't necessary to make anything to allow my app to use the location (GPS) of my phone. Now I am using an LG G4 with Android 6.0 and it is not using the GPS ever. I can see that in apps like waze, there is a prompt "Allow Waze to access this device's location?". I guess I have to do something similar to trigger this option before start my app. Anyone know how to do that. I have no idea how to ask Google. Thanks in advance.


Solution

  • On android 6.0 you have to request some permissions at Runtime. It's explain here https://developer.android.com/training/permissions/requesting.html

    Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.

    For request permissions at runtime you should do something like this(before you want to use GPS) :

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
        // Check Permissions Now
        private static final int REQUEST_LOCATION = 2;
    
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Display UI and wait for user interaction
        } else {
            ActivityCompat.requestPermissions(
                  this, new String[]{Manifest.permission.LOCATION_FINE},
        ACCESS_FINE_LOCATION);
        }
    } else {
        // permission has been granted, continue as usual
        Location myLocation =
            LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    }
    

    You have an example for GPS here https://developers.google.com/android/guides/permissions