从图库选择图片后根据Intent获取真实地址

通过Intent打开系统图库的方式可以选择以下:

Intent it = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.INTERNAL_CONTENT_URI);
activity.startActivityForResult(it, requestCode);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
activity.startActivityForResult(Intent.createChooser(intent, "选择图片"),requestCode);

对于不同系统版本返回的Uri的格式是不一样的,即使是相同版本,在不同型号的手机中,得到的结果也不一致。所以与其判断Build.VERSION,不如直接判断Uri的内容。

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPathByData(Activity context, Intent data) {
   if (data == null || data.getData() == null) {
       return null;
   }
   Uri uri = data.getData();
   String[] projection = {MediaStore.Images.Media.DATA};
   Cursor cursor = null;
   switch (uri.getScheme()) {
       case "file":
           cursor = context.getContentResolver().query(uri, projection, null, null, null);
           break;
       case "content":
           switch (uri.getHost()) {
               case "media":
                   cursor = context.getContentResolver().query(uri, projection, null, null, null);
                   break;
               case "com.android.providers.media.documents":
                   String wholeID = DocumentsContract.getDocumentId(uri);
                   String id = wholeID.split(":")[1];
                   String sel = MediaStore.Images.Media._ID + "=?";
                   cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                           projection, sel, new String[]{id}, null);
                   break;
               case "com.android.providers.downloads.documents":
                   String dId = DocumentsContract.getDocumentId(uri);
                   Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(dId));
                   cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
                   break;
           }
           break;
   }
   String path;
   if (cursor != null) {
       cursor.moveToNext();
       int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
       path = cursor.getString(index);
       cursor.close();
   } else {
       path = uri.getPath();
   }
   return path;
}

你可能感兴趣的:(Android)