转载请标明源地址:http://blog.csdn.net/gaolei1201/article/details/50392478

以前项目中做过上传头像 和仿QQ空间、微博发表文字和图片,也是花费了好多精力和时间多。现在花了几天时间做了整理与大家分享一下。下面把几个重要点列一下:

1.下面会把Demo源码奉献给大家,用的是以前公司的接口,首先需要登录才能更新头像和发表图文

2.我在项目中用的是OKHttp框架来实现Http网络请求,它的优点:非常高效,支持SPDY、连接池、GZIP和 HTTP 缓存。默认情况下,OKHttp会自动处理常见的网络问题,像二次连接、SSL的握手问题。如果你的应用程序中集成了OKHttp,Retrofit默认会使用OKHttp处理其他网络层请求。OkHttp是一个相对成熟的解决方案,据说Android4.4的源码中可以看到HttpURLConnection已经替换成OkHttp实现了。所以我们更有理由相信OkHttp的强大。详情可参考:Android OkHttp完全解析   。

3.展现图片用的是UniversalImageLoader

4.展示本地图片时一定要压缩,不然图片大的话一个几M,容易出现OOM

5.上传图片时也要压缩,不然图片大的话耗费时间太长,以及别人浏览图片时太耗流量

6.在获取上传图片时,刚开始是肯定获取不到的,因为一张图片上传需要几秒钟,为了较好的用户体验可以先展示本地图片,上传成功后下次再展示网络图片;另一种方法就是把所有图片都上传完成,然后再获取发表的内容

如图:

              

下面是网络请求封装类,别的类用接口回调可以获取请求结果

<span style="font-size:14px;">public class NetRequest {private MyInterface.NetRequestIterface netRequestIterface;private Context context;public NetRequest(MyInterface.NetRequestIterface netRequestIterface, Context context) {this.netRequestIterface = netRequestIterface;this.context = context;}/*** 网络请求用的是OKHttp,这个开源项目的好处是1.Android 6.0后不支持HttpClient请求,而它使用HttpUrlConnection 2.默认支持https*/public void httpRequest(Map<String, Object> map, final String requestUrl) {if (!CommonUtils.getUtilInstance().isConnectingToInternet(context)) {Toast.makeText(context,context.getString(R.string.internet_fail_connect),Toast.LENGTH_LONG).show();return;}OkHttpClient mOkHttpClient = new OkHttpClient();FormEncodingBuilder builder = new FormEncodingBuilder();if (null != map && !map.isEmpty())for (String key : map.keySet()) {builder.add(key, map.get(key)+"");}if(UserInfoUtil.getInstance().getAuthKey()!=null) {builder.add("authKey", UserInfoUtil.getInstance().getAuthKey());}Log.d("gaolei", " authKey------------------"+UserInfoUtil.getInstance().getAuthKey());Request request = new Request.Builder().url(requestUrl).post(builder.build()).build();try {mOkHttpClient.setConnectTimeout(5000, TimeUnit.MILLISECONDS);mOkHttpClient.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Request request, IOException e) {netRequestIterface.exception(e, requestUrl);}@Overridepublic void onResponse(final Response response) throws IOException {String result = response.body().string();netRequestIterface.changeView(result, requestUrl);}});}catch (Exception e){}}
}
</span>

下面是压缩图片

<span style="font-size:14px;"> //注意显示本地图片时一定要压缩质量,不然容易出现OOMpublic Bitmap trasformToZoomPhotoAndLessMemory(String url) {File file = new File(url);Log.d("gaolei", "file.length()--------original-------------" + file.length());BitmapFactory.Options options = new BitmapFactory.Options();// 通过这个bitmap获取图片的宽和高options.inJustDecodeBounds = true;int inSampleSize = 1;if (file.length() < 256 * 1024) {options.inPreferredConfig = Bitmap.Config.ARGB_8888;} else if (file.length() < 512 * 1024) {options.inPreferredConfig = Bitmap.Config.RGB_565;options.inSampleSize = 2;inSampleSize = 2;} else if (file.length() < 1024 * 1024) {options.inPreferredConfig = Bitmap.Config.RGB_565;options.inSampleSize = 4;inSampleSize = 4;} else {options.inPreferredConfig = Bitmap.Config.RGB_565;options.inSampleSize = 6;inSampleSize = 6;}options.inPurgeable = true;options.inInputShareable = true;// 注意这次要把options.inJustDecodeBounds 设为 false,这次图片是要读取出来的options.inJustDecodeBounds = false;Log.d("gaolei", "inSampleSize-----------------" + inSampleSize);int degree = readPictureDegree(file.getAbsolutePath());// Log.d("gaolei", "degree------------uploadImg--------------" +// degree);InputStream is = null;try {is = new FileInputStream(url);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}Bitmap cameraBitmap = BitmapFactory.decodeStream(is, null, options);// Bitmap cameraBitmap = BitmapFactory.decodeFile(url, options);Bitmap photo = rotaingImageView(degree, cameraBitmap);if (is != null) {try {is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return photo;}</span>

