谈谈android中的URI


Uri 在android中使用的地方很多,这篇讲解下android中使用Uri需要注意的地方,主要就是集中在Uri和路径的相互转换上,先贴上转换代码

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;

import java.io.File;

/**
 * @author: xiewenliang
 * @Filename:
 * @Description:
 * @Copyright: Copyright (c) 2017 Tuandai Inc. All rights reserved.
 * @date: 2017/4/13 17:02
 */

public class PathUtil {

    /**
     * 判断SD卡是否正常挂载,在对SD卡进行操作前一般都会作此判断
     *
     * @return true 为正常挂载
     */
    private static boolean getExternalStorageState() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * @return 返回下载缓存目录 /cache
     */
    private static String getDownloadCacheDirectory() {
        return Environment.getDownloadCacheDirectory().getAbsolutePath();
    }

    /**
     * @return 返回用户数据目录 /data
     */
    private static String getDataDirectory() {
        return Environment.getDataDirectory().getAbsolutePath();
    }

    /**
     * @return 返回外部存储路径 /mnt/sdcard
     */
    private static String getExternalStorageDirectory() {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    /**
     * 根据不同类型 返回不同目录,包涵图片目录、音乐目录、等等
     *
     * @param type {DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS,
     *             DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, DIRECTORY_MOVIES,
     *             DIRECTORY_DOWNLOADS, DIRECTORY_DCIM, DIRECTORY_DOCUMENTS}
     * @return 返回外部存储路径 /mnt/sdcard/...
     */
    private static String getExternalStoragePublicDirectory(String type) {
        return Environment.getExternalStoragePublicDirectory(type).getAbsolutePath();
    }

    /**
     * @return 返回系统目录 /system
     */
    private static String getRootDirectory() {
        return Environment.getRootDirectory().getAbsolutePath();
    }

    /**
     * 路径转换成Uri
     *
     * @param path 路径
     * @return 返回Uri
     */
    private Uri pathConvertUri(String path) {
        if ("/".startsWith(path)) {
            // 以“/”开头为文件路径
            return Uri.parse("file://" + path);
        } else {
            return Uri.parse(path);
        }
    }

    /**
     * 文件转换成Uri
     *
     * @param file 文件对象
     * @return 返回Uri
     */
    private Uri FileConvertUri(File file) {
        return Uri.fromFile(file);
    }

    /**
     * 根据Uri获取路径
     *
     * @param context 上下文
     * @param uri     Uri
     * @return 返回路径
     */
    public static String getPhotoPathFromContentUri(Context context, Uri uri) {
        String photoPath = "";
        if (context == null || uri == null) {
            return photoPath;
        }
        if (uri.getScheme().startsWith("http")) {
            return uri.toString();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if (isExternalStorageDocument(uri)) {
                String[] split = docId.split(":");
                if (split.length >= 2) {
                    String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        photoPath = Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                }
            } else if (isDownloadsDocument(uri)) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                photoPath = getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                String[] split = docId.split(":");
                if (split.length >= 2) {
                    String type = split[0];
                    Uri contentUris = null;
                    if ("image".equals(type)) {
                        contentUris = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUris = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUris = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    String selection = MediaStore.Images.Media._ID + "=?";
                    String[] selectionArgs = new String[]{split[1]};
                    photoPath = getDataColumn(context, contentUris, selection, selectionArgs);
                }
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            photoPath = uri.getPath();
        } else {
            photoPath = getDataColumn(context, uri, null, null);
        }

        return photoPath;
    }

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

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

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

    @Nullable
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null && !cursor.isClosed())
                cursor.close();
        }
        return null;
    }
}

先来讲一讲从路径到URI的转换,android中 路径基本上就是本地媒体路径: 以 “content:”开头,本地文件路径: 以"/"开头,以及网络地址:以“http”开头,
这是常规的写法, 其实也就是Uri中的 scheme(uri的结构 [scheme:][//authority][path][?query][#fragment]),不过需要注意到的一点就是,在把文件路径转换为Uri的时候,要注意加上scheme,也就是"file://", 例如:"file:///sdcard/"。
再来说说把Uri转换为路径,这里就需要根据scheme的值先判断Uri属于哪一种类型了,它分为本地媒体类型,本地文件类型,以及网络类型,先判断类型后,再根据不同的类型具体处理就可以了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值