Android 开发常用的工具类(更新ing)

本文汇总了Android开发中常用的工具类,包括View尺寸测量、图片压缩、倒计时功能、缓存清理、Double精确计算、图片保存、网络状态检查、图片路径获取、Retrofit网络请求、软键盘控制、SP数据存储、时间处理、Toast显示等功能,为开发者提供全面的代码参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1.测量View的宽高

 


public static void measureWidthAndHeight(View view) {
    int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    view.measure(widthMeasureSpec, heightMeasureSpec);
}

2.俩种压缩图片的方式 


public static Bitmap pressScaleCompress(Bitmap bitmap) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();  //创建一个字节数组输出流对象
    bitmap.compress(Bitmap.CompressFormat.PNG, 80, os); //通过bitmap中的compress,将图片压缩到os流对象中.
    //其中第二个参数quality,为100表示不压缩,如果为80,表示压缩百分之20.
    byte[] bt = os.toByteArray(); //将流对象转行成数组
    Bitmap bitmap1 = BitmapFactory.decodeByteArray(bt, 0, bt.length); //将字节数组转换成bitmap图片

    return bitmap1;
}

public static Bitmap pressScaleWidthHeightCompress(Bitmap bitmap) {
    Matrix matrix = new Matrix();
    matrix.postScale(0.6f, 0.6f);  //matrix 设置为0.6f 就是对宽高缩放二分之一
    Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

    return bitmap1;
}

3.倒计时工具类

 

private TextView tv;

/** 倒计时 **/
public CountDownUtils(long millisInFuture, long countDownInterval,
      TextView tv) {
   super(millisInFuture, countDownInterval);// 参数依次为�?�时�?,和计时的时间间隔
   // TODO Auto-generated constructor stub
   this.tv = tv;
}

// 计时过程显示
@Override
public void onTick(long millisUntilFinished) {
   // TODO Auto-generated method stub
   tv.setEnabled(false);
   tv.setText("重新获取("+millisUntilFinished / 1000+"s)");
}

// 计时结束 
@Override
public void onFinish() {
   // TODO Auto-generated method stub
   tv.setText("重新验证");
   tv.setEnabled(true);
}

 

 

4.清除缓存工具类

 

 

  /**
     * 需要查下缓存大小
     * @param context
     * @return
     * @throws Exception
     */
    public static String getTotalCacheSize(Context context) throws Exception {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(context.getExternalCacheDir());
        }
        return getFormatSize(cacheSize);
    }

    /**
     * 清空缓存
     * @param context
     */
    public static void clearAllCache(Context context) {
        deleteDir(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteDir(context.getExternalCacheDir());
        }
    }
    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
    /**
     * * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * *
     *
     * @param context
     */
    public static void cleanInternalCache(Context context) {
        deleteFilesByDirectory(context.getCacheDir());
    }

    /**
     * * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * *
     *
     * @param context
     */
    public static void cleanDatabases(Context context) {
        deleteFilesByDirectory(new File("/data/data/"
                + context.getPackageName() + "/databases"));
    }

    /**
     * * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) *
     *
     * @param context
     */
    public static void cleanSharedPreference(Context context) {
        deleteFilesByDirectory(new File("/data/data/"
                + context.getPackageName() + "/shared_prefs"));
    }

    /**
     * * 按名字清除本应用数据库 * *
     *
     * @param context
     * @param dbName
     */
    public static void cleanDatabaseByName(Context context, String dbName) {
        context.deleteDatabase(dbName);
    }

    /**
     * * 清除/data/data/com.xxx.xxx/files下的内容 * *
     *
     * @param context
     */
    public static void cleanFiles(Context context) {
        deleteFilesByDirectory(context.getFilesDir());
    }

    /**
     * * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
     *
     * @param context
     */
    public static void cleanExternalCache(Context context) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalCacheDir());
        }
    }
    /**
     * * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * *
     *
     * @param filePath
     * */
    public static void cleanCustomCache(String filePath) {
        deleteFilesByDirectory(new File(filePath));
    }

    /**
     * * 清除本应用所有的数据 * *
     *
     * @param context
     * @param filepath
     */
    public static void cleanApplicationData(Context context, String... filepath) {
        cleanInternalCache(context);
        cleanExternalCache(context);
        cleanDatabases(context);
        cleanSharedPreference(context);
        cleanFiles(context);
        if (filepath == null) {
            return;
        }
        for (String filePath : filepath) {
            cleanCustomCache(filePath);
        }
    }

    /**
     * * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * *
     *
     * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    // 获取文件
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录,一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 删除指定目录下文件及目录
     *
     * @param deleteThisPath
     * @param filePath
     * @return
     */
    public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 如果下面还有文件
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是文件,删除
                        file.delete();
                    } else {// 目录
                        if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
//        if (kiloByte < 1) {
//            return size + "Byte";
//        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "K";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "M";
        }

        double teraBytes = gigaByte / 1024; 
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "G";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "T";
    }

    public static String getCacheSize(File file) throws Exception {
        return getFormatSize(getFolderSize(file));
    }

 

 