下面是把图片byte转化为字符串上传到服务器

<span style="font-size:14px;">    //请注意:上传图片时 我是把图片byte转化为字符串 上传到服务器,当然还可以用1.stream上传到服务器 2.Socket上传到服务器,不过我没试过public void uploadUserPhotoNew(final String filePath) {uploading_photo_progress.setVisibility(View.VISIBLE);//为什么另开一个线程呢?因为要把图片字节流转化为字符串上传,比较耗时,阻塞UI线程,会使应用卡卡卡,所以要另开一线程new Thread() {public void run() {String fileType = UploadPhotoUtil.getInstance().getFileType(filePath);String fileString = UploadPhotoUtil.getInstance().getUploadPhotoZoomString(filePath);Map<String, Object> map = new HashMap<String, Object>();map.put("imgType", fileType);map.put("imgBody", fileString);Message msg = handler.obtainMessage();msg.obj = map;msg.what = SAVE_PHOTO_IMAGE;handler.sendMessage(msg);}}.start();}</span>

下面是展示发表图文ListView的Adapter,这里比较重要,因为图片上传需要一段时间,马上获取发表的图文时,肯定显示不出来图片,现在先显示本地的,等下次进入时显示网络的

<span style="font-size:14px;">public class ThemeListViewAdapter extends BaseAdapter {private LayoutInflater inflater;private List<ThemeObject> list;private Context context;private List<String> uploadImgUrlList;public ThemeListViewAdapter(List<ThemeObject> list,List<String> uploadImgUrlList, Context context) {inflater = LayoutInflater.from(context);this.list = list;this.uploadImgUrlList = uploadImgUrlList;this.context = context;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn list.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}public void changeList(List<ThemeObject> list) {this.list = list;}@Overridepublic View getView(final int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubViewHolder holder = null;if (convertView == null) {holder = new ViewHolder();convertView = inflater.inflate(R.layout.theme_listview_items, null);holder.user_photo = (ImageView) convertView.findViewById(R.id.user_photo);holder.theme_img1 = (ImageView) convertView.findViewById(R.id.theme_img1);holder.theme_img2 = (ImageView) convertView.findViewById(R.id.theme_img2);holder.theme_img3 = (ImageView) convertView.findViewById(R.id.theme_img3);holder.theme_title = (TextView) convertView.findViewById(R.id.theme_title);holder.theme_desc = (TextView) convertView.findViewById(R.id.theme_desc);holder.user_name = (TextView) convertView.findViewById(R.id.user_name);holder.publish_theme_time = (TextView) convertView.findViewById(R.id.publish_theme_time);holder.theme_reply_num = (TextView) convertView.findViewById(R.id.theme_reply_num);holder.theme_praise_num = (TextView) convertView.findViewById(R.id.theme_praise_num);holder.game_playing_prefix = (TextView) convertView.findViewById(R.id.game_playing_prefix);holder.game_playing = (TextView) convertView.findViewById(R.id.game_playing);convertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}holder.user_photo.setTag(position + "");holder.theme_img1.setTag(position + "");holder.theme_img2.setTag(position + "");holder.theme_img3.setTag(position + "");holder.game_playing_prefix.setTag(position + "");holder.game_playing.setTag(position + "");if (list.size() > 0) {final ThemeObject object = list.get(position);if (holder.user_photo.getTag().equals("" + position)) {if (object.getUserPhoto() != null) {new CommonUtils().displayCircleImage(object.getUserPhoto(),holder.user_photo, "photo");} else {holder.user_photo.setImageDrawable(context.getResources().getDrawable(R.drawable.personal_default_photo));}List<PictureList> themePictureList = object.getPictureList();int pictureListSize = themePictureList.size();List<String> pictureUrlList = new ArrayList<String>();for (int i = 0; i < themePictureList.size(); i++) {pictureUrlList.add(themePictureList.get(i).getUrl());}Log.d("gaolei", "themePictureList.size()------------" + position + "-------" + themePictureList.size());int uploadImgUrlListSize = uploadImgUrlList.size();Log.d("gaolei", "uploadImgUrlListSize------------" + position + "-------" + uploadImgUrlListSize);if (pictureListSize == 0) {holder.theme_img1.setVisibility(View.GONE);holder.theme_img2.setVisibility(View.GONE);holder.theme_img3.setVisibility(View.GONE);}if (pictureListSize == 1) {holder.theme_img1.setVisibility(View.VISIBLE);if (holder.theme_img1.getTag().equals("" + position)) {CommonUtils.getUtilInstance().displayLowQualityInImage(pictureUrlList.get(0),holder.theme_img1);}}if (pictureListSize == 2) {holder.theme_img1.setVisibility(View.VISIBLE);holder.theme_img2.setVisibility(View.VISIBLE);if (holder.theme_img1.getTag().equals("" + position)) {CommonUtils.getUtilInstance().displayLowQualityInImage(pictureUrlList.get(0),holder.theme_img1);}if (holder.theme_img2.getTag().equals("" + position)) {CommonUtils.getUtilInstance().displayLowQualityInImage(pictureUrlList.get(1),holder.theme_img2);}}if (pictureListSize == 3) {holder.theme_img1.setVisibility(View.VISIBLE);holder.theme_img2.setVisibility(View.VISIBLE);holder.theme_img3.setVisibility(View.VISIBLE);if (holder.theme_img1.getTag().equals("" + position)) {CommonUtils.getUtilInstance().displayLowQualityInImage(pictureUrlList.get(0),holder.theme_img1);}if (holder.theme_img2.getTag().equals("" + position)) {CommonUtils.getUtilInstance().displayLowQualityInImage(pictureUrlList.get(1),holder.theme_img2);}if (holder.theme_img3.getTag().equals("" + position)) {CommonUtils.getUtilInstance().displayLowQualityInImage(pictureUrlList.get(2),holder.theme_img3);}}//这里比较重要,因为图片上传需要一段时间,马上获取发表的图文时,肯定显示不出来图片,现在先显示本地的,等下次进入时显示网络的if (position == 0) {if (uploadImgUrlListSize == 1) {holder.theme_img1.setVisibility(View.VISIBLE);if (holder.theme_img1.getTag().equals("" + position)) {Bitmap bitmap = UploadPhotoUtil.getInstance().trasformToZoomBitmapAndLessMemory(uploadImgUrlList.get(0));holder.theme_img1.setImageDrawable(new BitmapDrawable(context.getResources(), bitmap));}}if (uploadImgUrlListSize == 2) {holder.theme_img1.setVisibility(View.VISIBLE);holder.theme_img2.setVisibility(View.VISIBLE);if (holder.theme_img1.getTag().equals("" + position)) {Bitmap bitmap = UploadPhotoUtil.getInstance().trasformToZoomBitmapAndLessMemory(uploadImgUrlList.get(0));holder.theme_img1.setImageDrawable(new BitmapDrawable(context.getResources(), bitmap));}if (holder.theme_img2.getTag().equals("" + position)) {Bitmap bitmap = UploadPhotoUtil.getInstance().trasformToZoomBitmapAndLessMemory(uploadImgUrlList.get(1));holder.theme_img2.setImageDrawable(new BitmapDrawable(context.getResources(), bitmap));}}if (uploadImgUrlListSize == 3) {holder.theme_img1.setVisibility(View.VISIBLE);holder.theme_img2.setVisibility(View.VISIBLE);holder.theme_img3.setVisibility(View.VISIBLE);if (holder.theme_img1.getTag().equals("" + position)) {Bitmap bitmap = UploadPhotoUtil.getInstance().trasformToZoomBitmapAndLessMemory(uploadImgUrlList.get(0));holder.theme_img1.setImageDrawable(new BitmapDrawable(context.getResources(), bitmap));}if (holder.theme_img2.getTag().equals("" + position)) {Bitmap bitmap = UploadPhotoUtil.getInstance().trasformToZoomBitmapAndLessMemory(uploadImgUrlList.get(1));holder.theme_img2.setImageDrawable(new BitmapDrawable(context.getResources(), bitmap));}if (holder.theme_img3.getTag().equals("" + position)) {Bitmap bitmap = UploadPhotoUtil.getInstance().trasformToZoomBitmapAndLessMemory(uploadImgUrlList.get(2));holder.theme_img3.setImageDrawable(new BitmapDrawable(context.getResources(), bitmap));}}}holder.user_name.setText(object.getUserName());holder.theme_title.setText(object.getThemeTitle());holder.theme_desc.setText(object.getThemeDescr());holder.theme_reply_num.setText(object.getReplyNum() + "");holder.publish_theme_time.setText(CommonUtils.getUtilInstance().transformMillisToDate(object.getCreateTime()));holder.theme_praise_num.setText(object.getPraiseNum() + "");}holder.user_photo.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub}});}return convertView;}class ViewHolder {ImageView user_photo, theme_img1, theme_img2, theme_img3;TextView user_name, theme_title, theme_desc, publish_theme_time,theme_reply_num, theme_praise_num, game_playing,game_playing_prefix;}
}</span>

另外的开源项目地址:http://www.itlanbao.com/code/20150810/10044/100222.html ,http://download.csdn.net/download/reality_jie/6807867,一个开源项目源码有上传头像功能http://download.csdn.net/detail/gaolei1201/9414286效果如下图:

源码下载地址,欢迎光临......

Android实战之 上传头像 和仿QQ空间、微博发表文字和图片相关推荐

  1. typecho本地上传头像_微信QQ抖音透明头像制作方法,还有不会的吗?

       精彩内容每天更新 她搂着被子从床上坐起来,愣了十几秒,听到厨房有动静后,这才撒着脚往房间外跑,看到一抹修长背影在厨房里忙活. 邵允琛做好早餐从厨房出来,见陆瑶穿着睡裙站那,眉头皱了皱," ...

  2. mui开发app之多图压缩与上传(仿qq空间说说发表)

    应广大读者建议,已经将该项目源码提交到地址: https://github.com/devilyouwei/dashen 与本博客相关的多图压缩上传代码在dashen/service/ask.html ...

  3. 手机端-上传头像并裁剪

    <headrunat="server"><metahttp-equiv="Content-Type"content="text/ht ...

  4. Swift-一步步教你上传头像

    先前有人私信我说上传有问题,博主确认了下,发现是路径的问题,把Object-C的代码转变成Swift后路径就出了问题,不知道原因,推测可能是Swift本身的问题,所以博主换了一种路径方式,大家注意,关 ...

  5. android mysql上传头像,Android自定义控件仿QQ编辑和选取圆形头像

    android大家都有很多需要用户上传头像的需求,有的是选方形,有的是圆角矩形,有的是圆形. 首先我们要做一个处理图片的自定义控件,把传入的图片,经过用户选择区域,处理成一定的形状. 有的app是通过 ...

  6. Android 仿qq上传头像(一)

           转载请注明出处http://blog.csdn.net/u014163726/article/details/44994197        这么长时间没写博客感觉手都要生了啊,最近因为 ...

  7. android 模仿qq 上传头像,Android 仿qq上传头像(一)

    转载请注明出处http://blog.csdn.net/u014163726/article/details/44994197 这么长时间没写博客感觉手都要生了啊,最近因为工作的关系来到了上海,目前还 ...

  8. Android kotlin上传头像实现

    Android 上传头像基本上是每个app都有的功能,虽然看起来简单,但是作为新手的我实现起来却没有那么简单,实现如下 从相册获取照片,代码如下 //从相册获取照片private fun getFro ...

  9. 高仿微信上传头像附带压缩,旋转图片,附加demo

    本人初学者,再做项目时要求上传头像要像微信那种,需要外面裁剪框不动,里面图片可以改变大小,android系统裁剪和所要求的完全相反,所以,对于这个问题,困扰了我将近一个月,不断的修改,不断的出现新问题 ...

  10. Android上传头像,图片剪裁,压缩图片

    点击头像的时候开始调用camera()方法 private byte[] mContent = new byte[1024];// 保存照片转换后的字节,用与上传到服务器private Bitmap ...

最新文章

  1. linux 系统负载
  2. 对Python中路径操作指南
  3. scikit-learn 梯度提升树(GBDT)调参小结
  4. matlab计算海洋浮力频率_帝国理工学院海洋、海岸与建筑环境工程流体力学理学硕士研究生offer一枚...
  5. permgen_打破PermGen神话
  6. Java Fork / Join进行并行编程
  7. 光端机按照技术类型及接口种类是怎么分类的?
  8. Java新手造假_老板居然让我在Java项目中“造假”
  9. linux杀掉进程后总是重启,Linux监控进程,进程关闭自动重启方案
  10. php枚举属于什么类型,python枚举类型是什么?python枚举类型的简单介绍
  11. dfs Codeforces Round #356 (Div. 2) D
  12. 视频编解码器,bbv 缓冲区溢出和下溢
  13. python lambda函数两个列表大小关系_python lambda结合列表推导式?
  14. 如何在 Mac 上输入带重音符的字符?
  15. 电力-104规约实际测试1
  16. PR视频剪辑(项目包装)
  17. goodnote笔记同步 Android,goodnotes笔记
  18. 【Linux】计算机组成与进程
  19. 触摸屏:Linux输入子系统:多点触控协议
  20. 北京单身狗都去哪儿了

热门文章

  1. Android集成Sentry
  2. 活着的意义--读《此生未完成》有感
  3. 新成员入群监控自动发送邮件效果如何实现?
  4. 影像组学ibex_影像组学技术方法
  5. 手把手教你用Gurobi求解一个数学模型
  6. 「Medical Image Analysis」Note on 3D U-Net
  7. 【Linux上分之路】第二篇:Linux硬件、磁盘结构和分区,Linux文件目录结构
  8. IDEA版本控制:文件导航各种颜色含义
  9. 正则匹配大于等于号与indexof结合
  10. 快门光圈感光度口诀_怎么利用光圈快门感光度