千家信息网

Android开发中常用到的工具类有哪些

发表于:2024-10-24 作者:千家信息网编辑
千家信息网最后更新 2024年10月24日,这篇文章给大家介绍Android开发中常用到的工具类有哪些,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。作为一个程序员界的新晋司机,也是时候整理一些东西了,两三年的路走来,代码也
千家信息网最后更新 2024年10月24日Android开发中常用到的工具类有哪些

这篇文章给大家介绍Android开发中常用到的工具类有哪些,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

作为一个程序员界的新晋司机,也是时候整理一些东西了,两三年的路走来,代码也是边写边忘、边走边丢,很多问题忙着忙着就忘了,决定写点随笔供自己闲余时间回望,有需要的读者也可以随意瞄几眼,哪里有错有问题可以提出来,虽然我不见得会改,O(∩_∩)O哈哈~

日常开发中很多东西都是写过无数遍的,我本人没有每次都去重新写的习惯(不知道有没有小伙伴会如此耿直??)那么整理好自己的工具类还是有必要的。这里就记录几个目前为止我使用较多的。

常用工具类

 /**      * 根据手机的分辨率从 dp 的单位 转成为 px(像素)      */     public static int dip2px(Context context, float dpValue) {         final float scale = context.getResources().getDisplayMetrics().density;         return (int) (dpValue * scale + 0.5f);     }      /**      * 根据手机的分辨率从 px(像素) 的单位 转成为 dp      */     public static int px2dip(Context context, float pxValue) {         final float scale = context.getResources().getDisplayMetrics().density;         return (int) (pxValue / scale + 0.5f);     }      /**      * Md5 32位 or 16位 加密      *      * @param plainText      * @return 32位加密      */     public static String Md5(String plainText) {         StringBuffer buf = null;         try {             MessageDigest md = MessageDigest.getInstance("MD5");             md.update(plainText.getBytes());             byte b[] = md.digest();             int i;             buf = new StringBuffer("");             for (int offset = 0; offset < b.length; offset++) {                 i = b[offset];                 if (i < 0) i += 256;                 if (i < 16)                     buf.append("0");                 buf.append(Integer.toHexString(i));             }          } catch (NoSuchAlgorithmException e) {             e.printStackTrace();         }         return buf.toString();     }   /**      * 手机号正则判断      * @param str      * @return      * @throws PatternSyntaxException      */     public static boolean isPhoneNumber(String str) throws PatternSyntaxException {         if (str != null) {         String pattern = "(13\\d|14[579]|15[^4\\D]|17[^49\\D]|18\\d)\\d{8}";          Pattern r = Pattern.compile(pattern);         Matcher m = r.matcher(str);             return m.matches();         } else {             return false;         }     }  /**      * 检测当前网络的类型 是否是wifi      *      * @param context      * @return      */     public static int checkedNetWorkType(Context context) {         if (!checkedNetWork(context)) {             return 0;//无网络         }         ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);         if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()) {             return 1;//wifi         } else {             return 2;//非wifi         }     }      /**      * 检查是否连接网络      *      * @param context      * @return      */     public static boolean checkedNetWork(Context context) {         // 获得连接设备管理器         ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);         if (cm == null) return false;         /**          * 获取网络连接对象          */         NetworkInfo networkInfo = cm.getActiveNetworkInfo();          if (networkInfo == null || !networkInfo.isAvailable()) {             return false;         }         return true;     }      /**      * 检测GPS是否打开      *      * @return      */     public static boolean checkGPSIsOpen(Context context) {         boolean isOpen;         LocationManager locationManager = (LocationManager) context                 .getSystemService(Context.LOCATION_SERVICE);         if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){             isOpen=true;         }else{             isOpen = false;         }          return isOpen;     }      /**      * 跳转GPS设置      */     public static void openGPSSettings(final Context context) {         if (checkGPSIsOpen(context)) { //            initLocation(); //自己写的定位方法         } else { //            //没有打开则弹出对话框             AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialogCustom);              builder.setTitle("温馨提示");             builder.setMessage("当前应用需要打开定位功能。请点击\"设置\"-\"定位服务\"打开定位功能。");             //设置对话框是可取消的             builder.setCancelable(false);              builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {                 @Override                 public void onClick(DialogInterface dialogInterface, int i) {                     dialogInterface.dismiss();                     //跳转GPS设置界面                     Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);                     context.startActivity(intent);                 }             });             builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {                 @Override                 public void onClick(DialogInterface dialogInterface, int i) {                     dialogInterface.dismiss();                     ActivityManager.getInstance().exit();                 }             });             AlertDialog alertDialog = builder.create();             alertDialog.show();         }     }      /**      * 字符串进行Base64编码      * @param str      */     public static String StringToBase64(String str){         String encodedString = Base64.encodeToString(str.getBytes(), Base64.DEFAULT);         return encodedString;     }      /**      * 字符串进行Base64解码      * @param encodedString      * @return      */     public static String Base64ToString(String encodedString){         String decodedString =new String(Base64.decode(encodedString,Base64.DEFAULT));         return decodedString;     }

这里还有一个根据经纬度计算两点间真实距离的,一般都直接使用所集成第三方地图SDK中包含的方法,这里还是给出代码

/**      * 补充:计算两点之间真实距离      *      * @return 米      */     public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {         // 维度         double lat1 = (Math.PI / 180) * latitude1;         double lat2 = (Math.PI / 180) * latitude2;          // 经度         double lon1 = (Math.PI / 180) * longitude1;         double lon2 = (Math.PI / 180) * longitude2;          // 地球半径         double R = 6371;          // 两点间距离 km,如果想要米的话,结果*1000就可以了         double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;          return d * 1000;     }

常用文件类

文件类的代码较多,这里就只给出读写文件的

/**      * 判断SD卡是否可用      * @return SD卡可用返回true      */     public static boolean hasSdcard() {         String status = Environment.getExternalStorageState();         return Environment.MEDIA_MOUNTED.equals(status);     }      /**      * 读取文件的内容      * 
* 默认utf-8编码 * @param filePath 文件路径 * @return 字符串 * @throws IOException */ public static String readFile(String filePath) throws IOException { return readFile(filePath, "utf-8"); } /** * 读取文件的内容 * @param filePath 文件目录 * @param charsetName 字符编码 * @return String字符串 */ public static String readFile(String filePath, String charsetName) throws IOException { if (TextUtils.isEmpty(filePath)) return null; if (TextUtils.isEmpty(charsetName)) charsetName = "utf-8"; File file = new File(filePath); StringBuilder fileContent = new StringBuilder(""); if (file == null || !file.isFile()) return null; BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream( file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { if (!fileContent.toString().equals("")) { fileContent.append("\r\n"); } fileContent.append(line); } return fileContent.toString(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 读取文本文件到List字符串集合中(默认utf-8编码) * @param filePath 文件目录 * @return 文件不存在返回null,否则返回字符串集合 * @throws IOException */ public static List readFileToList(String filePath) throws IOException { return readFileToList(filePath, "utf-8"); } /** * 读取文本文件到List字符串集合中 * @param filePath 文件目录 * @param charsetName 字符编码 * @return 文件不存在返回null,否则返回字符串集合 */ public static List readFileToList(String filePath, String charsetName) throws IOException { if (TextUtils.isEmpty(filePath)) return null; if (TextUtils.isEmpty(charsetName)) charsetName = "utf-8"; File file = new File(filePath); List fileContent = new ArrayList(); if (file == null || !file.isFile()) { return null; } BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream( file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { fileContent.add(line); } return fileContent; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 向文件中写入数据 * @param filePath 文件目录 * @param content 要写入的内容 * @param append 如果为 true,则将数据写入文件末尾处,而不是写入文件开始处 * @return 写入成功返回true, 写入失败返回false * @throws IOException */ public static boolean writeFile(String filePath, String content, boolean append) throws IOException { if (TextUtils.isEmpty(filePath)) return false; if (TextUtils.isEmpty(content)) return false; FileWriter fileWriter = null; try { createFile(filePath); fileWriter = new FileWriter(filePath, append); fileWriter.write(content); fileWriter.flush(); return true; } finally { if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 向文件中写入数据
* 默认在文件开始处重新写入数据 * @param filePath 文件目录 * @param stream 字节输入流 * @return 写入成功返回true,否则返回false * @throws IOException */ public static boolean writeFile(String filePath, InputStream stream) throws IOException { return writeFile(filePath, stream, false); } /** * 向文件中写入数据 * @param filePath 文件目录 * @param stream 字节输入流 * @param append 如果为 true,则将数据写入文件末尾处; * 为false时,清空原来的数据,从头开始写 * @return 写入成功返回true,否则返回false * @throws IOException */ public static boolean writeFile(String filePath, InputStream stream, boolean append) throws IOException { if (TextUtils.isEmpty(filePath)) throw new NullPointerException("filePath is Empty"); if (stream == null) throw new NullPointerException("InputStream is null"); return writeFile(new File(filePath), stream, append); } /** * 向文件中写入数据 * 默认在文件开始处重新写入数据 * @param file 指定文件 * @param stream 字节输入流 * @return 写入成功返回true,否则返回false * @throws IOException */ public static boolean writeFile(File file, InputStream stream) throws IOException { return writeFile(file, stream, false); } /** * 向文件中写入数据 * @param file 指定文件 * @param stream 字节输入流 * @param append 为true时,在文件开始处重新写入数据; * 为false时,清空原来的数据,从头开始写 * @return 写入成功返回true,否则返回false * @throws IOException */ public static boolean writeFile(File file, InputStream stream, boolean append) throws IOException { if (file == null) throw new NullPointerException("file = null"); OutputStream out = null; try { createFile(file.getAbsolutePath()); out = new FileOutputStream(file, append); byte data[] = new byte[1024]; int length = -1; while ((length = stream.read(data)) != -1) { out.write(data, 0, length); } out.flush(); return true; } finally { if (out != null) { try { out.close(); stream.close(); } catch (IOException e) { e.printStackTrace(); } } } }

日期工具类

/**      * 将long时间转成yyyy-MM-dd HH:mm:ss字符串
* @param timeInMillis 时间long值 * @return yyyy-MM-dd HH:mm:ss */ public static String getDateTimeFromMillis(long timeInMillis) { return getDateTimeFormat(new Date(timeInMillis)); } /** * 将date转成yyyy-MM-dd HH:mm:ss字符串 *
* @param date Date对象 * @return yyyy-MM-dd HH:mm:ss */ public static String getDateTimeFormat(Date date) { return dateSimpleFormat(date, defaultDateTimeFormat.get()); } /** * 将年月日的int转成yyyy-MM-dd的字符串 * @param year 年 * @param month 月 1-12 * @param day 日 * 注:月表示Calendar的月,比实际小1 * 对输入项未做判断 */ public static String getDateFormat(int year, int month, int day) { return getDateFormat(getDate(year, month, day)); } /** * 获得HH:mm:ss的时间 * @param date * @return */ public static String getTimeFormat(Date date) { return dateSimpleFormat(date, defaultTimeFormat.get()); } /** * 格式化日期显示格式 * @param sdate 原始日期格式 "yyyy-MM-dd" * @param format 格式化后日期格式 * @return 格式化后的日期显示 */ public static String dateFormat(String sdate, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); java.sql.Date date = java.sql.Date.valueOf(sdate); return dateSimpleFormat(date, formatter); } /** * 格式化日期显示格式 * @param date Date对象 * @param format 格式化后日期格式 * @return 格式化后的日期显示 */ public static String dateFormat(Date date, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); return dateSimpleFormat(date, formatter); } /** * 将date转成字符串 * @param date Date * @param format SimpleDateFormat *
* 注: SimpleDateFormat为空时,采用默认的yyyy-MM-dd HH:mm:ss格式 * @return yyyy-MM-dd HH:mm:ss */ public static String dateSimpleFormat(Date date, SimpleDateFormat format) { if (format == null) format = defaultDateTimeFormat.get(); return (date == null ? "" : format.format(date)); } /** * 将"yyyy-MM-dd HH:mm:ss" 格式的字符串转成Date * @param strDate 时间字符串 * @return Date */ public static Date getDateByDateTimeFormat(String strDate) { return getDateByFormat(strDate, defaultDateTimeFormat.get()); } /** * 将"yyyy-MM-dd" 格式的字符串转成Date * @param strDate * @return Date */ public static Date getDateByDateFormat(String strDate) { return getDateByFormat(strDate, defaultDateFormat.get()); } /** * 将指定格式的时间字符串转成Date对象 * @param strDate 时间字符串 * @param format 格式化字符串 * @return Date */ public static Date getDateByFormat(String strDate, String format) { return getDateByFormat(strDate, new SimpleDateFormat(format)); } /** * 将String字符串按照一定格式转成Date
* 注: SimpleDateFormat为空时,采用默认的yyyy-MM-dd HH:mm:ss格式 * @param strDate 时间字符串 * @param format SimpleDateFormat对象 * @exception ParseException 日期格式转换出错 */ private static Date getDateByFormat(String strDate, SimpleDateFormat format) { if (format == null) format = defaultDateTimeFormat.get(); try { return format.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 将年月日的int转成date * @param year 年 * @param month 月 1-12 * @param day 日 * 注:月表示Calendar的月,比实际小1 */ public static Date getDate(int year, int month, int day) { Calendar mCalendar = Calendar.getInstance(); mCalendar.set(year, month - 1, day); return mCalendar.getTime(); } /** * 求两个日期相差天数 * * @param strat 起始日期,格式yyyy-MM-dd * @param end 终止日期,格式yyyy-MM-dd * @return 两个日期相差天数 */ public static long getIntervalDays(String strat, String end) { return ((java.sql.Date.valueOf(end)).getTime() - (java.sql.Date .valueOf(strat)).getTime()) / (3600 * 24 * 1000); } /** * 获得当前年份 * @return year(int) */ public static int getCurrentYear() { Calendar mCalendar = Calendar.getInstance(); return mCalendar.get(Calendar.YEAR); } /** * 获得当前月份 * @return month(int) 1-12 */ public static int getCurrentMonth() { Calendar mCalendar = Calendar.getInstance(); return mCalendar.get(Calendar.MONTH) + 1; } /** * 获得当月几号 * @return day(int) */ public static int getDayOfMonth() { Calendar mCalendar = Calendar.getInstance(); return mCalendar.get(Calendar.DAY_OF_MONTH); } /** * 获得今天的日期(格式:yyyy-MM-dd) * @return yyyy-MM-dd */ public static String getToday() { Calendar mCalendar = Calendar.getInstance(); return getDateFormat(mCalendar.getTime()); } /** * 获得昨天的日期(格式:yyyy-MM-dd) * @return yyyy-MM-dd */ public static String getYesterday() { Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DATE, -1); return getDateFormat(mCalendar.getTime()); } /** * 获得前天的日期(格式:yyyy-MM-dd) * @return yyyy-MM-dd */ public static String getBeforeYesterday() { Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DATE, -2); return getDateFormat(mCalendar.getTime()); } /** * 获得几天之前或者几天之后的日期 * @param diff 差值:正的往后推,负的往前推 * @return */ public static String getOtherDay(int diff) { Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DATE, diff); return getDateFormat(mCalendar.getTime()); } /** * 取得给定日期加上一定天数后的日期对象. * * @param //date 给定的日期对象 * @param amount 需要添加的天数,如果是向前的天数,使用负数就可以. * @return Date 加上一定天数以后的Date对象. */ public static String getCalcDateFormat(String sDate, int amount) { Date date = getCalcDate(getDateByDateFormat(sDate), amount); return getDateFormat(date); } /** * 取得给定日期加上一定天数后的日期对象. * * @param date 给定的日期对象 * @param amount 需要添加的天数,如果是向前的天数,使用负数就可以. * @return Date 加上一定天数以后的Date对象. */ public static Date getCalcDate(Date date, int amount) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, amount); return cal.getTime(); }

关于Android开发中常用到的工具类有哪些就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

0