您的位置:首页 > 移动开发 > Android开发

第一行代码Android 8.3调用摄像头和相册最新发现的bug

2019-06-10 19:29 471 查看

最近需要用到调用手机相册这门技术,就想到郭霖大神写的书里有,我也刚好敲过,就直接调用书里的代码,结果发现了一个隐藏的bug,就是调用手机相册时,如果你选择的时recent文件里的图片,那没问题,但是如果你选择download文件里的图片,会出现一个数值转换异常的情况,然后整个app强行退出,经过我的人工debug(写log)发现,问题出现在函数handleImageOnKitKat里,先看书上的源代码:

private void handleImageOnKitKat(Intent data){
String imagePath=null;
Uri uri=data.getData();
if(DocumentsContract.isDocumentUri(this,uri)){

//如果是Document类型的uri,则通过document id处理,如果你选择了download文件里的图片,则docId的值就变成了raw:+图片路径,我是通过写log发现的
String docId=DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())){
String id=docId.split(":")[1];//解析出数字格式的id
String selection=MediaStore.Images.Media._ID+"="+id;
imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);

//如果你选择download文件里的图片,会执行下面的代码
}else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){

//此时docId值并不能转成long型的值,所以会出现数值转换异常的情况
Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://" +
"downloads/public_downloads"),Long.valueOf(docId));
imagePath=getImagePath(contentUri,null);        }
}else if("content".equalsIgnoreCase(uri.getScheme())){
//如果是content类型的uri,则使用普通方式处理
imagePath=getImagePath(uri,null);
}else if("file".equalsIgnoreCase(uri.getScheme())){
//如果是file类型的uri,直接获取图片路径即可
imagePath=uri.getPath();
}
displayImage(imagePath);//根据图片路径显示图片
}

好了,来看解决办法:

if("com.android.providers.downloads.documents".equals(uri.getAuthority())){

//如果选择下载文件里的图片,获取到的docId是raw:+图片路径,所以只要从第五个字符开始读就可以直接获取图片路径了
imagePath=docId.substring(4);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: