各种输入校验工具类

public class CommonUtil {

    /**
     * 电话号码验证
     *
     * @param phoneNum
     * @return
     */
    public static boolean isPhoneNum(String phoneNum) {
        Pattern p = Pattern.compile("^((1[0-9])|(1[0-9])|(1[0-9])|(1[0-9]))\\d{9}$");
        Matcher m = p.matcher(phoneNum);
        return m.matches();
    }

    /**
     * 电子邮件验证
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
//        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

        String str = "^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,2})";

        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 第一位是否为零
     *
     * @param numString
     * @return
     */
    public static boolean isZero(String numString) {
        String str = "[0](\\s|\\S)*";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(numString);
        return m.matches();
    }

    //银行卡校验
    public static String isBankNo(String bankno) {
        String SUCCESS = "true";
        String BAD_LENGTH = "银行卡号长度必须在16到19之间";
        String NOT_NUMBER = "银行卡必须全部为数字";
        String ILLEGAL_NUMBER = "银行卡不符合规则";

        if (bankno.length() < 16 || bankno.length() > 19) {
            return BAD_LENGTH;
        }


        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher match = pattern.matcher(bankno);
        if (match.matches() == false) {
            return NOT_NUMBER;
        }


// if (strBin.indexOf(bankno.substring(0, 2)) == -1) {
// return "银行卡号开头6位不符合规范";
// }


        int lastNum = Integer.parseInt(bankno.substring(bankno.length() - 1,
                bankno.length()));// 取出最后一位(与luhm进行比较)


        String first15Num = bankno.substring(0, bankno.length() - 1);// 前15或18位
// System.out.println(first15Num);
        char[] newArr = new char[first15Num.length()]; // 倒叙装入newArr
        char[] tempArr = first15Num.toCharArray();
        for (int i = 0; i < tempArr.length; i++) {
            newArr[tempArr.length - 1 - i] = tempArr[i];
        }
// System.out.println(newArr);


        int[] arrSingleNum = new int[newArr.length]; // 奇数位*2的积 <9
        int[] arrSingleNum2 = new int[newArr.length];// 奇数位*2的积 >9
        int[] arrDoubleNum = new int[newArr.length]; // 偶数位数组


        for (int j = 0; j < newArr.length; j++) {
            if ((j + 1) % 2 == 1) {// 奇数位
                if ((int) (newArr[j] - 48) * 2 < 9)
                    arrSingleNum[j] = (int) (newArr[j] - 48) * 2;
                else
                    arrSingleNum2[j] = (int) (newArr[j] - 48) * 2;
            } else
// 偶数位
                arrDoubleNum[j] = (int) (newArr[j] - 48);
        }


        int[] arrSingleNumChild = new int[newArr.length]; // 奇数位*2 >9
// 的分割之后的数组个位数
        int[] arrSingleNum2Child = new int[newArr.length];// 奇数位*2 >9
// 的分割之后的数组十位数


        for (int h = 0; h < arrSingleNum2.length; h++) {
            arrSingleNumChild[h] = (arrSingleNum2[h]) % 10;
            arrSingleNum2Child[h] = (arrSingleNum2[h]) / 10;
        }


        int sumSingleNum = 0; // 奇数位*2 < 9 的数组之和
        int sumDoubleNum = 0; // 偶数位数组之和
        int sumSingleNumChild = 0; // 奇数位*2 >9 的分割之后的数组个位数之和
        int sumSingleNum2Child = 0; // 奇数位*2 >9 的分割之后的数组十位数之和
        int sumTotal = 0;
        for (int m = 0; m < arrSingleNum.length; m++) {
            sumSingleNum = sumSingleNum + arrSingleNum[m];
        }


        for (int n = 0; n < arrDoubleNum.length; n++) {
            sumDoubleNum = sumDoubleNum + arrDoubleNum[n];
        }


        for (int p = 0; p < arrSingleNumChild.length; p++) {
            sumSingleNumChild = sumSingleNumChild + arrSingleNumChild[p];
            sumSingleNum2Child = sumSingleNum2Child + arrSingleNum2Child[p];
        }


        sumTotal = sumSingleNum + sumDoubleNum + sumSingleNumChild
                + sumSingleNum2Child;


// 计算Luhm值
        int k = sumTotal % 10 == 0 ? 10 : sumTotal % 10;
        int luhm = 10 - k;


        if (lastNum == luhm) {
            return SUCCESS;// 验证通过
        } else {
            return ILLEGAL_NUMBER;
        }
    }

