Abbes Yassine
Abbes Yassine

Reputation: 1689

Permission READ_EXTERNAL_STORAGE is always denied

I'm trying to request a runtime permission with Android 6.0. This is my code:

private void enablePermission() {
    String[] PERMISSIONS = { Manifest.permission.READ_EXTERNAL_STORAGE};

    if (!hasPermissions(this, PERMISSIONS)) {
        ActivityCompat.requestPermissions(this, PERMISSIONS,
                PERMISSION_ALL);
    }
}


public static boolean hasPermissions(Context context, String... permissions) {

    for (String permission : permissions) {
        if (ContextCompat.checkSelfPermission(context, permission) !=
                PackageManager.PERMISSION_GRANTED) {
            return false;
        }
    }

    return true;
}


@Override
public void onRequestPermissionsResult(int requestCode, String[]
        permissions, int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_ALL:
            if (grantResults.length > 0 && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED) {
                Log.d("Permission", "Granted");
            } else {
                Log.d("Permission", "Denied");
            }
    }
}

It always tells my "Permission Denied" in onRequestPermissionsResult. I tried this code with ACCESS_FINE_LOCATION and it worked.

Upvotes: 4

Views: 2101

Answers (2)

Abbes Yassine
Abbes Yassine

Reputation: 1689

I solved my problem by restart my virtual device in Genymotion .

Upvotes: 0

MetaSnarf
MetaSnarf

Reputation: 6177

Try adding the android package on your permissions. Something like this (this is for writing external storage):

public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission. READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission. READ_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }


}

For callback:

 @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
            Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
            //resume tasks needing this permission
        }
    }

You can refer to this SO answer for more info.

Upvotes: 3

Related Questions