前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【收藏篇】Android 开发中常用的10种工具类

【收藏篇】Android 开发中常用的10种工具类

作者头像
程序员小猿
发布2021-01-18 10:00:17
7010
发布2021-01-18 10:00:17
举报
文章被收录于专栏:程序IT圈

导语

Android开发中,收集一些常用的代码工具类是非常重要的。现在Android开发技术已经很成熟了,很多代码大牛已经写出了很多框架和工具类,我们现在应该要站在巨人的肩膀上做开发了。今天我把平时开发中收集最常用的 10 个工具类,分享给大家。以后开发中合理利用,对于在平时开发中的效率是非常有帮助的 。

1安装应用APK

代码语言:javascript
复制
// 安装应用APK
private void installApk(String apkFilePath) {
       File apkfile = new File(apkFilePath);        
        if (!apkfile.exists()) {            
            return;
       }
       Intent i = new Intent(Intent.ACTION_VIEW);
       i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
       startActivity(i);
   }
}

2MD5算法

代码语言:javascript
复制
public final static String MD5(String s) {        
            char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};        
            try {            
            byte[] btInput = s.getBytes();          // 获得MD5摘要算法的 MessageDigest 对象
           MessageDigest mdInst = MessageDigest.getInstance("MD5");  // 使用指定的字节更新摘要
           mdInst.update(btInput);                 // 获得密文
           byte[] md = mdInst.digest();            // 把密文转换成十六进制的字符串形式
           int j = md.length;            
            char str[] = new char[j * 2];            
            int k = 0;            //把字节转换成对应的字符串
           for (int i = 0; i < j; i++) {                
                byte byte0 = md[i];
               str[k++] = hexDigits[byte0 >>> 4 & 0xf];
               str[k++] = hexDigits[byte0 & 0xf];
           }           
                 return new String(str);
       } catch (Exception e) {
           e.printStackTrace();            
                 return null;
       }
   }

3判断现在是否有网络

代码语言:javascript
复制
private boolean NetWorkStatus() {
       ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);       cwjManager.getActiveNetworkInfo();        
        boolean netSataus = true;        
        if (cwjManager.getActiveNetworkInfo() != null) {       netSataus = cwjManager.getActiveNetworkInfo().isAvailable();       Toast.makeText(this, "网络已经打开", Toast.LENGTH_LONG).show();       }
    else {
       Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络")
                                       .setMessage("是否对网络进行设置?");
       b.setPositiveButton("是", new DialogInterface.OnClickListener()
       {    
               public void onClick(DialogInterface dialog, int whichButton) {
               Intent mIntent = new Intent("/");
               ComponentName comp = new ComponentName( "com.android.settings", "com.android.settings.WirelessSettings");
               mIntent.setComponent(comp);
               mIntent.setAction("android.intent.action.VIEW");
               startActivityForResult(mIntent,0);
               }
               }).setNeutralButton("否", new DialogInterface.OnClickListener() {                        
                public void onClick(DialogInterface dialog, int whichButton) {
                       dialog.cancel();
                       }
               }).show();
               }                
                return netSataus;
       }

4获取设备屏幕的宽度高度密度

代码语言:javascript
复制
public  class   DisplayUtil {
    /**
    * 得到设备屏幕的宽度
    */
   public static int getScreenWidth(Context context) {        
        return context.getResources().getDisplayMetrics().widthPixels;
   }    /**
    * 得到设备屏幕的高度
    */
   public static int getScreenHeight(Context context) {        
        return context.getResources().getDisplayMetrics().heightPixels;
   }    /**
    * 得到设备的密度
    */
   public static float getScreenDensity(Context context) {        
        return context.getResources().getDisplayMetrics().density;
   }
   }

5dp、sp 转换为 px 的工具类