    //金额格式化
    public static String formatMoney(String money) {
        if (TextUtils.isEmpty(money)) return "0";
        NumberFormat nf = new DecimalFormat("###,###,###");
        BigDecimal bigDecimal = new BigDecimal(money);
        return nf.format(bigDecimal);
    }

    //金额格式化
    public static String formatMoneyPoint(String money) {
        if (TextUtils.isEmpty(money)) return "0";
        if (money.indexOf(".") > 0) {
            money = money.replaceAll("0+?$", "");
            money = money.replaceAll("[.]$", "");
        }
        return money;
    }

    public static boolean isWaybillID(String waybill) {
        String str = "([a-zA-Z0-9]+)";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(waybill);
        return m.matches();
    }

    public static boolean isPostcode(String postcode) {
        String format = "\\p{Digit}{6}";
        return postcode.matches(format);
    }

    public static int[] getScreenSize(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        int[] size = {dm.widthPixels, dm.heightPixels};
        return size;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }


    public static void galleryAddPic(Context context, String path) {
        Intent mediaScanIntent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(path);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }

    //把字符串转为长整型
    public static long convertStringToLong(String value) {
        if (value == null || "".equals(value)) return 0;
        try {
            return Long.valueOf(value);
        } catch (Exception ex) {
            ex.printStackTrace();
            return 0;
        }
    }

    public static long trimAndConvert(String value) {
        if (value == null || "".equals(value)) return 0;
        try {
            value = value.replace("¥", "");
            value = value.replace(",", "");
            return Long.valueOf(value);
        } catch (Exception ex) {
            ex.printStackTrace();
            return 0;
        }
    }

    /**
     * 去掉空格
     *
     * @param value
     * @return
     */
    public static String trim(String value) {
        return value == null ? "" : value.trim();
    }

