我使用第三方文件管理器从文件系统中选择一个文件(在我的案例中是 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);
}
}
}
}
代码片段是从 开放意图文件管理器指令中借用的,可以在这里找到:
Http://www.openintents.org/en/node/829
if-else
的目的是向后兼容。我想知道这是否是获取文件名的最佳方法,因为我发现其他文件管理器会返回所有类型的内容。
例如,文件待办返回以下内容: < br/>
content://com.dataviz.dxtg.documentprovider/document/file%3A%2F%2F%2Fsdcard%2Fdropbox%2FTransfer%2Fconsent.pdf
其中 getContentResolver().query()
返回 null
。
为了让事情变得更有趣,未命名的文件管理器(我从客户机日志中获得了这个 URI)返回了类似下面的内容:
/./sdcard/downloads/.bin
是否有从 URI 中提取文件名的首选方法,或者应该使用字符串解析?