专栏名称: 程序员大咖
为程序员提供最优质的博文、最精彩的讨论、最实用的开发资源;提供最新最全的编程学习资料:PHP、Objective-C、Java、Swift、C/C++函数库、.NET Framework类库、J2SE API等等。并不定期奉送各种福利。
目录
相关文章推荐
程序员小灰  ·  Manus,又一国产AI封神了,一码难求! ·  2 天前  
OSC开源社区  ·  三句话让老板直接给我主动放假 ·  4 天前  
OSC开源社区  ·  go-zero突破三万星——star数量最高 ... ·  4 天前  
51好读  ›  专栏  ›  程序员大咖

Android开发中常用到的工具类整理

程序员大咖  · 公众号  · 程序员  · 2018-05-20 10:24

正文

点击上方“ 程序员大咖 ”,选择“置顶公众号”

关键时刻,第一时间送达!


2018年 ,新的一年满血复活,新年总要有点新的东西,作为一个程序员界的新晋司机,也是时候整理一些东西了,两三年的路走来,代码也是边写边忘、边走边丢,很多问题忙着忙着就忘了,决定写点随笔供自己闲余时间回望,有需要的读者也可以随意瞄几眼,哪里有错有问题可以提出来,虽然我不见得会改,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 = "(13d|14[579]|15[^4D]|17[^49D]|18d)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("");                }                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






请到「今天看啥」查看全文