在 Android 13 Tiramisù 中,可能会出现应用在请求权限时无法正确处理用户的拒绝操作的情况。这会导致应用持续请求权限,并可能导致崩溃或应用无响应。以下是一个示例代码,可用于避免此问题:
private static final int PERMISSION_REQUEST_CODE = 1000;
private void requestPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
// Toast.makeText(this, "We need permission to access your storage files", Toast.LENGTH_SHORT).show();
}
// request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted.
// do your work here.
} else {
// Permission denied.
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
在这个示例中,当应用需要读取外部存储时,会检查应用是否已被授权。如果没有授权,应用会向用户请求授权。如果用户拒绝授权,则应用会显示一个消息告诉用户为什么需要访问存储,但不会持续请求授权。如果用户授予授权,则应用可以执行需要访问存储的操作。如果用户拒绝授权,则应用会显示一个消息告诉用户授权已被拒绝。