5.Double精确计算工具类

 

/**
 * double的计算不精确,会有类似0.0000000000000002的误差,正确的方法是使用BigDecimal或者用整型
 * 整型地方法适合于货币精度已知的情况,比如12.11+1.10转成1211+110计算,最后再/100即可
 * 以下是摘抄的BigDecimal方法:
 */
private static final long serialVersionUID = -3345205828566485102L;
// 默认除法运算精度
private static final Integer DEF_DIV_SCALE = 2;

/**
 * 提供精确的加法运算。
 *
 * @param value1 被加数
 * @param value2 加数
 * @return 两个参数的和
 */
public static Double add(Double value1, Double value2) {
    BigDecimal b1 = new BigDecimal(Double.toString(value1));
    BigDecimal b2 = new BigDecimal(Double.toString(value2));
    return b1.add(b2).doubleValue();
}

/**
 * 提供精确的减法运算。
 *
 * @param value1 被减数
 * @param value2 减数
 * @return 两个参数的差
 */
public static double sub(Double value1, Double value2) {
    BigDecimal b1 = new BigDecimal(Double.toString(value1));
    BigDecimal b2 = new BigDecimal(Double.toString(value2));
    return b1.subtract(b2).doubleValue();
}

/**
 * 提供精确的乘法运算。
 *
 * @param value1 被乘数
 * @param value2 乘数
 * @return 两个参数的积
 */
public static Double mul(Double value1, Double value2) {
    BigDecimal b1 = new BigDecimal(Double.toString(value1));
    BigDecimal b2 = new BigDecimal(Double.toString(value2));
    return b1.multiply(b2).doubleValue();
}

/**
 * 提供(相对)精确的除法运算,当发生除不尽的情况时, 精确到小数点以后10位,以后的数字四舍五入。
 *
 * @param dividend 被除数
 * @param divisor  除数
 * @return 两个参数的商
 */
public static Double divide(Double dividend, Double divisor) {
    return divide(dividend, divisor, DEF_DIV_SCALE);
}

/**
 * 提供(相对)精确的除法运算。 当发生除不尽的情况时,由scale参数指定精度,以后的数字四舍五入。
 *
 * @param dividend 被除数
 * @param divisor  除数
 * @param scale    表示表示需要精确到小数点以后几位。
 * @return 两个参数的商
 */
public static Double divide(Double dividend, Double divisor, Integer scale) {
    if (scale < 0) {
        throw new IllegalArgumentException("The scale must be a positive integer or zero");
    }
    BigDecimal b1 = new BigDecimal(Double.toString(dividend));
    BigDecimal b2 = new BigDecimal(Double.toString(divisor));
    return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue();
}

/**
 * 提供指定数值的(精确)小数位四舍五入处理。
 *
 * @param value 需要四舍五入的数字
 * @param scale 小数点后保留几位
 * @return 四舍五入后的结果
 */
public static double round(double value, int scale) { 
    if (scale < 0) {
        throw new IllegalArgumentException("The scale must be a positive integer or zero");
    }
    BigDecimal b = new BigDecimal(Double.toString(value));
    BigDecimal one = new BigDecimal("1");
    return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue();
}

