BitDEVil2K16
BitDEVil2K16

Reputation: 324

How To Request Android Permission API >= 23?

Hi and good evening Stackoverflowers,

I have a Question is this enaught on my MainActivity to Request Permissions for External Card read GPS etc.?

in my onCreate have

checkPermissions();

so then have

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

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

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

}

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
            }
            return;
        }
        case 2: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
            }
            return;
        }
        case 3: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
            }
            return;
        }
    }
}

Can that still optimizing? and the permissions are queried? or am I completely wrong?

Thank you for your answers

Upvotes: 0

Views: 2481

Answers (1)

Juan Cruz Soler
Juan Cruz Soler

Reputation: 8254

First you need to declare the permissions in your AndroidManifest.xml:

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

Do not request all the permissions in onCreate, request them just before you are going to use it. Do one method like this for each permission, and before requesting it check if you already have it.

private void checkReadPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
         != PackageManager.PERMISSION_GRANTED) {

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

Upvotes: 1

Related Questions