关于intent调用文件管理并获取选择文件的路径的问题

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/fzkf9225/article/details/80491580

    网上很多关于调用文件管理并返回路径的demo,给你详细介绍了,很多很多做了很多适配,看似很厉害,但是那些博客都是抄过来的,并不能使用,你用起来会各种报错,各种文件路径找不到,例如这类(下面的链接)的文章都是你抄我我吵你的,千万不要看https://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//设置类型,我这里是任意类型,任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, StaticUtil.REQUEST_OPEN_FILE);

    网上会告诉你这里的type设置*/*,然后在onActivityResult中回调路径是各种适配,其实那些都是没用的,当你问题就出在这个intent.setType("*/*")的问题上,不设置类型的话,文件管理中的所有文件你可以选择,但是网上的那些demo却没有对所有文件的路径进行适配,只适配了媒体文件,那么非多媒体文件选择后返回路径就有问题。

    说句不好听的那些人抄袭博客也不动动脑子吗?

    其实只要做这样一个方法就可以了:

  public String getPath(Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;
            try {
                cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                 e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

getPath中的uri是在onActivityResult中回调的uri,即intent.getData();



猜你喜欢

转载自blog.csdn.net/fzkf9225/article/details/80491580