虽然我来晚了,但希望这能帮到有需要的人。我在Android 10和11上遇到了同样的问题。下面逐步介绍如何获取PDF路径:
1)打开文件以选择PDF
fun openPdfSelector(){
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
type = "application/pdf"
addCategory(Intent.CATEGORY_OPENABLE)
}
startActivityForResult(intent, 101)
}
2)在activity的Override onActivityResult()方法中,使用以下代码:
data?.data?.also { documentUri ->
contentResolver.takePersistableUriPermission(
documentUri,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
val filePathHelper = FilePathHelper()
var uriString: String = ""
if (filePathHelper.getPathnew(documentUri, this) != null) {
uriString = filePathHelper.getPathnew(documentUri, this).toLowerCase()
} else {
uriString =
filePathHelper.getFilePathFromURI(documentUri, this).toLowerCase()
}
}
3) FilePathHelper是我们使用的类,用于解析URI以获取路径
public class FilePathHelper {
public FilePathHelper(){
}
public String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url.replace(" ", ""));
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
public String getFilePathFromURI(Uri contentUri, Context context) {
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
File copyFile = new File(context.getExternalCacheDir() + File.separator + fileName);
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getPath(Uri uri, Context context) {
String filePath = null;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
filePath = generateFromKitkat(uri, context);
}
if (filePath != null) {
return filePath;
}
Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DATA}, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath == null ? uri.getPath() : filePath;
}
@TargetApi(19)
private String generateFromKitkat(Uri uri, Context context) {
String filePath = null;
if (DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Video.Media.DATA};
String sel = MediaStore.Video.Media._ID + "=?";
Cursor cursor = context.getContentResolver().
query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath;
}
public String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public String getPathnew(Uri uri, Context context) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Something with exception - " + e.toString());
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}}
注意:如果您使用的是Android 11,请为您的应用程序提供作用域存储权限
-> 您可以使用以下代码来请求权限
btn_select_file.setOnClickListener {
if (isScopedStoragePermissionNeeded()) {
askForExternalStoragePermission()
} else {
openPdfSelector()
}}
private fun isScopedStoragePermissionNeeded(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()
}
private fun askForExternalStoragePermission() {
requestPermissions(
arrayOf(Manifest.permission.MANAGE_EXTERNAL_STORAGE),
102
)
}
-> 在onRequestPermissionResultI()方法中打开到权限界面的意图
if (requestCode == 102) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
intent.data = Uri.parse("package:com.example.pdfselector")
startActivityForResult(intent, 103)
}
}
-> 在清单文件中添加 android:requestLegacyExternalStorage="true"
一行。