一个好用的工具类基类

public class BaseUtils {
    private static Display display;

    private static final String DATE_1 = "yyyyMMddhhmmss";

    private static final String DATE_2 = "yyyyMMddhhmm";

    public static boolean isMobileNO1(String mobiles) {
        Pattern p = Pattern.compile("^[0-9]{3,4}(-)[0-9]{7,8}$|^(\\+86)?1[3,5,8,7,4][0-9]{9}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static boolean aa(String aa) {
        Pattern p = Pattern.compile("订单号:(\\d*).*?共");
        Matcher m = p.matcher(aa);
        while (m.find()) {
            if (!"".equals(m.group()))
                Log.e("memeda", m.group().replace("订单号:", "").replace("共", "").trim());
        }
        return m.matches();
    }

    public static boolean isExpress(String mobiles) {
        String pattern = "([0-9a-zA-Z]|(-))*";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static boolean isPassword(String mobiles) {
        Pattern p = Pattern.compile("^[a-zA-Z0-9_]*$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 根据手机的分辨率从 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 String findToken(String cookies) {
        if (TextUtils.isEmpty(cookies)) {
            return null;
        }
        String[] strs = cookies.split(";");
        StringBuffer sb = new StringBuffer();
        String temp = null;
        for (String str : strs) {
            temp = str.trim().replace("Path=/", "");
            if (str.startsWith("userToken")) {
                sb.append(temp);
                sb.append(";");
            } else if (temp.startsWith("HttpOnlyuserToken")) {
                sb.append(temp.replace("HttpOnlyuserToken", "userToken"));
                sb.append(";");
            } else if (temp.startsWith("userType")) {
                sb.append(temp);
                sb.append(";");
            } else if (temp.startsWith("uid")) {
                sb.append(temp);
            }
        }
        return sb.toString();
    }

    /*
    "" = Constant.FILE_PATH
     */
    public static String compressImageWrite(Bitmap image, String id)
            throws IOException {
        File file = new File(String.format("", id));
        if (image == null) {
            return "";
        }
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        image = comp(image);
        FileOutputStream fos = new FileOutputStream(file);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 这里压缩options%,把压缩后的数据存放到baos中
        baos.writeTo(fos);
        return file.getPath();
    }

    private static Bitmap comp(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%,把压缩后的数据存放到baos中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = 300f;
        float ww = 300f;
        // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
        int scale = 1;
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            scale = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            scale = (int) (newOpts.outHeight / hh);
        }
        if (scale <= 0)
            scale = 1;
        newOpts.inSampleSize = scale;// 设置缩放比例
        newOpts.inPreferredConfig = Config.RGB_565;// 降低图片从ARGB888到RGB565
        // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return bitmap;// 压缩好比例大小后再进行质量压缩
    }

    /**
     * 图片圆形处理
     *
     * @param img
     * @return
     */
    public static Bitmap bitmapRound(Bitmap img) {
        if (img == null) {
            return null;
        }
        int w = img.getWidth();
        int h = img.getHeight();
        int size = w > h ? h : w;
        Paint p = new Paint();
        p.setColor(Color.WHITE);
        p.setAntiAlias(false);
        Bitmap bitmap = Bitmap.createBitmap(size, size, Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawRoundRect(new RectF(0, 0, size, size), 10, 10, p);
        p.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(img, 0, 0, p);
        p.setXfermode(null);
        p.setStrokeWidth(10);
        p.setStyle(Paint.Style.STROKE);

        return bitmap;
    }

    /**
     * 图片圆形处理
     *
     * @param img
     * @return
     */
    public static Bitmap bitmapCircle(Bitmap img) {
        if (img == null) {
            return null;
        }
        int w = img.getWidth();
        int h = img.getHeight();
        int size = w > h ? h : w;
        Paint p = new Paint();
        p.setColor(Color.WHITE);
        p.setAntiAlias(false);
        Bitmap bitmap = Bitmap.createBitmap(size, size, Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawCircle(size / 2, size / 2, size / 2, p);
        p.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(img, 0, 0, p);
        p.setXfermode(null);
        p.setStrokeWidth(10);
        p.setStyle(Paint.Style.STROKE);

        return bitmap;
    }

    public static String formatDate(String dateStr) {
        if (TextUtils.isEmpty(dateStr)) {
            return null;
        }
        try {
            return DateFormat.format("MM-dd HH:mm", new SimpleDateFormat(DATE_1).parse(dateStr)).toString();
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String formatDate1(String dateStr) {
        if (TextUtils.isEmpty(dateStr)) {
            return null;
        }
        try {
            return DateFormat.format("MM-dd HH:mm", new SimpleDateFormat(DATE_2).parse(dateStr)).toString();
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] bitmapToBytes(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 将Bitmap压缩成PNG编码,质量为100%存储
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);//除了PNG还有很多常见格式,如jpeg等。
        return os.toByteArray();
    }

    public static String getMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();

            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++) {
                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }
            return strBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    private static String key = "a6U&1$Ip[Jr/sed]Rfvn=O>Mz+}lXN*%-gLcGD|0";

    //SHA1 加密实例
    public static String encryptToSHA(String info) {
        byte[] digesta = null;
        try {
// 得到一个SHA-1的消息摘要
            MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要进行计算摘要的信息
            alga.update(info.getBytes());
// 得到该摘要
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
// 将摘要转为字符串
        String rs = byte2hex(digesta);
        return rs + key;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs;
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        switch (requestCode) {
//            case 123:
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    // Permission Granted
//                    getMyUUID(context1);
//                } else {
//                    // Permission Denied
//                    Toast.makeText(context1, "没有定位权限!", Toast.LENGTH_SHORT)
//                            .show();
//                }
//                break;
//            default:
//                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        }
//    }

    /**
     * UUID
     *
     * @return
     */
    public static String getMyUUID(Context context) {
//        context1 = context;
//        int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, "android.permission.READ_PHONE_STATE");
//        if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions((Activity) context, new String[]{"android.permission.READ_PHONE_STATE"}, 123);
//            return "0";
//        } else {
        //上面已经写好的拨号方法
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        final String tmDevice, tmSerial, tmPhone, androidId;

        tmDevice = "" + tm.getDeviceId();

        tmSerial = "" + tm.getSimSerialNumber();

        androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());

        String uniqueId = deviceUuid.toString();

        return uniqueId;
//        }


    }


    /**
     * 检查当前网络是否可用
     *
     * @return
     */

    public static boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    Log.e("===状态===", networkInfo[i].getState().toString());
                    Log.e("===类型===", networkInfo[i].getTypeName().toString());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static void showNetexception(String net, Context context) {
//        if (net.equals(Constant.NETEXCEPTION)) {
//            Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
//        } else {
//            Toast.makeText(context, "请稍后重试", Toast.LENGTH_SHORT).show();
//        }
    }

    public static void goToMarket(Context context, String packageName) {
//        Uri uri = Uri.parse("market://details?id=" + packageName);
//        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
//        try {
//            context.startActivity(goToMarket);
//        } catch (ActivityNotFoundException e) {
//            e.printStackTrace();
//            Log.e("123",e.toString());
//        }
        Uri uri = Uri.parse("market://details?id=" + packageName);
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        try {
            goToMarket.setClassName("com.tencent.android.qqdownloader", "com.tencent.pangu.link.LinkProxyActivity");
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Log.e("13", e.toString());
        }
    }

    public static void launchAppDetail(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg))
                intent.setPackage(marketPkg);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("1", e.toString());
        }
    }

    /**
     * 获取加密sign值
     *
     * @param map
     * @return
     */
    public static String getSign(Map<String, String> map, String time) {
        String key = "";
//        Set keys = map.keySet();
//        if (keys != null) {
//            Set<String> keySet = map.keySet();
//            Iterator<String> iter = keySet.iterator();
//            while (iter.hasNext()) {
//                key = key + map.get(key);
//            }
//        }
        Object[] keys = map.keySet().toArray();
        Arrays.sort(keys);

        for (int i = 0; i < keys.length; i++) {
            System.out.println(map.get(keys[i]));
            key = key + map.get(keys[i]);
        }
        return getMD5(key + Constant.KEY);
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }

    //比较器类
    public static class MapKeyComparator implements Comparator<String> {
        public int compare(String str1, String str2) {
            return str1.compareTo(str2);
        }
    }

    public static String getVersioncode(Context context) {
        String pkName = context.getPackageName();
        String versionName = null;
        int versionCode = 0;
        try {
            versionName = context.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            versionCode = context.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值