Android常用的工具类的收集首页投稿(暂停使用,暂停投稿)Android开发经验谈

我常用的一些Utils方法

2016-05-06  本文已影响659人  wanbo_

网络数据操作类

这部分主要是对从网络获取的数据做处理操作的Utils方法

  1. 将输入流中的文本数据转化为String类型
     public static String getTextFromStream(InputStream is){
       //设置已1字节来存储到流中
       byte[] b=new byte[1024];
       int len=0;
       //创建字节数组输出流,读取输入流的文本数据时,同步把数据写入字节数组输出流
       ByteArrayOutputStream bos=new ByteArrayOutputStream();
       try {
           while ((len=is.read(b))!=-1){
               bos.write(b,0,len);
           }
           String text=new String(bos.toByteArray());//这里可以设置编码方式
           bos.close();
           return text;
       } catch (IOException e) {
           e.printStackTrace();
       }
       return null;
   }
  1. 将输入流中的文本数据转化为字节数组
  public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

SharedPreferences工具类

这部分简单封装了几个常用的SharedPreferences相关方法直接调用即可,想添加其他类型也可以直接添加

  public class PrefUtils {
    public static final String PREF_NAME="config";

    public static boolean getBoolean(Context ctx,String key,Boolean defaultValue){
        SharedPreferences sp=ctx.getSharedPreferences(PREF_NAME,ctx.MODE_PRIVATE);
        return sp.getBoolean(key,defaultValue);
    }

    public static void setBoolean(Context ctx,String key,Boolean value){
        SharedPreferences sp=ctx.getSharedPreferences(PREF_NAME,ctx.MODE_PRIVATE);
        sp.edit().putBoolean(key,value).commit();
    }

    public static String getString(Context ctx,String key,String defaultValue){
        SharedPreferences sp=ctx.getSharedPreferences(PREF_NAME,ctx.MODE_PRIVATE);
        return sp.getString(key,defaultValue);
    }

    public static void setString(Context ctx,String key,String value){
        SharedPreferences sp=ctx.getSharedPreferences(PREF_NAME,ctx.MODE_PRIVATE);
        sp.edit().putString(key,value).commit();
    }

}

Calendar工具类

这部分主要是针对日期的判断处理的工具方法

  1. 检查两个Calendar是否相同(包括年,月,日)
   public static boolean sameDate(Calendar cal, Calendar selectedDate) {
        return cal.get(Calendar.MONTH) == selectedDate.get(Calendar.MONTH)
                && cal.get(Calendar.YEAR) == selectedDate.get(Calendar.YEAR)
                && cal.get(Calendar.DAY_OF_MONTH) == selectedDate.get(Calendar.DAY_OF_MONTH);
    }
  1. 检查一个Calendar和Date是否相同(包括年,月,日)
  public static boolean sameDate(Calendar cal, Date selectedDate) {
        Calendar selectedCal = Calendar.getInstance();
        selectedCal.setTime(selectedDate);
        return cal.get(Calendar.MONTH) == selectedCal.get(Calendar.MONTH)
                && cal.get(Calendar.YEAR) == selectedCal.get(Calendar.YEAR)
                && cal.get(Calendar.DAY_OF_MONTH) == selectedCal.get(Calendar.DAY_OF_MONTH);
    }
  1. 检查一个Date是否存在于两个Calendar之间
  public static boolean isBetweenInclusive(Date selectedDate, Calendar startCal, Calendar endCal) {
        Calendar selectedCal = Calendar.getInstance();
        selectedCal.setTime(selectedDate);
        // Check if we deal with the same day regarding startCal and endCal
        if (sameDate(selectedCal, startCal)) {
            return true;
        } else {
            return selectedCal.after(startCal) && selectedCal.before(endCal);
        }
    }
  1. 把一个毫秒表示时间转化为字符串
  public static String getDuration(Context context, long millis) {
        if (millis < 0) {
            throw new IllegalArgumentException("Duration must be greater than zero!");
        }

        long days = TimeUnit.MILLISECONDS.toDays(millis);
        millis -= TimeUnit.DAYS.toMillis(days);
        long hours = TimeUnit.MILLISECONDS.toHours(millis);
        millis -= TimeUnit.HOURS.toMillis(hours);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);

        StringBuilder sb = new StringBuilder(64);
        if (days > 0) {
            sb.append(days);
            sb.append(context.getResources().getString(R.string.agenda_event_day_duration));
            return (sb.toString());
        } else {
            if (hours > 0) {
                sb.append(hours);
                sb.append("h");
            }
            if (minutes > 0) {
                sb.append(minutes);
                sb.append("m");
            }
        }
        return (sb.toString());
    }

像素密度工具类

这部分主要针对于在代码中队尺寸单位做处理的工具类

  1. 获取设备显示宽度(高度同理)
  private int getDeviceWidth() {
        // 得到屏幕的宽度
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }
  1. 单位dp对单位px的转换
  private int dip2px(float dipValue) {
        float m = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * m + 0.5f);
    }

数据加密工具类

  1. MD5加密
    public static String encode(String string) throws Exception {
        byte[] hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读