华为手机选择文件路径uri问题

转载至:https://blog.csdn.net/androidzmm/article/details/82886392

在上传文件功能的时候在文件管理器中选择文件有些打不开,例如在下载文件夹中的,一直找不到原因,最后查到这篇文章成功使用里面的方法解决了

重点就是 添加docId.startsWith("raw:")这个的判断处理

else if ("com.android.providers.downloads.documents".equals(authority)) {
            // 下載目錄
            final String docId = DocumentsContract.getDocumentId(uri);
            if (docId.startsWith("raw:")) {
                final String path = docId.replaceFirst("raw:", "");
                return path;
            }
            final Uri downloadUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
            String path = queryAbsolutePath(context, downloadUri);
            return path;
}

以下为原文章内容

在华为手机上选择图片的时候。拿到一个这样的路径:(华为手机进打开图库-》下载内容-》browser-》图片收藏-》选择图片)

content://com.android.providers.downloads.documents/document/raw:/storage/emulated/0/Download/browser/图片收藏/200832810200350_2.jpg
emmm.这个uri怎么转换都不成功。之前的转换方法:

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final Uri contentUri = ContentUris.withAppendedId(
                Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{split[1]};

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return uri.getPath();
}

public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {column};

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
            null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, "GetDataColumnFail", e);
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

之前一直这么用,直到遇到了这次,之前选择以后的路径都是类似这种:

content://com.android.providers.media.documents/document/image%3A836956
这次的路径是:

content://com.android.providers.downloads.documents/document/raw:/storage/emulated/0/Download/browser/图片收藏/200832810200350_2.jpg
这个会进到isDownloadsDocument这个判断中,代码里是拿到long类型的id.可是我们这个拿到的id是:

raw:/storage/emulated/0/Download/browser/图片收藏/200832810200350_2.jpg"
这样就会报转换错误。

java.lang.NumberFormatException: For input string: "raw:/storage/emulated/0/Download/browser/图片收藏/200832810200350_2.jpg"

找了很多资料,最后找到解决办法。

if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            if (id.startsWith("raw:")) {
                return id.replaceFirst("raw:", "");
            }
            final Uri contentUri = ContentUris.withAppendedId(
                Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }

我们也可以看到raw后面返回的其实就是真实路径,所以我们直接取出来就好了。

完整的代码:

@SuppressLint("NewApi")
public static String getPathFromUri(final Context context, final Uri uri) {
    if (uri == null) {
        return null;
    }
    // 判斷是否為Android 4.4之後的版本
    final boolean after44 = Build.VERSION.SDK_INT >= 19;
    if (after44 && DocumentsContract.isDocumentUri(context, uri)) {
        // 如果是Android 4.4之後的版本,而且屬於文件URI
        final String authority = uri.getAuthority();
        // 判斷Authority是否為本地端檔案所使用的
        if ("com.android.externalstorage.documents".equals(authority)) {
            // 外部儲存空間
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] divide = docId.split(":");
            final String type = divide[0];
            if ("primary".equals(type)) {
                String path = Environment.getExternalStorageDirectory().getAbsolutePath().concat("/").concat(divide[1]);
                return path;
            } else {
                String path = "/storage/".concat(type).concat("/").concat(divide[1]);
                return path;
            }
        } else if ("com.android.providers.downloads.documents".equals(authority)) {
            // 下載目錄
            final String docId = DocumentsContract.getDocumentId(uri);
            if (docId.startsWith("raw:")) {
                final String path = docId.replaceFirst("raw:", "");
                return path;
            }
            final Uri downloadUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
            String path = queryAbsolutePath(context, downloadUri);
            return path;
        } else if ("com.android.providers.media.documents".equals(authority)) {
            // 圖片、影音檔案
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] divide = docId.split(":");
            final String type = divide[0];
            Uri mediaUri = null;
            if ("image".equals(type)) {
                mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                mediaUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                mediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            } else {
                return null;
            }
            mediaUri = ContentUris.withAppendedId(mediaUri, Long.parseLong(divide[1]));
            String path = queryAbsolutePath(context, mediaUri);
            return path;
        }
    } else {
        // 如果是一般的URI
        final String scheme = uri.getScheme();
        String path = null;
        if ("content".equals(scheme)) {
            // 內容URI
            path = queryAbsolutePath(context, uri);
        } else if ("file".equals(scheme)) {
            // 檔案URI
            path = uri.getPath();
        }
        return path;
    }
    return null;
}

public static String queryAbsolutePath(final Context context, final Uri uri) {
    final String[] projection = {MediaStore.MediaColumns.DATA};
    Cursor cursor = null;
    try {
        cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            return cursor.getString(index);
        }
    } catch (final Exception ex) {
        ex.printStackTrace();
        if (cursor != null) {
            cursor.close();
        }
    }
    return null;
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,612评论 5 471
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,345评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,625评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,022评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,974评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,227评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,688评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,358评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,490评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,402评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,446评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,126评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,721评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,802评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,013评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,504评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,080评论 2 341

推荐阅读更多精彩内容