代码语言:javascript
复制
public  class   DisplayUtil {          
   /**
    * 将px值转换为dip或dp值,保证尺寸大小不变
    */
   public static int px2dip(Context context, float pxValue) {        final float scale = context.getResources().getDisplayMetrics().density;        return (int) (pxValue / scale + 0.5f);
   }    /**
    * 将dip或dp值转换为px值,保证尺寸大小不变
    *
    * @param dipValue
    * @param scale
    *            (DisplayMetrics类中属性density)
    * @return
    */
   public static int dip2px(Context context, float dipValue) {        
        final float scale = context.getResources().getDisplayMetrics().density;        
        return (int) (dipValue * scale + 0.5f);
   }    /**
    * 将px值转换为sp值,保证文字大小不变
    *
    * @param pxValue
    * @param fontScale
    *            (DisplayMetrics类中属性scaledDensity)
    * @return
    */
   public static int px2sp(Context context, float pxValue) {        
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;        
        return (int) (pxValue / fontScale + 0.5f);
   }    /**
    * 将sp值转换为px值,保证文字大小不变
    *
    * @param spValue
    * @param fontScale
    *            (DisplayMetrics类中属性scaledDensity)
    * @return
    */
   public static int sp2px(Context context, float spValue) {        
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;        
        return (int) (spValue * fontScale + 0.5f);
   }
   }

6drawable转bitmap的工具类

代码语言:javascript
复制
/**
* drawable转bitmap
*
* @param drawable
* @return
*/private Bitmap drawableToBitamp(Drawable drawable) {    
        if (null == drawable) {        
        return null;
       }if (drawable instanceof BitmapDrawable) {
       BitmapDrawable bd = (BitmapDrawable) drawable;        
        return bd.getBitmap();
   }    
        int w = drawable.getIntrinsicWidth();    
        int h = drawable.getIntrinsicHeight();
       Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
       Canvas canvas = new Canvas(bitmap);
       drawable.setBounds(0, 0, w, h);
       drawable.draw(canvas);    
        return bitmap;
}

7文章发布模仿朋友圈时间显示

