(1条消息) 解决android4.4以上系统的相册选择图片后获取不到有效的URI

最近用到上传图片发现,当选择相册里的照片时,会出现无效的URI,android4.4以上系统,选择相册中的最近照片,也会报同样的错误。

找到如下两个方法:

方法一:

/**
     * 图片选择及拍照结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != RESULT_OK) {
            return;
        }
        Uri uri = null;
        switch (requestCode) {
            case PHOTOZOOM:// 相册
                if (data == null) {
                    return;
                }
                uri = data.getData();
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor cursor = managedQuery(uri, proj, null, null, null);
                int column_index = cursor
                       .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                path = cursor.getString(column_index);// 图片在的路径
                Intent intent3 = new Intent(mContext, UserRectClipHead.class);
                intent3.putExtra("path", path);
                Log.i("选择图片路径",path+"");
                startActivityForResult(intent3, IMAGE_COMPLETE);
                break;
            case PHOTOTAKE:// 拍照
                path = photoSavePath + photoSaveName;
                uri = Uri.fromFile(new File(path));
                Intent intent2 = new Intent(mContext, UserRectClipHead.class);
                intent2.putExtra("path", path);
                startActivityForResult(intent2, IMAGE_COMPLETE);
                break;
            case IMAGE_COMPLETE:
                final String temppath = data.getStringExtra("path");
                Intent intent = new Intent();
                saveAllPath = FileUtils.saveBitmap(compressImage(BitmapUtils.UrlToBitmap(temppath)), ((int) (Math.random() * 10000)) + ".png");//质量压缩并存储得到path
                        intent.putExtra("path", saveAllPath);
//                intent.putExtra("path", temppath);
                setResult(0, intent);
                try {
                    cbuilder = new CustomDialogLoading.Builder(mContext, "上传中...");
                    mDialog = cbuilder.create();
                    mDialog.show();
                    postFile(saveAllPath);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                add_img.setImageBitmap(BitmapUtils.UrlToBitmap(temppath));
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

发现有些手机获取不到图片的path,后来经查找发现是因为android4.4以上的手机相册中有个最近的照片,是获取不到path路径的,更改如下可以解决:

/**
     * 图片选择及拍照结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != RESULT_OK) {
            return;
        }
        Uri uri = null;
        switch (requestCode) {
            case PHOTOZOOM:// 相册
                if (data == null) {
                    return;
                }
                uri = data.getData();
                //此处为了解决android4.4 相册选择时的 选择最近图片 获取不到path问题
                if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT){//4.4及以上
                    String wholeID = DocumentsContract.getDocumentId(uri);
                    String id = wholeID.split(":")[1];
                    String[] column = { MediaStore.Images.Media.DATA };
                    String sel = MediaStore.Images.Media._ID + "=?";
                    Cursor cursor = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column,
                            sel, new String[] { id }, null);
                    int columnIndex = cursor.getColumnIndex(column[0]);
                    if (cursor.moveToFirst()) {
                        path = cursor.getString(columnIndex);
                    }
                    cursor.close();
                }else{//4.4以下,即4.4以上获取路径的方法
                    String[] projection = { MediaStore.Images.Media.DATA };
                    Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    path = cursor.getString(column_index);
                }
//                }
                Intent intent3 = new Intent(mContext, UserRectClipHead.class);
                intent3.putExtra("path", path);
                Log.i("x选择图片",path+"");
                startActivityForResult(intent3, IMAGE_COMPLETE);
                break;
            case PHOTOTAKE:// 拍照
                path = photoSavePath + photoSaveName;
                uri = Uri.fromFile(new File(path));
                Intent intent2 = new Intent(mContext, UserRectClipHead.class);
                intent2.putExtra("path", path);
                startActivityForResult(intent2, IMAGE_COMPLETE);
                break;
            case IMAGE_COMPLETE:
                final String temppath = data.getStringExtra("path");
                Intent intent = new Intent();
                saveAllPath = FileUtils.saveBitmap(compressImage(BitmapUtils.UrlToBitmap(temppath)), ((int) (Math.random() * 10000)) + ".png");//质量压缩并存储得到path
                        intent.putExtra("path", saveAllPath);
//                intent.putExtra("path", temppath);
                setResult(0, intent);
                try {
                    cbuilder = new CustomDialogLoading.Builder(mContext, "上传中...");
                    mDialog = cbuilder.create();
                    mDialog.show();
                    postFile(saveAllPath);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                add_img.setImageBitmap(BitmapUtils.UrlToBitmap(temppath));
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

方法二:

  1. /**
  2. * 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换
  3. * @param activity
  4. * @param imageUri
  5. * @author yaoxing
  6. * @date 2014-10-12
  7. */
  8. @TargetApi(19)
  9. public static String getImageAbsolutePath(Activity context, Uri imageUri) {
  10. if (context == null || imageUri == null)
  11. return null;
  12. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
  13. if (isExternalStorageDocument(imageUri)) {
  14. String docId = DocumentsContract.getDocumentId(imageUri);
  15. String[] split = docId.split(":");
  16. String type = split[0];
  17. if ("primary".equalsIgnoreCase(type)) {
  18. return Environment.getExternalStorageDirectory() + "/" + split[1];
  19. }
  20. } else if (isDownloadsDocument(imageUri)) {
  21. String id = DocumentsContract.getDocumentId(imageUri);
  22. Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
  23. return getDataColumn(context, contentUri, null, null);
  24. } else if (isMediaDocument(imageUri)) {
  25. String docId = DocumentsContract.getDocumentId(imageUri);
  26. String[] split = docId.split(":");
  27. String type = split[0];
  28. Uri contentUri = null;
  29. if ("image".equals(type)) {
  30. contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  31. } else if ("video".equals(type)) {
  32. contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
  33. } else if ("audio".equals(type)) {
  34. contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  35. }
  36. String selection = MediaStore.Images.Media._ID + "=?";
  37. String[] selectionArgs = new String[] { split[1] };
  38. return getDataColumn(context, contentUri, selection, selectionArgs);
  39. }
  40. } // MediaStore (and general)
  41. else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
  42. // Return the remote address
  43. if (isGooglePhotosUri(imageUri))
  44. return imageUri.getLastPathSegment();
  45. return getDataColumn(context, imageUri, null, null);
  46. }
  47. // File
  48. else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
  49. return imageUri.getPath();
  50. }
  51. return null;
  52. }
  53. public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
  54. Cursor cursor = null;
  55. String column = MediaStore.Images.Media.DATA;
  56. String[] projection = { column };
  57. try {
  58. cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
  59. if (cursor != null && cursor.moveToFirst()) {
  60. int index = cursor.getColumnIndexOrThrow(column);
  61. return cursor.getString(index);
  62. }
  63. } finally {
  64. if (cursor != null)
  65. cursor.close();
  66. }
  67. return null;
  68. }
  69. /**
  70. * @param uri The Uri to check.
  71. * @return Whether the Uri authority is ExternalStorageProvider.
  72. */
  73. public static boolean isExternalStorageDocument(Uri uri) {
  74. return "com.android.externalstorage.documents".equals(uri.getAuthority());
  75. }
  76. /**
  77. * @param uri The Uri to check.
  78. * @return Whether the Uri authority is DownloadsProvider.
  79. */
  80. public static boolean isDownloadsDocument(Uri uri) {
  81. return "com.android.providers.downloads.documents".equals(uri.getAuthority());
  82. }
  83. /**
  84. * @param uri The Uri to check.
  85. * @return Whether the Uri authority is MediaProvider.
  86. */
  87. public static boolean isMediaDocument(Uri uri) {
  88. return "com.android.providers.media.documents".equals(uri.getAuthority());
  89. }
  90. /**
  91. * @param uri The Uri to check.
  92. * @return Whether the Uri authority is Google Photos.
  93. */
  94. public static boolean isGooglePhotosUri(Uri uri) {
  95. return "com.google.android.apps.photos.content".equals(uri.getAuthority());
  96. }
(0)

相关推荐