如何在 Android 11 和 12 中获取 PDF 文件路径

Abh*_*IBS 3 java android android-layout android-studio

我尝试了很多代码来在 android 11 或 12 中获取 pdf 路径,但仅适用于 android 10 或更低的设备。你能帮我么?我分享我的行代码

像这样的意图调用

Intent intent = new Intent();
            intent.setType("application/pdf");
            statusAdapter = "pdf";
            pos = position;
            intent.setAction(Intent.ACTION_GET_CONTENT);
            someActivityResultLauncher.launch(Intent.createChooser(intent, "Select PDF"));

Run Code Online (Sandbox Code Playgroud)
someActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // There are no request codes
                        Intent data = result.getData();
                        if (data == null) {
                            //error
                            return;
                        }
                        try {
                            final Uri pdfUri= data.getData();
                            File pdfFile = new File(getPath(pdfUri));
                            long length = pdfFile.length();
                            length = length / 1024;
                            Toast.makeText(CreateSubEventActivity.this, "File Path : " + pdfFile.getPath() + ", File size : " + length + " KB", Toast.LENGTH_SHORT).show();
//                            uploadFile(imageFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(CreateSubEventActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
                        }
                    }
                });
Run Code Online (Sandbox Code Playgroud)

getPath 像这样调用

public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) return null;
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String s = cursor.getString(column_index);
        cursor.close();
        return s;
    }

Run Code Online (Sandbox Code Playgroud)

Abh*_*IBS 6

如果您想访问文件或想要从 MediaStore 返回的 Uri 获取文件路径,我有一个可以处理您可能遇到的所有异常。这包括磁盘、内部磁盘和可移动磁盘上的所有文件。例如,当从 Dropbox 选择文件时,该文件将被复制到您具有完全访问权限的应用程序目录,然后将返回复制的文件路径。