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

前端之家收集整理的这篇文章主要介绍了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);
}
原文链接:https://www.f2er.com/android/309954.html

猜你在找的Android相关文章