Android应用开发常用方法打包(一)

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;
  }
}