android 设置头像在网上有很多例子,在这边就不多说了,主要是我在项目中有遇到从相册中获取图片设置头像是出现过问题,在这边做了一些总结:

在android中选择图片的时候,打开相册选择图片(根据是否4.4设置不同action),
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
} else {
intent.setAction(Intent.ACTION_GET_CONTENT);
};
在onActivityResult里面返回的Uri uri = data.getData();如果是android4.4 uri格式为content://com.android.providers.media.documents/document/image:3952,4.4以下格式为
content://media/external/images/media/3951,要获取图片的存储路径需要:
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT){
String wholeID = DocumentsContract.getDocumentId(contentUri);
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);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}else{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null,null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filePath = cursor.getString(column_index);
}。
另一种方式就是直接设置打开相册的action,
intent.setAction(Intent.ACTION_PICK);
intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
后面的onActivityResult里面就可以不区分4.4版本就可以获取到路径。经测试该种方法就可以实现从相册中获取图片


总的来说第一种方式的效果对于4.4的界面看起来很不错的,如果只求功能第二种就简便一些了。


注:使用 intent.setAction(Intent.ACTION_GET_CONTENT);华为手机荣耀7没有办法加载图片


以上是我亲测后得出的结论,可能我这边的手机版本的量不足,以供参考,如有不足敬请见谅,或者有不同意见的可以和我进行交流沟通。

更多相关文章

  1. 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
  2. Android(安卓)TabHost学习笔记
  3. Android(安卓)Widgets
  4. android studio 设置编译apk的名称以及配置签名,打包方式
  5. android studio与VS2019的安卓开发共存问题
  6. 安卓ListView去除分割线、设置边距
  7. android的PowerManager和PowerManager.WakeLock
  8. Android:布局(线性布局LinearLayout)
  9. ListView的优化就这么多了

随机推荐

  1. Java/Android回调——由一段Bmob查询操作
  2. Part 1:Multi-threading Android Apps fo
  3. android 判断联网类型
  4. cross compile busybox for android
  5. android 书架效果实现
  6. Android简单计算器界面实现
  7. Android Studio计算器 app
  8. Android GMS认证项总结
  9. Android中数据库升级
  10. android 获取当前设备的ip地址 mac地址