我常用的一些Utils方法

作者: wanbo_ | 来源:发表于2016-05-06 10:08 被阅读659次
    • 在做项目到的时候,我通常会自己写一些Utils方法,现在向大家分享一下,同时也是在这里记录整理一下,以后会不定期更新的
    • 大家有什么好的,自己写的或者学习到的Utils方法,可以发给我,一起整理,一起学习

    网络数据操作类

    这部分主要是对从网络获取的数据做处理操作的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();
        }
    }
    

    相关文章

      网友评论

      • 蚂蚁上树卡:大神我想问下,你这个做的内存缓存中并没有缓存成功是怎么回事?lurcache.put()不能放进去,为空
      • pdog18:sp提交用apply可以吗。不阻塞主线程。
        wanbo_:@0a5c44d4aa57 没有打扰呀,一起进步~:smile:
        pdog18:@听任蔓草堙路 谢谢,打扰你了。其实我按下回复的时候也想到可能有这样的场景,谢谢,新年快乐。
        wanbo_:@0a5c44d4aa57 apply不会马上执行,建议用commit。
      • 最爱当年的我:不是很多

      本文标题:我常用的一些Utils方法

      本文链接:https://www.haomeiwen.com/subject/zsfjrttx.html