设为首页 加入收藏

TOP

Android应用开发常用方法封装(一)
2017-10-13 09:43:03 】 浏览:2140
Tags:Android 应用开发 常用 方法 封装

在Android开发过程中,有很多东西都是常常用到的,为了提高效率,将常用的方法做个记录。

 

1.在网路编程中,如果还没建立套接字就使用发送write,会出现异常,封装后没问题了(若发送byte[]型自己更改参数类型):

public static boolean sendMsg(OutputStream outs,String str){


  boolean isConnect=false;

  if(outs!=null)             
  try {
    outs.write(str.getBytes());
    outs.flush();
    isConnect=true;
  } catch (IOException e) {
    isConnect=false;
  }

  return isConnect;
}

 

2.在接收图片消息时,通常先接收大小,再接收内容,而且内容可能分多次接收,我们可以封装这样一个类:

public class MyUtil {
  public static byte[] read(BufferedInputStream bin, int size, int max) {
    byte[] image = new byte[size];
    int hasRead = 0;
    while (true) {
      if (max > size - hasRead) {
        max = size - hasRead;    //剩下的字节不及max,则剩下的字节赋值为max
      }


      try {
        hasRead = hasRead + bin.read(image, hasRead, max);  //累计读取的字节
       } catch (IOException e) {
        e.printStackTrace();
      }


      if (hasRead == size) {
        break;
      }
    }
    return image;
  }
}

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Android_实用技术(3)—— Servi.. 下一篇Android学习路线总结,绝对干货

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目