如何在Android中从下载文件夹获取PDF真实路径



我想从下载文件夹中下载的PDF的URI中获得PDF的真实路径。

我已经在关注这个链接了。但在这方面,我并没有得到真正的路径和例外。如下所示:

URI

content://com.android.providers.downloads.documents/document/msf%3A26

午餐意向:

Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select PDF"), PICK_PDF_REQUEST);

OnActivityResult:

if (requestCode == PICK_PDF_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
String path = null;
try {
path = getPDFPath(uri);
LogUtils.logE(TAG, "Document :  " + path);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}

private String getPDFPath(Uri uri) {
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
String documentId = DocumentsContract.getDocumentId(uri);
String[] split = documentId.split(":");
String type = split[0];
return Environment.getExternalStorageDirectory().toString() + "/" + split[1];
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
String decodedURI = Uri.decode(uri.toString());
if (decodedURI.contains("raw:")) {
return decodedURI.substring(decodedURI.indexOf("raw:") + 4);
}
String id = DocumentsContract.getDocumentId(Uri.parse(decodedURI));
Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id));
return getDataColumn(contentUri, null, null);
}
}
return null;
}
public String getDataColumn(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);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}

异常

2020-05-04 14:47:09.747 17908-17908/ W/System.err: java.lang.NumberFormatException: For input string: "msf:26"
2020-05-04 14:47:09.748 17908-17908/W/System.err:     at java.lang.Long.parseLong(Long.java:594)
2020-05-04 14:47:09.748 17908-17908/ W/System.err:     at java.lang.Long.valueOf(Long.java:808)

我想要PDF的真实路径,这样我就可以使用它来进一步使用。

提前感谢

无需获取"真实"路径。

没有必要。

按原样使用uri即可。

这些天我们都喜欢这样。

加入我们。

最新更新