-2

I'm using the following code to check for and request permission for GPS:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

    ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION }, 1);
}

I have the following in the manifest:

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

I'm deploying the app to an Android 5.0.2 tablet using Android Studio.

I know the checkSelfPermission doesn't return PERMISSION_GRANTED and it executes the requestPermissions, but it doesn't show a dialog or grant the permission. How do I grant the app permission to use GPS?

rityzmon
  • 1,945
  • 16
  • 26
  • 1
    "I know the `checkSelfPermission` doesn't return `PERMISSION_GRANTED`" - Are you sure you have the permission in the right place in the manifest? I.e., outside of the `` tags? – Mike M. Dec 02 '16 at 06:14
  • Possible duplicate of [How do I get the current GPS location programmatically in Android?](http://stackoverflow.com/questions/1513485/how-do-i-get-the-current-gps-location-programmatically-in-android) – Maveňツ Dec 02 '16 at 06:20

3 Answers3

1
ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION }, 1);

This code requests runtime permissions on android 6.For lower versions i launch the settings intent for the user to turn on the preferred setting as below(in place of the above code)

Intent myIntent = new Intent(Settings.ACTION_SETTINGS);
                        startActivity(myIntent);
Mushirih
  • 451
  • 5
  • 13
1

Add these lines in manifest:

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

and these too:

<!-- Below permissions are used to detect required hardware or service providers for the application -->
    <uses-feature
        android:name="android.hardware.location"
        android:required="true" />
    <uses-feature
        android:name="android.hardware.location.gps"
        android:required="true" />
Hassan Jamil
  • 951
  • 1
  • 13
  • 33
Aris_choice
  • 392
  • 2
  • 18
0

You can use the below code. With the below code it will ask to turn the GPS on .

public class Activity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {


    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    // boolean flag to toggle periodic location updates
    private boolean mRequestingLocationUpdates = false;

    private LocationRequest mLocationRequest;

    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 600000; // 10 min
    private static int FATEST_INTERVAL = 600000; // 10 min
    private static int DISPLACEMENT = 5; // 5 meters

    PendingResult<LocationSettingsResult> result;

    AlertDialog.Builder alertDialogBuilder;
    LinearLayout parent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        alertDialogBuilder = new AlertDialog.Builder(Activity.this);

        parent = new LinearLayout(ActivitySetting.this);
        parent.setGravity(Gravity.CENTER);
        parent.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));


        alertDialogBuilder.setTitle("name");

        // First we need to check availability of play services
        if (checkPlayServices()) {

            // Building the GoogleApi client
            buildGoogleApiClient();

            createLocationRequest();
        }

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY));


        result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
                // final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:

                        alertDialogBuilder.setMessage("Turn On GPS");
                        alertDialogBuilder.setView(parent);
                        alertDialogBuilder.setCancelable(false);

                        alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                try {
                                    // Show the dialog by calling startResolutionForResult(),
                                    // and check the result in onActivityResult().
                                    status.startResolutionForResult(ActivitySetting.this, 1000);
                                } catch (IntentSender.SendIntentException e) {
                                    // check  error.
                                }

                            }
                        });

                        alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                try {
                                    // Show the dialog by calling startResolutionForResult(),
                                    finish();
                                } catch (Exception e) {
                                    // check error.
                                }

                            }
                        });
                        alertDialogBuilder.create();
                        alertDialogBuilder.show();
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                        // you can do here what ever you want.

                        break;
                }
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

        checkPlayServices();

        // Resuming the periodic location updates
        if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    /**
     * Creating google api client object
     */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
        switch (requestCode) {
            case 1000:
                switch (resultCode) {
                    case Activity.RESULT_OK:

                        // If user has active gps you will get it here

                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to turn on

                        break;
                    default:

                        break;
                }
                break;
        }
    }

    /**
     * Method to verify google play services on the device
     */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }


    /**
     * Google api callback methods
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i("fsAil", "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {


    }

}

Here API <= 21 gps permission will be granted automatically(if you have defined permission on manifest) and for marshmallow and above you need to ask for runtime permission(also add permission in manifest) but to turn on GPS after permission granted you can use the above code.

With this code one alertbox comes up and ask to turn on the GPS(if not active). So you can directly turn on GPS with the above code.

Hope this help you.

Cheers!!

rushank shah
  • 856
  • 1
  • 9
  • 28
  • if questions are duplicate flag them as **duplicate** – Maveňツ Dec 02 '16 at 06:20
  • `write code for the requestpermission`? and if you are giving answer give it complete for helping OP and readers of the future to keep getting the answer complete and precise – Maveňツ Dec 02 '16 at 06:27