我尝试了很多代码来获取 android 11 或 12 中的 pdf 路径,但只适用于 android 10 或更低版本的设备。 你能帮我么?我分享我的行代码
这样调用Intent
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"));
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();
}
}
});
像这样调用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;
}
最佳答案
如果你想访问一个文件或想要一个从 MediaStore 返回的 Uri 的文件路径,我有一个 library处理您可能遇到的所有异常。这包括磁盘、内部和可移动磁盘上的所有文件。例如,当从 Dropbox 选择一个文件时,该文件将被复制到您具有完全访问权限的应用程序目录,然后将返回复制的文件路径。
关于java - 如何在 Android 11 和 12 中获取 PDF 文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70374649/