Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

后端 未结 19 2304
温柔的废话
温柔的废话 2020-11-22 02:44

Before KitKat (or before the new Gallery) the Intent.ACTION_GET_CONTENT returned a URI like this

content://media/external/images/media/39

19条回答
  •  臣服心动
    2020-11-22 03:28

    @paul burke's answer works fine for both camera and gallery pictures for API level 19 and above, but it doesn't work if your Android project's minimum SDK is set to below 19, and some answers referring above doesn't work for both gallery and camera. Well, I have modified @paul burke's code which works for API level below 19. Below is the code.

    public static String getPath(final Context context, final Uri uri) {
    
        final boolean isKitKat = Build.VERSION.SDK_INT >=
                                 Build.VERSION_CODES.KITKAT;
        Log.i("URI",uri+"");
        String result = uri+"";
    
        // DocumentProvider
        // if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        if (isKitKat && (result.contains("media.documents"))) {
    
            String[] ary = result.split("/");
            int length = ary.length;
            String imgary = ary[length-1];
            final String[] dat = imgary.split("%3A");
    
            final String docId = dat[1];
            final String type = dat[0];
    
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            }
            else if ("video".equals(type)) {
            }
            else if ("audio".equals(type)) {
            }
    
            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                dat[1]
            };
    
            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
        else
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
    
        return null;
    }
    
    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);
            }
        }
        finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
    

提交回复
热议问题