public static String getValue(double amout) {

    DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");

    return decimalFormat.format(amout);
}

public static String getValue2(double amout) {

    DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");

    return decimalFormat.format(amout);
}

 

6.图片保存到本地并返回路径

 

/**
 * 将Bitmap 图片保存到本地路径,并返回路径
 * @param fileName 文件名称
 * @param bitmap   图片
 * @param资源类型,参照 MultimediaContentType 枚举,根据此类型,保存时可自动归类
 */
public static String saveFile(Context c, String fileName, Bitmap bitmap) {
    return saveFile(c, "", fileName, bitmap);
}

public static String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) {
    byte[] bytes = bitmapToBytes(bitmap);
    return saveFile(c, filePath, fileName, bytes);
}

public static byte[] bitmapToBytes(Bitmap bm) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(CompressFormat.JPEG, 100, baos);
    return baos.toByteArray();
}

public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) {
    String fileFullName = "";
    FileOutputStream fos = null;
    String dateFolder = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA)
            .format(new Date());
    try {
        String suffix = "";
        if (filePath == null || filePath.trim().length() == 0) {
            filePath = Environment.getExternalStorageDirectory() + "/XiaoCao/" + dateFolder + "/";
        }
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File fullFile = new File(filePath, fileName + suffix);
        fileFullName = fullFile.getPath();
        fos = new FileOutputStream(new File(filePath, fileName + suffix));
        fos.write(bytes);
    } catch (Exception e) {  
        fileFullName = "";
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                fileFullName = "";
            }
        }
    }
    return fileFullName;
}

 

7.杂 看注释

 

   private static int mScreenWidth, mScreenHeight;

    // base64图片转字符串
    public static String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs)
     * context
     */
    public static void cleanSharedPreference(Context context) {
        deleteFilesByDirectory(new File("/data/data/"
                + context.getPackageName() + "/shared_prefs"));
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }
    public static String listToString(ArrayList<String> stringList){
        if (stringList == null) {
            return null;
        }
        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (String string : stringList) {
            if (flag) {
                result.append("|"); // 分隔符
            }else {
                flag=true;
            }
            result.append(string);
        }
        return result.toString();
    }
    /*
    * 时间转时间戳
    * */
    public static String Timetodata(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy年MM月dd日",
                Locale.CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return times;
    }


    public static String getMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return str;
        }
    }

    /*将日期转为时间戳*/
    public static long getStringToDate(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();
    }

    public static String stampToDate(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        long lcc_time = Long.valueOf(time);
        String format = sdf.format(new Date(lcc_time * 1000L));
        return format;
    }

    //  时间戳转为日期  /年/月/日
    public static String getDateToString(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        long lcc_time = Long.valueOf(time);
        String format = sdf.format(new Date(lcc_time * 1000L));
        return format;
    }

    public static String go(Long ttl){
        Date nowTime = new Date(System.currentTimeMillis()+ttl);
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
        return retStrFormatNowDate;
    }

    // 获取当前时间
    public static String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String date = sdf.format(curDate);
        return date;
    }
    // 获取当前时间
    public static String getCurrentDate1() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy,MM");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String date = sdf.format(curDate);
        return date;
    }
    // 获取当前时间
    public static String getCurrentDate2() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy,MM,dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String date = sdf.format(curDate);
        return date;
    }
    //  时间戳转为日期  /年/月/日/时/分
    public static String getDateToStringTime(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        long lcc_time = Long.valueOf(time);
        String format = sdf.format(new Date(lcc_time * 1000L));
        return format;
    }

    //手机号判断逻辑
    public static boolean isMobileNO(String mobiles) {
//        Pattern p = Pattern.compile("^(13[0-9]|14[57]|15[0-35-9]|17[6-8]|18[0-9])[0-9]{8}$");
//        Matcher m = p.matcher(mobiles);
//        return m.matches();
        //上面的验证会有些问题,手机号码格式不是固定的,所以就弄简单点
        if (mobiles.length()==11){
            return true;
        }
        return false;
    }

    //正则6-16位数字或字母
    public static boolean isPswRuleNO(String mobiles) {
        Pattern p = Pattern
                .compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();
    }

    public static int getScreenWidth(Context context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        mScreenWidth = metrics.widthPixels;
        return mScreenWidth;
    }

    public static int getScreenHeight(Context context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        mScreenHeight = metrics.heightPixels;
        return mScreenHeight;
    }

    //启动应用的设置,跳转到应用的设置界面
    public static void startAppSettingsResult(Activity activity) {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + activity.getPackageName()));
        activity.startActivityForResult(intent, 0);
    }

    //得到此设备的设备信息,这里用到的是方便进行友盟的集成测试
    public static String getDeviceInfo(Context context) {
        TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = manager.getDeviceId();
        return deviceId;
    }

    /**
     * 获取当前应用程序的包名
     *
     * @param context 上下文对象
     * @return 返回包名
     */
    public static String getAppPackageName(Context context) {
        //当前应用pid
        int pid = android.os.Process.myPid();
        //任务管理类
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //遍历所有应用
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == pid)//得到当前应用
                return info.processName;//返回包名
        }
        return "";
    }

    /**
     * 获取程序的版本号
     *
     * @param context
     * @return
     */
    public static String getAppVersion(Context context) {
        //包管理操作管理类
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packinfo = pm.getPackageInfo(getAppPackageName(context), 0);
            return packinfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 根据手机的分辨率从 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);
    }


    public static void setMargins (View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

 

8.判断网络工具类

 

/**
 * 判断是否有网络连接
 *
 * @param context
 * @return
 */
public static boolean isNetworkConnected(Context context) {
    if (context != null) {
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // 获取NetworkInfo对象
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        //判断NetworkInfo对象是否为空
        if (networkInfo != null)
            return networkInfo.isAvailable();
    }
    return false;
}

/**
 * 判断WIFI网络是否可用
 *
 * @param context
 * @param context
 * @return
 */
public static boolean isMobileConnected(Context context) {
    if (context != null) {
        //获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //获取NetworkInfo对象
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        //判断NetworkInfo对象是否为空 并且类型是否为MOBILE
        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
            return networkInfo.isAvailable();
    }
    return false;
}

/**
 * 获取当前网络连接的类型信息
 * 原生
 *
 * @param context
 * @return
 */
public static int getConnectedType(Context context) {
    if (context != null) {
        //获取手机所有连接管理对象
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //获取NetworkInfo对象
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            //返回NetworkInfo的类型
            return networkInfo.getType();
        }
    }
    return -1;
}

