I am developing an android app in which it is required to provide permission for Read and write external storage. My requirement is to select a picture from gallery and use
Checking every situation
if denied - showing Alert dialog to user why we need permission
public static final int STORAGE_PERMISSION_REQUEST_CODE= 1;
private void askPermissions() {
int permissionCheckStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
// we already asked for permisson & Permission granted, call camera intent
if (permissionCheckStorage == PackageManager.PERMISSION_GRANTED) {
//do what you want
} else {
// if storage request is denied
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You need to give permission to access storage in order to work this feature.");
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setPositiveButton("GIVE PERMISSION", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
// Show permission request popup
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
STORAGE_PERMISSION_REQUEST_CODE);
}
});
builder.show();
} //asking permission for first time
else {
// Show permission request popup for the first time
ActivityCompat.requestPermissions(AddWorkImageActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
STORAGE_PERMISSION_REQUEST_CODE);
}
}
}
Checking Permission Results
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case STORAGE_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// check whether storage permission granted or not.
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do what you want;
}
}
break;
default:
break;
}
}
you can just copy and paste this code, it works fine. change context(this) & permissions according to you.