Это реализация разрешения запроса с обоснованием запроса.Надеюсь, это кому-нибудь поможет.
public class MainActivity extends AppCompatActivity {
private View mainLayout;
private static final int PERMISSION_REQUEST_READ_EXTERNAL_STORAGE = 0; //Arbitrary >= 0
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = findViewById(R.id.mainLayout); //SnackBar container view in your activity.
//Runtime permission request required if Android permission >= Marshmallow
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
checkPermission();
else
//read my file in /sdcard/test.csv
readTheFiles();
}
private void readTheFiles() {
//This is the method where you read your SD Card content.
}
private void checkPermission() {
// Check if the permission has been granted
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Permission is already available
readTheFiles();
} else {
// Permission is missing and must be requested.
requestReadExternalStoragePermission();
}
}
private void requestReadExternalStoragePermission() {
// Permission has not been granted and must be requested.
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show a snackBar to the user that explain why you need this permission.
Snackbar.make(mainLayout, "read_external_storage_permission_required",
Snackbar.LENGTH_INDEFINITE).setAction(R.string.ok, new View.OnClickListener() {
@Override
public void onClick(View view) {
// Request the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_REQUEST_READ_EXTERNAL_STORAGE);
}
}).show();
} else {
// Request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_READ_EXTERNAL_STORAGE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_READ_EXTERNAL_STORAGE) {
// Request for permission.
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission has been granted.
readTheFiles();
} else {
// Permission request was denied by user
// Show a snackBar, exit program, close activity, etc.
}
}
}
}