/**
 * 获取当前的网络状态 :没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2
 * 自定义
 *
 * @param context
 * @return
 */
public static int getAPNType(Context context) {
    //结果返回值
    int netType = 0;
    //获取手机所有连接管理对象
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    //获取NetworkInfo对象
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    //NetworkInfo对象为空 则代表没有网络
    if (networkInfo == null) {
        return netType;
    }
    //否则 NetworkInfo对象不为空 则获取该networkInfo的类型
    int nType = networkInfo.getType();
    if (nType == ConnectivityManager.TYPE_WIFI) {
        //WIFI
        netType = 1;
    } else if (nType == ConnectivityManager.TYPE_MOBILE) {
        int nSubType = networkInfo.getSubtype();
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        //3G   联通的3G为UMTS或HSDPA 电信的3G为EVDO
        if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
                && !telephonyManager.isNetworkRoaming()) {
            netType = 4;
        } else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
                || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
                && !telephonyManager.isNetworkRoaming()) {
            netType = 3;
            //2G 移动和联通的2G为GPRS或EGDE,电信的2G为CDMA
        } else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
                || nSubType == TelephonyManager.NETWORK_TYPE_EDGE
                || nSubType == TelephonyManager.NETWORK_TYPE_CDMA
                && !telephonyManager.isNetworkRoaming()) {
            netType = 2;
        } else {
            netType = 2;
        }
    }
    return netType;
}

/**
 * 判断GPS是否打开
 * ACCESS_FINE_LOCATION权限 
 *
 * @param context
 * @return
 */
