Android에서 Uri와 Path 사이의 변환

8143 단어 SDK
Android Uri to Path
현재 나타나는 일반 Uri는 두 가지입니다.
  • 미디어 파일의 Uri는 content://로 데이터베이스 데이터임을 나타낸다.데이터베이스에 대한 조회가 정상적으로 되돌아오기
  • 다른 파일 Uri는 file://이며 이것은 파일임을 나타냅니다.이 uri는 Uri를 통해서.fromFile 메서드가 생성됩니다.

  • 직접 부호
    package com.xinmang.videoeffect.utils;
    
    import android.content.ContentResolver;
    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.v4.content.FileProvider;
    
    import com.xinmang.videoeffect.app.MainApplication;
    
    import java.io.File;
    
    public class UriTool {
        public static String getFilePathByUri(Context context, Uri uri) {
            String path = null;
            String scheme = uri.getScheme();
    
            //   file://    
            if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
                path = uri.getPath();
                return path;
            }
            //   content://    ,   content://media/extenral/images/media/17766
            if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        if (columnIndex > -1) {
                            path = cursor.getString(columnIndex);
                        }
                    }
                    cursor.close();
                }
                return path;
            }
            // 4.4        content://    ,   content://com.android.providers.media.documents/document/image%3A235700
            if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if (DocumentsContract.isDocumentUri(context, uri)) {
                    if (isExternalStorageDocument(uri)) {
                        // ExternalStorageProvider
                        final String docId = DocumentsContract.getDocumentId(uri);
                        final String[] split = docId.split(":");
                        final String type = split[0];
                        if ("primary".equalsIgnoreCase(type)) {
                            path = Environment.getExternalStorageDirectory() + "/" + split[1];
                            return path;
                        }
                    } else if (isDownloadsDocument(uri)) {
                        // DownloadsProvider
                        final String id = DocumentsContract.getDocumentId(uri);
                        final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                                Long.valueOf(id));
                        path = getDataColumn(context, contentUri, null, null);
                        return path;
                    } else if (isMediaDocument(uri)) {
                        // MediaProvider
                        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]};
                        path = getDataColumn(context, contentUri, selection, selectionArgs);
                        return path;
                    }
                } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                    // Return the remote address
                    if (isGooglePhotosUri(uri))
                        return uri.getLastPathSegment();
    
                    if (isQQMediaDocument(uri)) {
                        String paths = uri.getPath();
                        File fileDir = Environment.getExternalStorageDirectory();
                        File file = new File(fileDir, paths.substring("/QQBrowser".length(), paths.length()));
                        return file.exists() ? file.toString() : null;
                    }
    
                    return getDataColumn(context, uri, null, null);
                } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                    return uri.getPath();
                }
                else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
                    //       uri
                    path = uri.getPath();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                            && path != null && path.startsWith("/external")) {
                        return new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                                + path.replace("/external", "")).getPath();
                    } else {
                        String[] paths = uri.getPath().split("/0/");
                        if (paths.length == 2) {
                            return Environment.getExternalStorageDirectory() + "/" + paths[1];
                        }
                    }
                } else {
                    String[] paths = uri.getPath().split("/0/");
                    if (paths.length == 2) {
                        return Environment.getExternalStorageDirectory() + "/" + paths[1];
                    }
    
                }
            }
            return null;
        }
    
        private 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);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
            return null;
        }
    
    
        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());
        }
    
    
        public static Uri PathToUri(String path){
            Uri uri;
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                uri = Uri.fromFile(new File(path));
            } else {
                /**
                 * 7.0               Uri  ,     FileProvider
                 *         MIUI       size 0   
                 */
                uri = FileProvider.getUriForFile(MainApplication.getInstance(),  "com.xinmang.videoeffect.fileprovider", new File(path));
            }
    
            return uri;
        }
     /**
         *      qq       
         *
         * @param uri
         * @return
         */
        public static boolean isQQMediaDocument(Uri uri) {
            return "com.tencent.mtt.fileprovider".equals(uri.getAuthority());
        }
    
        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is Google Photos.
         */
        public static boolean isGooglePhotosUri(Uri uri) {
            return "com.google.android.apps.photos.content".equals(uri.getAuthority());
        }
    }
    
    

    좋은 웹페이지 즐겨찾기