【问题标题】:retrieve absolute path when select image from gallery kitkat android从画廊kitkat android中选择图像时检索绝对路径
【发布时间】:2013-12-14 03:42:09
【问题描述】:

由于我支持我的应用程序到 Kitkat 版本,现在从图库中检索文件的方式有所不同。

我更喜欢这个Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT 从图库中检索文件并成功工作,但我需要该文件的绝对路径,我得到了

content://com.android.providers.media.documents/document/image:2505

对于低于 19 的版本,我们使用不同的 uri,因为我使用这种方式获取路径

Cursor cursor = this.getContentResolver().query(originalUri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String fpath = cursor.getString(column_index);

但在 19 版本中,它会给我空值如何获取用户选择的图像文件的绝对路径。

谢谢

【问题讨论】:

    标签: android image gallery


    【解决方案1】:

    这是选择文件后访问绝对路径的一种方法。

    以这种方式为 KK(KitKat) 获取新 URI 格式的数据后

    content://com.android.providers.media.documents/document/image:2505
    

    只需提取文档的 ID

    if(requestCode == GALLERY_KITKAT_INTENT_CALLED && resultCode == RESULT_OK){
    
        Uri originalUri = data.getData();
    
        final int takeFlags = data.getFlags()
                            & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // Check for the freshest data.
        getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
    
        /* now extract ID from Uri path using getLastPathSegment() and then split with ":"
        then call get Uri to for Internal storage or External storage for media I have used getUri()
        */
    
        String id = originalUri.getLastPathSegment().split(":")[1]; 
        final String[] imageColumns = {MediaStore.Images.Media.DATA };
        final String imageOrderBy = null;
    
        Uri uri = getUri();
        String selectedImagePath = "path";
    
        Cursor imageCursor = managedQuery(uri, imageColumns,
              MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
    
        if (imageCursor.moveToFirst()) {
            selectedImagePath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
        }
        Log.e("path",selectedImagePath ); // use selectedImagePath 
    }else if() {
          // for older version use existing code here
    }
    
    // By using this method get the Uri of Internal/External Storage for Media
    private Uri getUri() {
        String state = Environment.getExternalStorageState();
        if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
            return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
    
        return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    }
    

    【讨论】:

    • 我尝试执行此操作,但收到 01-09 12:09:49.333: E/AndroidRuntime(21760): java.lang.RuntimeException: 传递结果失败 ResultInfo{who=null, request= 1,结果=-1,数据=意图 { dat=content:flg=0x1 }} 到活动 {com.example.loadimage/com.example.loadimage.MainActivity}:java.lang.SecurityException:未找到 UID 的权限授予10259 和 Uri 内容:
    • 似乎在这一行发生异常 takePersistableUriPermission 我是否必须在清单中添加任何类型的权限
    • 它的抛出Caused by: java.lang.SecurityException: Requested flags 0x1, but only 0x0 are allowed
    • 行“getContentResolver().takePersistableUriPermission(originalUri, takeFlags);”在 KitKat 4.4.2 中引发安全异常。如果您将其注释掉或捕获异常,它似乎仍然可以正常工作。
    • 我仍然得到 null :(
    【解决方案2】:

    Pratik 的解决方案对我帮助很大。以下是在 Kitkat 4.4.2 中适用于我的版本。我改变的三件事是
    1) 使用内容解析器获取路径
    2) originalUri.getLastPathSegment().split(":")[1] 给我的索引超出范围,所以我使用索引 0 代替。到目前为止它一直在工作
    3) 在我们过滤带有 id 的游标时,移除了标记并检查最新数据。

    try {
            Uri originalUri = data.getData();
            String pathsegment[] = originalUri.getLastPathSegment().split(":");
            String id = pathsegment[0];
            final String[] imageColumns = { MediaStore.Images.Media.DATA };
            final String imageOrderBy = null;
    
            Uri uri = getUri();
            Cursor imageCursor = activity.getContentResolver().query(uri, imageColumns,
                                    MediaStore.Images.Media._ID + "=" + id, null, null);
    
            if (imageCursor.moveToFirst()) {
                value = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
    
        } catch (Exception e) {
            Toast.makeText(activity, "Failed to get image", Toast.LENGTH_LONG).show();
        }
    

    【讨论】:

      【解决方案3】:
      Bitmap bitmap = MediaStore.Images.Media
      .getBitmap(getActivity().getContentResolver(), uri);
      

      希望对你有所帮助。

      【讨论】:

        【解决方案4】:

        完美的解决方案:

        package utils;
        
        /**
         * Created by layer on 4/21/2015.
         */
        import android.annotation.TargetApi;
        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;
        
        public class ImageFilePath {
        
            /**
             * Method for return file path of Gallery image
             *
             * @param context
             * @param uri
             * @return path of the selected image file from gallery
             */
            @TargetApi(Build.VERSION_CODES.KITKAT)
            public static String getPath(final Context context, final Uri uri) {
        
                // check here to KITKAT or new version
                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 String id = DocumentsContract.getDocumentId(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 the remote address
                    if (isGooglePhotosUri(uri))
                        return uri.getLastPathSegment();
        
                    return getDataColumn(context, uri, null, null);
                }
                // File
                else if ("file".equalsIgnoreCase(uri.getScheme())) {
                    return uri.getPath();
                }
        
                return null;
            }
        
            /**
             * Get the value of the data column for this Uri. This is useful for
             * MediaStore Uris, and other file-based ContentProviders.
             *
             * @param context
             *            The context.
             * @param uri
             *            The Uri to query.
             * @param selection
             *            (Optional) Filter used in the query.
             * @param selectionArgs
             *            (Optional) Selection arguments used in the query.
             * @return The value of the _data column, which is typically a file path.
             */
            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 index = cursor.getColumnIndexOrThrow(column);
                        return cursor.getString(index);
                    }
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
                return null;
            }
        
            /**
             * @param uri
             *            The Uri to check.
             * @return Whether the Uri authority is ExternalStorageProvider.
             */
            public static boolean isExternalStorageDocument(Uri uri) {
                return "com.android.externalstorage.documents".equals(uri
                        .getAuthority());
            }
        
            /**
             * @param uri
             *            The Uri to check.
             * @return Whether the Uri authority is DownloadsProvider.
             */
            public static boolean isDownloadsDocument(Uri uri) {
                return "com.android.providers.downloads.documents".equals(uri
                        .getAuthority());
            }
        
            /**
             * @param uri
             *            The Uri to check.
             * @return Whether the Uri authority is MediaProvider.
             */
            public static boolean isMediaDocument(Uri uri) {
                return "com.android.providers.media.documents".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());
            }
        }
        

        https://github.com/layerlre/Android-Utility-Class/blob/master/utils/ImageFilePath.java

        希望对你有用。

        【讨论】:

          猜你喜欢
          • 2020-05-20
          • 1970-01-01
          • 2015-08-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多