Android – 如何从文档中获取选定的文件名

我正在推出使用以下代码选择文档的意图.
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);
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...