解决方案:应该在向用户请求权限之后,使用回调函数来检查是否授予了权限,并只有在授予权限后才保存图像。代码示例如下:
private static final int REQUEST_CODE = 1;
private static final String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private void requestPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_CODE);
} else {
saveImage();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
saveImage();
} else {
// Permission denied by user
}
}
}
private void saveImage() {
// Save image code here
}
在代码示例中,首先检查是否授予权限,如果没有则请求权限,在授权回调函数中再次检查是否授予权限并保存图像。