public static boolean isGPSEnabled(Context context) {
    //获取手机所有连接LOCATION_SERVICE对象
    LocationManager locationManager = ((LocationManager) context.getSystemService(Context.LOCATION_SERVICE));
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

 

9.根据图片url获取绝对路径

 

/**
 * 根据Uri获取图片的绝对路径
 *
 * @param context 上下文对象
 * @param uri     图片的Uri
 * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
 */
public static String getRealPathFromUri(Context context, Uri uri) {
    int sdkVersion = Build.VERSION.SDK_INT;
    if (sdkVersion >= 19) { // api >= 19
        return getRealPathFromUriAboveApi19(context, uri);
    } else { // api < 19
        return getRealPathFromUriBelowAPI19(context, uri);
    }
}

/**
 * 适配api19以下(不包括api19),根据uri获取图片的绝对路径
 *
 * @param context 上下文对象
 * @param uri     图片的Uri
 * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
 */
private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
    return getDataColumn(context, uri, null, null);
}

/**
 * 适配api19及以上,根据uri获取图片的绝对路径
 *
 * @param context 上下文对象
 * @param uri     图片的Uri
 * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
 */
@SuppressLint("NewApi")
public static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
    String filePath = null;
    if (DocumentsContract.isDocumentUri(context, uri)) {
        // 如果是document类型的 uri, 则通过document id来进行处理
        String documentId = DocumentsContract.getDocumentId(uri);
        if (isMediaDocument(uri)) { // MediaProvider
            // 使用':'分割
            String id = documentId.split(":")[1];

            String selection = MediaStore.Images.Media._ID + "=?";
            String[] selectionArgs = {id};
            filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
        } else if (isDownloadsDocument(uri)) { // DownloadsProvider
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
            filePath = getDataColumn(context, contentUri, null, null);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // 如果是 content 类型的 Uri
        filePath = getDataColumn(context, uri, null, null);
    } else if ("file".equals(uri.getScheme())) {
        // 如果是 file 类型的 Uri,直接获取图片对应的路径
        filePath = uri.getPath();
    }
    return filePath;
}

/**
 * 获取数据库表中的 _data 列,即返回Uri对应的文件路径
 *
 * @return
 */
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    String path = null;

    String[] projection = new String[]{MediaStore.Images.Media.DATA};
    Cursor cursor = null;
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
            path = cursor.getString(columnIndex);
        }
    } catch (Exception e) {
        if (cursor != null) {
            cursor.close();
        }
    }
    return path;  
}

/**
 * @param uri the Uri to check
 * @return Whether the Uri authority is MediaProvider
 */
private static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * @param uri the Uri to check
 * @return Whether the Uri authority is DownloadsProvider
 */
private static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

 

10.网络请求Retrofit工具类

 

 

private static RetrofitManager mRetrofitManager;

private final Retrofit mRetrofit;

private static String BASE_URL = "http://yb.dashuibei.com/index.php/Home/";

public RetrofitManager(String baseUrl) {

    mRetrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(bulidOkHttpClient())
            .build();


}

public static RetrofitManager getDefault() {

    return mRetrofitManager = new RetrofitManager(BASE_URL);

}

private OkHttpClient bulidOkHttpClient() {

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(5000, TimeUnit.MILLISECONDS)
            .writeTimeout(5000, TimeUnit.MILLISECONDS)
            .connectTimeout(5000, TimeUnit.MILLISECONDS)  
            .build();

    return okHttpClient; 
}

public <T> T create(Class<T> Clazz) {

    return mRetrofit.create(Clazz);

}

 需要用到的依赖

    //配置retrofit2.0
    implementation 'com.squareup.retrofit2:retrofit:+'
    implementation 'com.squareup.retrofit2:converter-gson:+'
    //Rxjava2需要依赖
    implementation 'io.reactivex.rxjava2:rxjava:+'
    implementation 'io.reactivex.rxjava2:rxandroid:+'

    //让retrofit支持Rxjava2
    implementation 'com.squareup.retrofit2:adapter-rxjava2:+'

 

11. 好东西自己看

 

/*
* 当点击后或出现倒计时的时候再点击是触发不了点击事件的。
  等倒计时结束显示重新获取验证码的时候可以重新触发点击事件;
* */
private int inFuture;
private int downInterval;
private TextView mTextView;

