从Android 11开始,应用程序需要通过'MANAGE_EXTERNAL_STORAGE”权限来访问外部存储中的文件。对于内部存储,应用程序需要请求'READ_EXTERNAL_STORAGE”权限。
以下是在Android 11上选择PDF文件上传时解决权限问题的示例代码:
1.在Manifest文件中添加以下权限请求:
2.添加以下代码以请求权限并打开文件选择器: private static final int PERMISSION_REQUEST_STORAGE = 1000; private void showFileChooser() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_STORAGE); return; } Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("application/pdf"); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(intent, REQUEST_CODE); }
3.在onRequestPermissionsResult方法中处理权限请求结果: @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSION_REQUEST_STORAGE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { showFileChooser(); } else { Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show(); } } }
在Android 11上进行文件访问时,请注意遵循最佳实践并避免直接访问外部存储中的文件。您还可以使用MediaStore API来访问外部存储中的文件。