我正在使用3rd party文件管理器从文件系统中选择文件(以我的情况为PDF)。
这是我启动活动的方式:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(getString(R.string.app_pdf_mime_type));
intent.addCategory(Intent.CATEGORY_OPENABLE);
String chooserName = getString(R.string.Browse);
Intent chooser = Intent.createChooser(intent, chooserName);
startActivityForResult(chooser, ActivityRequests.BROWSE);
这就是我所拥有的onActivityResult:
Uri uri = data.getData();
if (uri != null) {
if (uri.toString().startsWith("file:")) {
fileName = uri.getPath();
} else { // uri.startsWith("content:")
Cursor c = getContentResolver().query(uri, null, null, null, null);
if (c != null && c.moveToFirst()) {
int id = c.getColumnIndex(Images.Media.DATA);
if (id != -1) {
fileName = c.getString(id);
}
}
}
}
该代码段是从此处提供的Open Intents File Manager说明中借用的:http :
//www.openintents.org/en/node/829
的目的if-else是向后兼容。我想知道这是否是获取文件名的最佳方法,因为我发现其他文件管理器会返回所有信息。
例如,Documents ToGo返回如下内容:
content://com.dataviz.dxtg.documentprovider/document/file%3A%2F%2F%2Fsdcard%2Fdropbox%2FTransfer%2Fconsent.pdf
在上面getContentResolver().query()返回null。
为了使事情变得更有趣,未命名的文件管理器(我从客户端日志中获得了此URI)返回了以下内容:
/./sdcard/downloads/.bin
是否有一种从URI提取文件名的首选方法,或者应该采用字符串解析的方法?