JarsOfJam-Scheduler
JarsOfJam-Scheduler

Reputation: 3179

Permissions to write granted, but they are denied at execution time

I added the permissions to write access to the external storage device in the Manifest, and granted them in my Android phone. I even ask for them at execution time if they don't exist.

However, I always get this exception:

java.io.FileNotFoundException: /storage/emulated/03b3d97bd-5186-4506-97dc-9994b7ce0761 (Permission denied)

Do you have an idea of why?

Code

try {

    if (Build.VERSION.SDK_INT >= 23) {
        int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }


    OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + image_uuid);
    byte[] buffer = new byte[1024];
    int bytesRead;
    BitmapDrawable bitmapDrawable = (BitmapDrawable) temp.getDrawable();
    etc. etc. etc.

And in the manifest file:

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

Upvotes: 0

Views: 84

Answers (1)

Mehdi Varse
Mehdi Varse

Reputation: 299

You write file in sd card before you get permission.You must wait for the result of granting permission by using below code:

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE/*1 in here*/: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted
                // write file here
            } else {
                // permission denied
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request.
    }
}

see here

Upvotes: 3

Related Questions