//发送验证码,开始倒计时
public static void sendSms(TextView view, int normalColor, int afterColor) {
    SendSmsTimerUtils mCountDownTimerUtils = new SendSmsTimerUtils(view, 60000, 1000, normalColor, afterColor);
    mCountDownTimerUtils.start();
}
/**
 * 第一个参数:TextView控件(需要实现倒计时的TextView)
 * 第二个参数:倒计时总时间,以毫秒为单位;
 * 第三个参数:渐变事件,最低1秒,也就是说设置0-1000都是以一秒渐变,设置1000以上改变渐变时间
 * 第四个参数:点击textview之前的字体颜色
 * 第五个参数:点击textview之后的字体颜色
 */
private SendSmsTimerUtils(TextView textView, long millisInFuture, long countDownInterval,
                          int inFuture, int downInterval) {
    /*
    注意这个,super的构造器中millisInFuture是总时间,countDownInterval是间隔时间
    意思就是每隔countDownInterval时间会回调一次方法onTick,然后millisInFuture时间之后会回调onFinish方法。
     */
    super(millisInFuture, countDownInterval);
    this.mTextView = textView;
    this.inFuture = inFuture;
    this.downInterval = downInterval;
}

@Override
public void onTick(long millisUntilFinished) {
    mTextView.setClickable(false);
    mTextView.setText(millisUntilFinished / 1000 + "S");
    int color = MyApplication.getGloableContext().getResources().getColor(downInterval);
    mTextView.setTextColor(color);
    SpannableString spannableString = new SpannableString(mTextView.getText().toString());
    ForegroundColorSpan span = new ForegroundColorSpan(color);
    //设置秒数的颜色
    if (millisUntilFinished / 1000 > 9) {
        spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    } else {
        spannableString.setSpan(span, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    mTextView.setText(spannableString); 
}

@Override
public void onFinish() {
    mTextView.setText("重新发送");
    mTextView.setClickable(true);
    mTextView.setTextColor(MyApplication.getGloableContext().getResources().getColor(R.color.colorAccent));
}

 

12.EdText 关于软键盘

 

/**
 * 为EditText设置弹出软键盘
 *
 * @param view
 */
public static void showSoftKeyboard(View view) {
    InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(view, InputMethodManager.RESULT_SHOWN);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}

//关闭软键盘
public static void closeKeyboard(EditText et) {   
    InputMethodManager imm = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}

//关闭软键盘
public static void closeKeyboard(Activity context) {
    ((InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE))
            .hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
}

 

13.sp 工具类   

 

private static SharedPreferences mSharedPreferences;

public static void putString(Context context, String key, String value){
    mSharedPreferences =  context.getSharedPreferences(Urls.FILENAME, Context.MODE_PRIVATE);
    mSharedPreferences.edit().putString(key,value).commit();
}

public static String getString(Context context, String key, String defValue){
    mSharedPreferences=context.getSharedPreferences(Urls.FILENAME, Context.MODE_PRIVATE);
    return mSharedPreferences.getString(key,defValue);
}

public static void putBoolean(Context context, String key, boolean value){
    mSharedPreferences=context.getSharedPreferences(Urls.FILENAME, Context.MODE_PRIVATE);
    mSharedPreferences.edit().putBoolean(key,value).commit();
}

public static boolean getBoolean(Context context, String key, boolean defValue){
    mSharedPreferences=context.getSharedPreferences(Urls.FILENAME, Context.MODE_PRIVATE);
    return mSharedPreferences.getBoolean(key,defValue);
}

public static void putInt(Context context, String key, int value){
    mSharedPreferences=context.getSharedPreferences(Urls.FILENAME, Context.MODE_PRIVATE);
    mSharedPreferences.edit().putInt(key,value).commit();
}

public static int getInt(Context context, String key, int defValue){
    mSharedPreferences=context.getSharedPreferences(Urls.FILENAME, Context.MODE_PRIVATE);
    return mSharedPreferences.getInt(key,defValue);
}

14.关于时间

 

 

//把时间戳转换为毫秒
public static String dateTimeMs(String str){
   SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
   long msTime = -1;
   try {
      msTime=simpleDateFormat.parse(str).getTime();
   } catch (ParseException e) {
      e.printStackTrace();
   }

   return String.valueOf(msTime);

}

public static Date getData(String cc_time){
   long data_time = Long.valueOf(cc_time);
   Date date = new Date(data_time * 1000L);
   return date;
}

/**
 * 获取两个日期之间的间隔天数
 * @return
 */
public static int getGapCount(Date startDate, Date endDate) {
   Calendar fromCalendar = Calendar.getInstance();
   fromCalendar.setTime(startDate);
   fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
   fromCalendar.set(Calendar.MINUTE, 0);
   fromCalendar.set(Calendar.SECOND, 0);
   fromCalendar.set(Calendar.MILLISECOND, 0);

   Calendar toCalendar = Calendar.getInstance();
   toCalendar.setTime(endDate);
   toCalendar.set(Calendar.HOUR_OF_DAY, 0);
   toCalendar.set(Calendar.MINUTE, 0);
   toCalendar.set(Calendar.SECOND, 0);
   toCalendar.set(Calendar.MILLISECOND, 0);

   return (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
}

/**
 * MD5加密
 */
public static String md5(String inputStr) {
   String md5Str = inputStr;
   if (inputStr != null) {
      MessageDigest md = null;
      try {
         md = MessageDigest.getInstance("MD5");
      } catch (NoSuchAlgorithmException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      md.update(inputStr.getBytes());
      BigInteger hash = new BigInteger(1, md.digest());
      md5Str = hash.toString(16);
      if ((md5Str.length() % 2) != 0) {
         md5Str = "0" + md5Str;
      }
   }
   return md5Str;
}

/**
 * 时间戳转换为几天前
 * 
 * @param timeStr
 */
public static String getStandardDate(String timeStr) {

   StringBuffer sb = new StringBuffer();

   long t = Long.parseLong(timeStr);
   long time = System.currentTimeMillis() - (t * 1000);
   long mill = (long) Math.ceil(time / 1000);// 秒前

   long minute = (long) Math.ceil(time / 60 / 1000.0f);// 分钟前

   long hour = (long) Math.ceil(time / 60 / 60 / 1000.0f);// 小时

   long day = (long) Math.ceil(time / 24 / 60 / 60 / 1000.0f);// 天前

   if (day - 1 > 0) {
      sb.append(day + "天");
   } else if (hour - 1 > 0) {
      if (hour >= 24) {
         sb.append("1天");
      } else {
         sb.append(hour + "小时");
      }
   } else if (minute - 1 > 0) {
      if (minute == 60) {
         sb.append("1小时");
      } else {
         sb.append(minute + "分钟");
      }
   } else if (mill - 1 > 0) {
      if (mill == 60) {
         sb.append("1分钟");
      } else {
         sb.append(mill + "秒");
      }
   } else {
      sb.append("刚刚");
   }
   if (!sb.toString().equals("刚刚")) {
      sb.append("前");
   }
   return sb.toString();
}

/**
 * 时间戳转换为时间
 * 
 * @param cc_time
 * @return
 */
public static String getStrTimeYMD(String cc_time) {
   String re_StrTime = null;
   // SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   long lcc_time = Long.valueOf(cc_time);
   re_StrTime = sdf.format(new Date(lcc_time * 1000L));

   return re_StrTime;
}

public static String getStrTimeYMD2(String cc_time) {
   String re_StrTime = null;
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
   long lcc_time = Long.valueOf(cc_time);
   re_StrTime = sdf.format(new Date(lcc_time * 1000L));

   return re_StrTime;
}

public static String getStrTimeMonth(String cc_time) {
   String re_StrTime = null;
   SimpleDateFormat sdf = new SimpleDateFormat("MM月");
   long lcc_time = Long.valueOf(cc_time);
   re_StrTime = sdf.format(new Date(lcc_time * 1000L));

   return re_StrTime;
}

public static String getStrTimeDay(String cc_time) {
   String re_StrTime = null;
   SimpleDateFormat sdf = new SimpleDateFormat("dd");
   long lcc_time = Long.valueOf(cc_time);
   re_StrTime = sdf.format(new Date(lcc_time * 1000L));

   return re_StrTime;
}

public static String getStrTimeMonthDay(String cc_time) {
   String re_StrTime = null;
   SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
   long lcc_time = Long.valueOf(cc_time);
   re_StrTime = sdf.format(new Date(lcc_time * 1000L));

   return re_StrTime;
}

public static String getStrTimeMonthDaySF(String cc_time) {
   String re_StrTime = null;
   SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
   long lcc_time = Long.valueOf(cc_time);
   re_StrTime = sdf.format(new Date(lcc_time * 1000L));

   return re_StrTime;
}

public static String getStrTimeMonthDay2(String cc_time) {
   String re_StrTime = null;
   SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
   long lcc_time = Long.valueOf(cc_time);
   re_StrTime = sdf.format(new Date(lcc_time * 1000L));

   return re_StrTime;
}

public static String getStrTime(String cc_time) {
   String re_StrTime = null;
   SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
   long lcc_time = Long.valueOf(cc_time);
   re_StrTime = sdf.format(new Date(lcc_time * 1000L));

   return re_StrTime;
}

/**
 * 获取当前时间
 */
public static String getNowTime() {
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
   Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
   String str = formatter.format(curDate);
   return str;
}

/**
 * 获取当前时间
 */
public static String getNowTime1() {
   SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
   Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
   String str = formatter.format(curDate);
   return str;
}

public static Date getNowDate(){
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
   Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
   return curDate;
}

/**
 * 计算跟当前时间的时间差
 */
public static String CountTime(String end) {
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
   long days = 0;

   try {
      Date d1 = df.parse(getNowTime());
      Date d2 = df.parse(getStrTimeYMD(end));
      long diff = d1.getTime() - d2.getTime();// 这样得到的差值是微秒级别

      days = diff / (1000 * 60 * 60 * 24);
      // long hours = (diff - days * (1000 * 60 * 60 * 24))
      // / (1000 * 60 * 60);
      // long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours
      // * (1000 * 60 * 60))
      // / (1000 * 60);
   } catch (Exception e) {
   }
   return String.valueOf(days);  
}

/**
 * date转Sting
 */
public static String ConverToString(Date date) {
   DateFormat df = new SimpleDateFormat("d");// 日 01 变成 1
   return df.format(date);
}

public static String ConverToString2(Date date) {
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//
   return df.format(date);
}

/**
 * 把字符串转为日期
 */
public static Date ConverToDate(String strDate) throws Exception {
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
   return df.parse(strDate);
}

 

15.Toast工具类

 

private TUtils() {
   /* cannot be instantiated */
   throw new UnsupportedOperationException("cannot be instantiated");
}

public static boolean isShow = true;

/**
 * 短时间显示Toast
 * 
 * @param context
 * @param message
 */
public static void showShort(Context context, CharSequence message) {
   if (isShow)
      Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}

/**
 * 短时间显示Toast
 * 
 * @param context
 * @param message
 */
public static void showShort(Context context, int message) {
   if (isShow)
      Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}

/**
 * 长时间显示Toast
 * 
 * @param context
 * @param message
 */
public static void showLong(Context context, CharSequence message) {
   if (isShow)
      Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}

/**
 * 长时间显示Toast
 * 
 * @param context
 * @param message
 */
public static void showLong(Context context, int message) {
   if (isShow)
      Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}

/**
 * 自定义显示Toast时间
 * 
 * @param context
 * @param message
 * @param duration
 */
public static void show(Context context, CharSequence message, int duration) {
   if (isShow)
      Toast.makeText(context, message, duration).show();
}

/**
 * 自定义显示Toast时间    
 * 
 * @param context
 * @param message
 * @param duration
 */
public static void show(Context context, int message, int duration) {
   if (isShow)
      Toast.makeText(context, message, duration).show();
}

public static void showCustom(Context context, String message) {
   if (isShow)
      Toast.makeText(context, message, Toast.LENGTH_SHORT).show();    
}

 

上面的代码都可以cv 欢迎大家来搬  

 

希望对您有所帮助

 

 

                                  欢迎您入群讨论更多Android技术

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值