当Callback
用户允许WRITE_EXTERNAL_STORAGE
来自RuntimePermission dialog
.
首先你需要在你的和覆盖 方法中实现OnRequestPermissionsResultCallback
Listener
类来检查用户是允许还是拒绝权限ActivityCompat
Activity
void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
你可以这样做:
int REQUEST_STORAGE = 1;
private void checkExternalStoragePermissions() {
if (hasStoragePermissionGranted()) {
//You can do what whatever you want to do as permission is granted
} else {
requestExternalStoragePermission();
}
}
public boolean hasStoragePermissionGranted(){
return ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
public void requestExternalStoragePermission() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
ActivityCompat.requestPermissions(MainActivity.this, {Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_STORAGE);
}
}
onRequestPermissionsResult()
当用户从运行时权限对话框允许或拒绝权限时,将调用以下方法。
您还可以处理用户已选中从不显示运行时权限对话框的情况。
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_STORAGE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//User allow from permission dialog
//You can do what whatever you want to do as permission is granted
} else if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivtity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//User has deny from permission dialog
Snackbar.make(mainLayout, getResources().getString("Please enable storage permission"),Snackbar.LENGTH_INDEFINITE)
.setAction("OK", new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(MainActivity.this, {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE);
}
})
.show();
} else {
// User has deny permission and checked never show permission dialog so you can redirect to Application settings page
Snackbar.make(mainLayout, getResources().getString("Please enable permission from settings"),Snackbar.LENGTH_INDEFINITE)
.setAction("OK", new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", MainActivity.this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
})
.show();
}
}
}
在这里,我曾经Snackbar
向用户显示有关权限的相关消息,并且mainLayout
是Activity's Main Layout
.
希望它可以帮助你。