我正在推出使用以下代码选择文档的意图.
private void showFileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult( Intent.createChooser(intent,"Select a File to Upload"),1); } catch (android.content.ActivityNotFoundException ex) { // Potentially direct the user to the Market with a Dialog Toast.makeText(this,"Please install a File Manager.",Toast.LENGTH_SHORT).show(); } }
在onActivity结果中,当我尝试获取文件路径时,它会给出一些其他数字的文件名.
@Override protected void onActivityResult(int requestCode,int resultCode,Intent data) { switch (requestCode) { case 1: if (resultCode == RESULT_OK) { // Get the Uri of the selected file Uri uri = data.getData(); File myFile = new File(uri.toString()); String path = myFile.getAbsolutePath(); } break; } super.onActivityResult(requestCode,resultCode,data); }
那个路径值我就这样得到了.
“内容://com.android.providers.downloads.documents/document/1433”
但我想要真正的文件名,如doc1.pdf等..如何得到它?
解决方法
当您获得内容:// uri时,您需要查询内容解析器,然后获取显示名称.
@Override protected void onActivityResult(int requestCode,Intent data) { switch (requestCode) { case 1: if (resultCode == RESULT_OK) { // Get the Uri of the selected file Uri uri = data.getData(); String uriString = uri.toString(); File myFile = new File(uriString); String path = myFile.getAbsolutePath(); String displayName = null; if (uriString.startsWith("content://")) { Cursor cursor = null; try { cursor = getActivity().getContentResolver().query(uri,null,null); if (cursor != null && cursor.moveToFirst()) { displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); } } finally { cursor.close(); } } else if (uriString.startsWith("file://")) { displayName = myFile.getName(); } } break; } super.onActivityResult(requestCode,data); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。