0

I tried setting up the gps permission for an andriod app using the below code in manifest.xml

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

But when I execute I am not able to get the gps coordinates. I am getting "need permission" toast message. Need help. Here is my code snippet.

LocationManager locationManager = (LocationManager)
                getSystemService(Context.LOCATION_SERVICE);
        LocationListener locationListener = new MyLocationListener();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast toast = Toast.makeText(getApplicationContext(), "no permission", Toast.LENGTH_LONG);
            toast.show();
            return;
        }
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
Sudip Podder
  • 830
  • 11
  • 25
  • 1
    https://developer.android.com/training/permissions/requesting.html – CommonsWare Oct 12 '16 at 14:34
  • pls look at this answer i have added location permission http://stackoverflow.com/questions/35973235/android-permission-denial-starting-intent-with-revoked-permission-android-perm – Saveen Oct 12 '16 at 14:43

1 Answers1

0

Add this line inside of your if block

ActivityCompat.requestPermissions(context, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1); // 1 is a integer which will return the result in onRequestPermissionsResult

And attach this code in your Activity,

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    switch (requestCode) {
        case 1:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this,"GPS permission granted",Toast.LENGTH_LONG).show();

            //  get Location from your device by some method or code

            } else {
            // show user that permission was denied. inactive the location based feature or force user to close the app
            }
            break;
    }
}
Sudip Podder
  • 830
  • 11
  • 25