ToolUtils.java 6.62 KB
package com.glsx.commonres.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.glsx.commonres.CommonResApp;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("unchecked")
public class ToolUtils {

    private static Pattern p = Pattern.compile("^(1[0-9])\\d{9}$");

    /**
     * 获取当前版本
     *
     * @return 版本号
     */
    public static String getVersionCode() {
        try {
            PackageManager manager = CommonResApp.getContext().getPackageManager();
            PackageInfo info = manager.getPackageInfo(CommonResApp.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取应用数据目录下files路径
     *
     * @return
     */
    public static String getDataPath() {
        File file = CommonResApp.getContext().getFilesDir();
        return file.getAbsolutePath();
    }

    /**
     * 判断字符串是否为空
     *
     * @param src 字符串
     * @return true/false
     */
    public static boolean isEmpty(String src) {
        boolean result = true;
        if (src != null && src.length() > 0) {
            for (int i = 0; i < src.length(); i++) {
                char c = src.charAt(i);
                if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                    result = false;
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 手机号码验证
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        boolean flag = false;
        if (mobiles != null && !"".equals(mobiles) && mobiles.length() == 11) {
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        }
        return flag;
    }

    public static boolean checkNickNameLength(String nickName) {
        if (!TextUtils.isEmpty(nickName)
                && (nickName.length() < 2 || nickName.length() > 12)) {
            return false;
        }
        return true;
    }

    /**
     * Description:将versionName变成整形 的versionCode
     *
     * @param versionName
     * @return
     * @author 李满 2014-7-3
     */
    @SuppressLint("DefaultLocale")
    public static int getAppCode(String versionName) {
        if (!isEmpty(versionName)) {
            String[] nList = versionName.replace(".", "-").split("-");
            if (nList.length < 4) {
                return 0;
            }
            String versionCodeStr = String.format("%1$d%2$d%3$02d%4$02d",
                    Integer.valueOf(nList[0]), Integer.valueOf(nList[1]),
                    Integer.valueOf(nList[2]), Integer.valueOf(nList[3]));

            return Integer.valueOf(versionCodeStr);
        }
        return 0;
    }

    /**
     * 将时间戳转换为时间
     */
    public static String stampToDate(long lt, int type) {
        String format = "yyyy-MM-dd HH:mm:ss";
        if (type == 1) {
            format = "yyyy-MM-dd HH:mm";
        } else if (type == 2) {
            format = "yyyy-MM-dd";
        } else if (type == 3) {
            format = "yyyy-MM";
        } else if (type == 4) {
            format = "MM-dd HH:mm";
        } else if (type == 5) {
            format = "MM-dd";
        } else if (type == 6) {
            format = "HH:mm";
        } else if (type == 7) {
            format = "dd";
        } else if (type == 8) {
            format = "yy/MM/dd";
        } else if (type == 9) {
            format = "mm:ss";
        } else if (type == 10) {
            format = "yyyy$MM$dd$HH$mm$ss$";
        } else if (type == 11) {
            format = "yyyy年MM月dd日";
        }
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.CHINA);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * dp转px
     *
     * @param context content
     * @param dpValue dp
     * @return
     */
    public static int dipToPx(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * Android9(P)版本使用反射弹出异常Dialog,关闭之
     */
    public static void closeAndroidPDialog(){
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            @SuppressLint("SoonBlockedPrivateApi") Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static SimpleDateFormat sdf = null;
    public  static String formatUTC(long l, String strPattern) {
        if (TextUtils.isEmpty(strPattern)) {
            strPattern = "yyyy-MM-dd HH:mm:ss";
        }
        if (sdf == null) {
            try {
                sdf = new SimpleDateFormat(strPattern, Locale.CHINA);
            } catch (Throwable e) {
            }
        } else {
            sdf.applyPattern(strPattern);
        }
        return sdf == null ? "NULL" : sdf.format(l);
    }


    //string转double,str为空时会抛异常NullPointerException,str格式异常会抛NumberFormatException
    //只捕获NumberFormatException异常,规避空指针异常。封装方法统一调用
    public static double stringToDdouble(String str){
        double mDdouble = 0;
        if(!TextUtils.isEmpty(str)){
            try {
                mDdouble = Double.parseDouble(str);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                mDdouble = -1;
            }
        }
        return mDdouble;
    }

}