相信开发过一段Android的都被Android中的兼容性问题给折腾过,有时这确实很无奈,Android被不同的厂商改的七零八落的。本文主要总结下本人在实际的项目开发过程中所遇到的兼容性问题,以及最后的解决办法。本文将持续更新。
1. 选择系统相册时HTC 7出现的系统崩溃(空指针异常) 系统版本 2.3.7
最近在做一发表的功能时,需要从系统相册中选择图片,最后有将此图片上传服务端。通常从系统相册中选择图片写法如下:
albumButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, AppContext.GETIMAGE_BYSDCARD); } });
然后在onActivityResult中获取刚刚选取的照片:
1 @Override 2 protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 3 if (resultCode == RESULT_OK) { 4 if (requestCode == AppContext.GETIMAGE_BYSDCARD || requestCode == AppContext.GETIMAGE_BYCAMERA) { 5 if (requestCode == AppContext.GETIMAGE_BYSDCARD && null != data) { 6 Uri selectedImage = data.getData(); 7 String[] filePathColumn = { MediaStore.Images.Media.DATA }; 8 Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); 9 if (cursor != null) { 10 if (cursor.moveToFirst()) { 11 //int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 12 int columnIndex = cursor.getColumnIndexOrThrow(filePathColumn[0]); 13 photoPath = cursor.getString(columnIndex); 14 } 15 cursor.close(); 16 } 17 } 18 } 19 } 20 }
可以在HTC7 2.3.7 上发现无法获取图片,如果上述代码中没有做cursor != null 则系统崩溃,最后定为出原因在于Uri selectedImage = data.getData();这行代码上,在其他手机上,此处返回格式为content://media/external/images/media/244709,因此自然是通过接下来的Content Privider方式获取到图片实际地址。而在HTC此手机上,返回的结果却为:/storage/sdcard0/DCIM/Camera/IMG_20140608_162447.jpg,即直接返回了所选取图片的地址,因此,需要针对性的做出如下处理:
1 @Override 2 protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 3 if (resultCode == RESULT_OK) { 4 if (requestCode == AppContext.GETIMAGE_BYSDCARD || requestCode == AppContext.GETIMAGE_BYCAMERA) { 5 if (requestCode == AppContext.GETIMAGE_BYSDCARD && null != data) { 6 Uri selectedImage = data.getData(); 7 String[] filePathColumn = { MediaStore.Images.Media.DATA }; 8 Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); 9 if (cursor != null) { 10 if (cursor.moveToFirst()) { 11 //int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 12 int columnIndex = cursor.getColumnIndexOrThrow(filePathColumn[0]); 13 photoPath = cursor.getString(columnIndex); 14 } 15 cursor.close(); 16 } else { 17 if (selectedImage != null) { 18 String tmpPath = selectedImage.getPath(); 19 if (tmpPath != null && (tmpPath.endsWith(".jpg") || tmpPath.endsWith(".png") || tmpPath.endsWith(".gif"))) { 20 photoPath = tmpPath; 21 } 22 } 23 } 24 } 25 } 26 } 27 }
----------------------------
一天整理一点 更新一点吧...