码迷,mamicode.com
首页 > 移动开发 > 详细

Android4.4打开系统相册返回Null问题

时间:2016-05-12 13:37:38      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

public interface PhotoCallBack {
        void onSuccess(String picturePath);// 拿取相片成功
        void onFailure();// 拿取相片失败
    }

    /**
     * 获取图片路径
     * 
     * @param context
     * @param data
     * @param callback
     * @return
     */
    public static void getPhotoURLByAlbum(Context context, Intent data, PhotoCallBack callback) {
        if (data == null) {
            callback.onFailure();
            return;
        }
        final Uri selectedImage = data.getData();
        if (selectedImage == null) {
            callback.onFailure();
            return;
        }

        String picturePath = ""; // 关于Android4.4的图片路径获取,如果回来的Uri的格式有两种

            if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context, selectedImage)) {
                String wholeID = DocumentsContract.getDocumentId(selectedImage);
                String id = wholeID.split(":")[1];
                String[] column = { MediaStore.Images.Media.DATA };
                String sel = MediaStore.Images.Media._ID + "=?";
                Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[] { id }, null);
                if (cursor.moveToNext()) {
                    int columnIndex = cursor.getColumnIndex(column[0]);
                    picturePath = cursor.getString(columnIndex);
                    callback.onSuccess(picturePath);// 获取图片路径
                }
                cursor.close();
            } else {
                String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = context.getContentResolver().query(selectedImage, projection, null, null, null);
                if (cursor.moveToNext()) {
                    int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
                    picturePath = cursor.getString(column_index);
                    callback.onSuccess(picturePath);// 获取图片路径
                }
                cursor.close();
            }
    }

在onActivityResult中处理返回的数据。
同时一定要在打开相册的逻辑中做判断

Intent intent = new Intent();
intent.setType("image/*");// 从所有图片中进行选择
//根据版本号不同使用不同的Action  
if (Build.VERSION.SDK_INT <19) {  
    intent.setAction(Intent.ACTION_GET_CONTENT);  
}else {  
    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);  
}
((Activity) context).startActivityForResult(intent, Constants.REQUEST_CODE_HEADPIC_PICK_PHOTO);

参考:
http://blog.csdn.net/huangyanan1989/article/details/17263203
http://blog.csdn.net/eastman520/article/details/17756817

Android4.4打开系统相册返回Null问题

标签:

原文地址:http://blog.csdn.net/limiao2143/article/details/51364351

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!