代码语言:javascript
复制

   public static String ChangeTime(Date time) {
       String ftime = "";
       Calendar cal = Calendar.getInstance();        // 判断是否是同一天
       String curDate = dateFormater2.get().format(cal.getTime());
       String paramDate = dateFormater2.get().format(time);        

   if (curDate.equals(paramDate)) {            

   int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);            

   if (hour == 0)
               ftime = Math.max(
                       (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                       + "分钟前";            

           else
               ftime = hour + "小时前";            

           return ftime;
       }        long lt = time.getTime() / 86400000;        

           long ct = cal.getTimeInMillis() / 86400000;        

           int days = (int) (ct - lt);        

           if (days == 0) {            

           int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);            

           if (hour == 0)
           ftime = Math.max( (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                       + "分钟前";          
            else
               ftime = hour + "小时前";
       } else if (days == 1) {
           ftime = "昨天";
       } else if (days == 2) {
           ftime = "前天 ";
       } else if (days > 2 && days < 31) {
           ftime = days + "天前";
       } else if (days >= 31 && days <= 2 * 31) {
           ftime = "一个月前";
       } else if (days > 2 * 31 && days <= 3 * 31) {
           ftime = "2个月前";
       } else if (days > 3 * 31 && days <= 4 * 31) {
           ftime = "3个月前";
       } else {
           ftime = dateFormater2.get().format(time);
       }        return ftime;
   }    public static String friendly_time(String sdate) {
       Date time = null;        

           if (TimeZoneUtil.isInEasternEightZones())
           time = toDate(sdate);        else
           time = TimeZoneUtil.transformTime(toDate(sdate),
                   TimeZone.getTimeZone("GMT+08"), TimeZone.getDefault());        

           if (time == null) {            

           return "Unknown";
       }
       String ftime = "";
       Calendar cal = Calendar.getInstance();        // 判断是否是同一天
       String curDate = dateFormater2.get().format(cal.getTime());
       String paramDate = dateFormater2.get().format(time);        

           if (curDate.equals(paramDate)) {            

           int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);            

           if (hour == 0)
               ftime = Math.max(
                       (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                       + "分钟前";          
            else
               ftime = hour + "小时前";            

            return ftime;
       }        long lt = time.getTime() / 86400000;        

            long ct = cal.getTimeInMillis() / 86400000;        

            int days = (int) (ct - lt);        

            if (days == 0) {            

            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);            

            if (hour == 0)
               ftime = Math.max(
                       (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                       + "分钟前";           

             else
               ftime = hour + "小时前";
       } else if (days == 1) {
           ftime = "昨天";
       } else if (days == 2) {
           ftime = "前天 ";
       } else if (days > 2 && days < 31) {
           ftime = days + "天前";
       } else if (days >= 31 && days <= 2 * 31) {
           ftime = "一个月前";
       } else if (days > 2 * 31 && days <= 3 * 31) {
           ftime = "2个月前";
       } else if (days > 3 * 31 && days <= 4 * 31) {
           ftime = "3个月前";
       } else {
           ftime = dateFormater2.get().format(time);
       }        return ftime;
   }

8时间格式转换工具类

代码语言:javascript
复制
public static String ConverToString(Date date) {
       DateFormat df = new SimpleDateFormat("yyyy-MM-dd");        
        return df.format(date);
   }    
        public static String ConverToString2(Date date){
       DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");        
        return df.format(date);
   }    
        public static String ConverToString3(Date date){
       DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        
        return df.format(date);
   }

9验证码倒计时工具类

代码语言:javascript
复制
public class TimeCount extends CountDownTimer {    
    private Button button;    /**
    * 到计时
    * @param millisInFuture  到计时多久,毫秒
    * @param countDownInterval 周期
    * @param button   按钮
    */
   public TimeCount(long millisInFuture, long countDownInterval,Button button) {        
    super(millisInFuture, countDownInterval);        
    this.button =button;
   }    
    public TimeCount(long millisInFuture, long countDownInterval) {        
    super(millisInFuture, countDownInterval);
   }    
    @Override
   public void onFinish() {// 计时完毕
       button.setText("获取验证码");
       button.setClickable(true);
       button.setBackground(MyApplication.getContext().getResources().getDrawable(R.drawable.radius14));
   }   
     @Override
   public void onTick(long millisUntilFinished) {// 计时过程
       button.setClickable(false);//防止重复点击
       button.setText(millisUntilFinished / 1000 + "s后重试");
       button.setBackground(MyApplication.getContext().getResources().getDrawable(R.drawable.radius_gray));
   }
}

10屏幕截图工具类

代码语言:javascript
复制
public class ScreenShot {    
public static void shoot(Activity a, File filePath) {        
    if (filePath == null) {            
        return;
       }        
    if (!filePath.getParentFile().exists()) {
           filePath.getParentFile().mkdirs();
       }
       FileOutputStream fos = null;        
    try {
           fos = new FileOutputStream(filePath);            
    if (null != fos) {
               takeScreenShot(a).compress(Bitmap.CompressFormat.PNG, 100, fos);
           }
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } finally {            
    if (fos != null) {                
    try {
                   fos.flush();
                   fos.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
   }    private static Bitmap takeScreenShot(Activity activity) {
       View view = activity.getWindow().getDecorView();
       view.setDrawingCacheEnabled(true);
       view.buildDrawingCache();
       Bitmap bitmap = view.getDrawingCache();
       Rect frame = new Rect();
       activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);        
        int statusBarHeight = frame.top;        
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();        
        int height = activity.getWindowManager().getDefaultDisplay()
               .getHeight();        //去掉标题栏
       Bitmap b = Bitmap.createBitmap(bitmap, 0, statusBarHeight, width,
               height - statusBarHeight);
       view.destroyDrawingCache();        return b;
   }}

总结

如果大家没空一个一个复制黏贴的话,我已经花费时间精力为大家整理成一个文档,大家可以关注公众号【程序IT圈】,后台回复:工具库。获得完整代码。

本文属于原创,如有转载,请标注原作者,版权归本公众号所有。如果你喜欢我写的文章请关注 程序IT圈 ,欢迎大家继续关注本公众号的技术博文。如果您觉得这篇文章对你有所帮助的话,不妨点个赞或给个赞赏哈,您的支持就是我坚持原创的动力~~

最后,如果你想写公众号和热爱编程的朋友们,我建立了个技术微信群,可以公众号回复 "加群" ,欢迎您进群学习哈~

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-10-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员小猿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档