Correct way to request WRITE_EXTERNAL_STORAGE Permission

I have struggled to understand how storage works on Android. Now I am stuck asking for permission for WRITE_EXTERNAL_STORAGE and I am using Android 7.1.1. Here is my code:

int check = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (check == PackageManager.PERMISSION_GRANTED) {
            //Do something
        } else {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1024);
        }

      

UPDATE: So the code does work, it didn't work before because I had a typo in AndroidManifest.xml, thanks for your help!

+6


source to share


2 answers


Add permission to your manifest file



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

      

-7


source


Try it,

private Context mContext=YourActivity.this;

private static final int REQUEST = 112;

if (Build.VERSION.SDK_INT >= 23) {
    String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
    if (!hasPermissions(mContext, PERMISSIONS)) {
        ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
    } else {
        //do here
    }
} else {
     //do here
}

      

Obtaining Permits Result

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case REQUEST: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //do here
            } else {
                Toast.makeText(mContext, "The app was not allowed to write in your storage", Toast.LENGTH_LONG).show();
            }
        }
    }
}

      

check permissions for marshmallow



private static boolean hasPermissions(Context context, String... permissions) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

      

Manifesto

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

      

If you don't want to check multiple permissions at a time, add the permission to the PERMISSIONS array, for example:

String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE,android.Manifest.permission.READ_EXTERNAL_STORAGE};

      

+11


source







All Articles