    /**
     * 验证手机号
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        String telRegex = "[1][34758]\\d{9}";
        if (TextUtils.isEmpty(mobiles))
            return false;
        else
            return mobiles.matches(telRegex);
    }


    //去掉空格
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
            dest = dest.trim();
        }
        return dest;
    }

    public static int computeSampleSize(BitmapFactory.Options options,
                                        int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    /**
     * 判断服务是否正在运行
     *
     * @return
     */
    public static boolean isServiceRunning(Context context, String name) {

        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager
                .getRunningServices(Integer.MAX_VALUE)) {
            if (name.equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    public static boolean isHome(Context context) {
        String packageName = context.getPackageName();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = activityManager.getRunningTasks(1);
        if (list.size() > 0) {
            if (packageName.equals(list.get(0).topActivity.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public static String getTopActivity(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        String className = list.get(0).topActivity.getClassName();
        return className.substring(className.lastIndexOf(".") + 1);
    }

    public static Bitmap getNetPicture(String path) {
        Bitmap bitmap = null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
        } catch (Exception ignored) {
        }
        return bitmap;
    }

    public static void storeImage(Bitmap image, File pictureFile) {
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void storeImage(Bitmap image, File pictureFile, int compress) {
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.JPEG, compress, fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String transformToData(long second) {
        Date date = new Date(second);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public static String transformToTime(long second) {
        Date date = new Date(second);
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        return format.format(date);
    }

    public static String transformToHm(long second) {
        Date date = new Date(second);
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    public static long transformToSecond(String data, String format) {
        SimpleDateFormat tmpFormat = new SimpleDateFormat(format);
        long second = 0;
        try {
            second = tmpFormat.parse(data).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return second;
    }

    public static String transformToDataTime(long second) {
        Date date = new Date(second);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }

    public static String transformToDate(long second) {
        Date date = new Date(second);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    public static String transformToMd(long second) {
        Date date = new Date(second);
        SimpleDateFormat format = new SimpleDateFormat("MM月dd日");
        return format.format(date);
    }

    //加减天数
    public static String calculateDate(long time, int d) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE) - d);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d");
        return format.format(calendar.getTime());
    }

    public static String calculateDate(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-M—d");
        return format.format(calendar.getTime());
    }

    public static long calculateLongDate(long time, int d) {
        Date date = new Date(time);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE) - d);
        return calendar.getTimeInMillis();
    }

    public static String getUseDays(long start, long stop) {
        int hour = (int) ((stop - start) / 3600000);
        StringBuilder sBuffer = new StringBuilder();
        if (hour > 24) {
            sBuffer.append(hour / 24).append("天");
        }
        sBuffer.append(hour % 24).append("小时");
        return sBuffer.toString();
    }

    //离结束还有多长时间
    public static String getInterval(long start, long stop) {
        StringBuilder sBuffer = new StringBuilder();
        //时
        int hour = (int) ((stop - start) / 3600000);
        /*if (hour > 24) {
            sBuffer.append(hour / 24 + "天");
        }*/
        if (hour < 10)
            sBuffer.append("0").append(hour);
        else
            sBuffer.append(hour);
        //分
        int minute = (int) ((stop - start) % (3600000 / 60));
        if (minute < 10)
            sBuffer.append("0").append(minute);
        else
            sBuffer.append(minute);
        //秒
        int second = (int) ((stop - start) % (3600000 / 60 / 60));
        if (second < 10)
            sBuffer.append("0").append(second);
        else
            sBuffer.append(second);
        return sBuffer.toString();
    }

    public static String getInterval(long interval) {
        StringBuilder sBuffer = new StringBuilder();
        //时
        int hour = (int) (interval / 3600000);
       /* if (hour > 24) {
            sBuffer.append(hour / 24 + "天");
        }*/
        if (hour < 10)
            sBuffer.append("0").append(hour);
        else
            sBuffer.append(hour);
        //分
        int minute = (int) (interval / (3600000 / 60));
        minute = minute % 60;
        if (minute < 10)
            sBuffer.append("0").append(minute);
        else
            sBuffer.append(minute);
        //秒
        int second = (int) (interval % (3600000 / 60 / 60));
        second = second % 60;
        if (second < 10)
            sBuffer.append("0").append(second);
        else
            sBuffer.append(second);
        return sBuffer.toString();
    }

    public static long[] getTimes(long interval) {
        long[] times = new long[3];
        //时
        int hour = (int) (interval / 3600);
        times[0] = hour;
        //分
        int minute = (int) (interval / 60);
        minute = minute % 60;
        times[1] = minute;
        //秒
        int second = (int) interval % 60;
        times[2] = second;
        return times;
    }

    /**
     * 读取图片资源
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * dip转为px
     */
    public static int parseDip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px转为dip
     */
    public static int parsePx2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 格式化时间(输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间)
     *
     * @param time 传进来的时间毫秒数 使用"yyyy-MM-dd HH:mm:ss"格式
     * @return time为null,或者时间格式不匹配,输出空字符""
     */
    public static String formatDisplayTime(Long time) {
        String display = ""; // 要显示的文字
        int tMin = 60 * 1000; // 1分钟的毫秒数
        int tHour = 60 * tMin; // 一个小时的毫秒数
        int tDay = 24 * tHour; // 一天的毫秒数
        if (time != 0) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 最终显示的格式类型
                SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
                Date tDate = new Date(time); // 传进来的时间的Date
                long tMill = tDate.getTime(); //传进来的时间的 毫秒
                Date today = new Date(); // 当前时间的Date
                SimpleDateFormat sdfToday = new SimpleDateFormat("yyyy-MM-dd");//根据当前时间的Date得到今日0点的毫秒数
                long todayMill = sdfToday.parse(sdfToday.format(today)).getTime();
                if (tMill - todayMill >= 0) {
                    //今天
                    display = "今天" + sdf1.format(tDate);
                } else if ((tMill - todayMill < 0) && ((tMill - todayMill) >= (todayMill - tDay))) {
                    //昨天
                    display = "昨天" + sdf1.format(tDate);
                } else {
                    //其他
                    display = sdf.format(tDate);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return display;
    }

    /**
     * 格式化时间(输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间)
     *
     * @param time 传进来的时间毫秒数 使用"yyyy-MM-dd HH:mm:ss"格式
     * @return time为null,或者时间格式不匹配,输出空字符""
     */
    public static String formatDisplayTimeToMyNews(Long time) {
        String display = ""; // 要显示的文字
        int tMin = 60 * 1000; // 1分钟的毫秒数
        int tHour = 60 * tMin; // 一个小时的毫秒数
        int tDay = 24 * tHour; // 一天的毫秒数
        if (time != 0) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd"); // 最终显示的格式类型
                SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
                Date tDate = new Date(time); // 传进来的时间的Date
                long tMill = tDate.getTime(); //传进来的时间的 毫秒
                Date today = new Date(); // 当前时间的Date
                SimpleDateFormat sdfToday = new SimpleDateFormat("yyyy-MM-dd");//根据当前时间的Date得到今日0点的毫秒数
                long todayMill = sdfToday.parse(sdfToday.format(today)).getTime();
                if (tMill - todayMill >= 0) {
                    //今天
                    //  display = "今天" + sdf1.format(tDate);
                    display = sdf1.format(tDate);
                } else if ((tMill - todayMill < 0) && ((tMill - todayMill) >= (todayMill - tDay))) {
                    //昨天
                    //  display = "昨天" + sdf1.format(tDate);
                    display = "昨天";
                } else {
                    //其他
                    display = sdf.format(tDate);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return display;
    }

    /**
     * 得到版本名称
     *
     * @param context
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            /*verName = context.getPackageManager().getPackageInfo(
                    "com.luxji.auxtion", 0).versionName;*/
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            verName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("test", e.getMessage());
        }
        return verName;
    }

    /**
     * 得到版本编号
     *
     * @param context
     * @return
     */
    public static float getVerCode(Context context) {
        float verCode = 0;
        try {
            /*verCode = context.getPackageManager().getPackageInfo(
                    "com.luxji.auxtion", 0).versionCode;*/
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            verCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("test", e.getMessage());
        }
        return verCode;
    }

    /**
     * 设备id
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        String idString = "";
        try {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            idString = tm.getDeviceId();
            if (TextUtils.isEmpty(tm.getDeviceId())) {
                idString = "";
            }
        } catch (Exception ignored) {
        }
        return idString;
    }

    /**
     * 文件大小
     *
     * @param
     * @return
     * @throws Exception
     */

    @SuppressWarnings("resource")
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
        }
        return size;
    }

    /**
     * 文件夹大小
     *
     * @param file Fileʵ��
     * @return long
     */
    public static long getFolderSize(File file) {
        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/1048576;
        return size;
    }

    /**
     * 文件大小
     *
     * @param length
     * @return
     */
    public static String formatFileSize(long length) {
        String result = null;
        int sub_string = 0;
        if (length >= 1073741824) {
            sub_string = String.valueOf((float) length / 1073741824).indexOf(
                    ".");
            result = ((float) length / 1073741824 + "000").substring(0,
                    sub_string + 3) + "GB";
        } else if (length >= 1048576) {
            sub_string = String.valueOf((float) length / 1048576).indexOf(".");
            result = ((float) length / 1048576 + "000").substring(0,
                    sub_string + 3) + "MB";
        } else if (length >= 1024) {
            sub_string = String.valueOf((float) length / 1024).indexOf(".");
            result = ((float) length / 1024 + "000").substring(0,
                    sub_string + 3) + "KB";
        } else if (length < 1024)
            result = Long.toString(length) + "B";
        return result;
    }

    /**
     * 缓存大小
     *
     * @param context
     * @param cache1
     * @return
     */
    public static String getCacheSize(Context context, File cache1) {
        long cacheSize = 0;
        File cache2 = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            cache2 = new File(context.getExternalCacheDir(), "");
        }
        if (cache2 != null) {
            cacheSize = getFolderSize(cache1) + getFolderSize(cache2);
        } else {
            cacheSize = getFolderSize(cache1);
        }
        return formatFileSize(cacheSize);
    }


    public static void cleanCustomCache(String filePath) {
        deleteFilesByDirectory(new File(filePath));
    }

    public static void cleanApplicationData(Context context, String... filepath) {
        for (String filePath : filepath) {
            cleanCustomCache(filePath);
        }
    }

    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    public static String convertNullToZero(String s) {
        if (TextUtils.isEmpty(s)) return "0";
        else return s.trim();
    }

    public static long convertNullToZero(Long lng) {
        if (lng == null) return 0;
        else return lng;
    }

    public static int convertNullToInt(String s) {
        if (TextUtils.isEmpty(s)) return 0;
        else return Integer.valueOf(s);
    }

    public static BigDecimal convertNullToZero(BigDecimal bigDecimal) {
        if (bigDecimal == null) return BigDecimal.valueOf(0);
        return bigDecimal;
    }

    public static String removeDecimal(String s) {
        if (TextUtils.isEmpty(s)) return "0";
        else
            return s.replace(".00", "");
    }

    public static void releaseImageViewResouce(ImageView imageView) {
        if (imageView == null) return;
        Drawable drawable = imageView.getDrawable();
        if (drawable != null && drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
                System.gc();
            }
        }
    }

    public static void releaseImageViewResouce(FrameLayout view) {
        if (view == null) return;
        Drawable drawable = view.getBackground();
        if (drawable != null && drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
                System.gc();
            }
        }
    }

    public static String getAbsoluteImagePath(Context context, Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri,
                proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }

    private static boolean isFastMobileNetwork(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        switch (telephonyManager.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            case TelephonyManager.NETWORK_TYPE_EHRPD:
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return false; // ~25 kbps
            case TelephonyManager.NETWORK_TYPE_LTE:
                return true; // ~ 10+ Mbps
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                return false;
            default:
                return false;
        }
    }

    public static String addSpace(String str) {
        if (str != null && !str.equals("") && str.length() != 4) {
            StringBuffer strBuffer = new StringBuffer();
            String[] s1 = str.split("");
            for (int i = 0; i < s1.length; i++) {
                if (s1.length == 3) {
                    if (i == 1) {
                        strBuffer.append(s1[i]);
                        strBuffer.append("\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0");
                    } else {
                        strBuffer.append(s1[i]);
                    }

                } else if (s1.length == 4) {
                    if (i != 3 && i != 0) {
                        strBuffer.append(s1[i]);
                        strBuffer.append("\u00A0\u00A0");
                    } else {
                        strBuffer.append(s1[i]);
                    }
                }
            }
            return strBuffer.toString();
        } else {
            return str;
        }

    }

    /**
     * 字符串金额的加法运算
     *
     * @param addend1
     * @param addend2
     * @return
     */
    public static String add(String addend1, String addend2) {
        if (addend1 == null || addend2 == null) {
            return "0";
        }
        BigDecimal bd1 = null;
        BigDecimal bd2 = null;
        try {
            bd1 = new BigDecimal(addend1);
            bd2 = new BigDecimal(addend2);
        } catch (NumberFormatException e) {
            return "0";
        }

        return bd1.add(bd2).toString();
    }

    /**
     * 字符串金额的减法运算
     *
     * @param addend1
     * @param addend2
     * @return
     */
    public static String subtract(String addend1, String addend2) {
        if (TextUtils.isEmpty(addend1) || TextUtils.isEmpty(addend2)) {
            throw new RuntimeException("参数不能有空值!");
        }
        BigDecimal bd1 = null;
        BigDecimal bd2 = null;
        try {
            bd1 = new BigDecimal(addend1);
            bd2 = new BigDecimal(addend2);
        } catch (NumberFormatException e) {
            return "0";
        }

        return bd1.subtract(bd2).toString();
    }

    /**
     * 比较大小
     *
     * @param comp1
     * @param comp2
     * @return
     */
    public static int compare(String comp1, String comp2) {
        if (comp1 == null || comp2 == null) {
            throw new RuntimeException("两个参数均不能为空!");
        }
        BigDecimal bd1 = null;
        BigDecimal bd2 = null;
        try {
            bd1 = new BigDecimal(comp1);
            bd2 = new BigDecimal(comp2);
        } catch (NumberFormatException e) {
            throw new RuntimeException("参数格式不对!");
        }

        return bd1.compareTo(bd2);
    }

    public static String getCurDate() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * 如果string金额值小于0
     */
    public static boolean isNegMoney(String money) {
        if (TextUtils.isEmpty(money)) {
            throw new RuntimeException("参数不能有空值!");
        }
        BigDecimal bd1 = new BigDecimal(money);
        if (bd1.compareTo(new BigDecimal(0)) < 0) {
            return true;
        }
        return false;
    }

    /**
     * 传入的金额是否等于0
     *
     * @param money
     * @return
     */
    public static boolean isEqualZero(String money) {
        if (TextUtils.isEmpty(money)) {
            throw new RuntimeException("参数不能有空值!");
        }
        BigDecimal bd1 = new BigDecimal(money);
        if (bd1.compareTo(new BigDecimal(0)) == 0) {
            return true;
        }
        return false;
    }


    /**
     * 起Activity
     *
     * @param mContext
     * @param mclass
     * @param FLAG_ACTIVITY
     * @param mBundle
     */
    public static void startActivity(Context mContext, Class<?> mclass, int FLAG_ACTIVITY, Bundle mBundle) {
        Intent mIntent = new Intent();
        mIntent.setClass(mContext, mclass);
        if (mBundle != null)
            mIntent.putExtras(mBundle);
        if (FLAG_ACTIVITY != -1)
            mIntent.setFlags(FLAG_ACTIVITY);// Intent.FLAG_ACTIVITY_NEW_TASK
        mContext.startActivity(mIntent);
    }

    /**
     * 起Activity
     *
     * @param mContext
     * @param mclass
     * @param FLAG_ACTIVITY
     */
    public static void startActivity(Context mContext, Class<?> mclass, int FLAG_ACTIVITY) {
        Intent mIntent = new Intent();
        mIntent.setClass(mContext, mclass);
        if (FLAG_ACTIVITY != -1)
            mIntent.setFlags(FLAG_ACTIVITY);// Intent.FLAG_ACTIVITY_NEW_TASK
        mContext.startActivity(mIntent);
    }


    /**
     * 区号+座机号码+分机号码
     *
     * @param fixedPhone
     * @return
     */
    public static boolean isFixedPhone(String fixedPhone) {
        String reg = "(?:(\\(\\+?86\\))(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)|" +
                "(?:(86-?)?(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)";
        return Pattern.matches(reg, fixedPhone);
    }

//    /**
//     *
//     * @param fixedPhone
//     * @return
//     */
//    public static boolean isChinese(String fixedPhone){
//        String reg=("[\u4e00-\u9fa5]");
//        return Pattern.matches(reg, fixedPhone);
//    }

    /**
     * 判断是否含有中文
     *
     * @param str
     * @return
     */
    public static boolean isCN(String str) {
        try {
            byte[] bytes = str.getBytes("UTF-8");
            if (bytes.length == str.length()) {
                return false;
            } else {
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断是否含有表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { // 如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }


    public static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }


    /**
     * 密码大于6位
     *
     * @param password
     * @return
     */
    public static boolean isPasswordValid(String password) {
        if (password.length() < 6) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * 根据路径获得图片并压缩,返回bitmap用于显示
     *
     * @param filePath
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    /* 获取本应用的包名 */
    public static String getAppPackageName() {
        String packageName = null;
        try {
            PackageManager pManager = BaseApplication.getInstance().getPackageManager();
            PackageInfo pInfo = pManager.getPackageInfo(BaseApplication.getInstance().getPackageName(), 0);
            packageName = pInfo.packageName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageName;
    }

    /**
     * 获得文字输入的字节数
     *
     * @param inputStr
     * @return
     */

    public static String getLimitSubstring(String inputStr, int tempLength) {
        int orignLen = inputStr.length();
        int resultLen = 0;
        String temp = null;
        for (int i = 0; i < orignLen; i++) {
            temp = inputStr.substring(i, i + 1);
            try {// 3 bytes to indicate chinese word,1 byte to indicate english
                // word ,in utf-8 encode
                if (temp.getBytes("utf-8").length == 3) {
                    resultLen += 2;
                } else {
                    resultLen++;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (resultLen > tempLength) {
                return inputStr.substring(0, i);
            }
        }
        return inputStr;
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }
        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();
    }

    /**
     * 用于获取状态栏的高度。 使用Resource对象获取(推荐这种方式)
     * @return 返回状态栏高度的像素值。
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值