总结了一下android 码农经常用到的一些方法,工具类。

    private static Context context;

    private static Display display;

    private static String TAG = "MyTools";


    public Practical(Context context) {

        Practical.context = context;

    }

    /**
     * 给字符串每隔几个字符加一个逗号
     *
     * @param str   字符串
     * @param digit 间隙是几就写几
     * @return
     */
    private static String addComma(String str, int digit) {
        // 将传进数字反转
        String reverseStr = new StringBuilder(str).reverse().toString();
        String strTemp = "";
        for (int i = 0; i < reverseStr.length(); i++) {
            if (i * digit + digit > reverseStr.length()) {
                strTemp += reverseStr.substring(i * digit, reverseStr.length());
                break;
            }
            strTemp += reverseStr.substring(i * digit, i * digit + digit) + ",";
        }
        // 将[789,456,] 中最后一个[,]去除
        if (strTemp.endsWith(",")) {
            strTemp = strTemp.substring(0, strTemp.length() - 1);
        }
        // 将数字重新反转
        String resultStr = new StringBuilder(strTemp).reverse().toString();
        return resultStr;
    }

    /**
     * 精确获取屏幕尺寸(例如:3.5、4.0、5.0寸屏幕)
     *
     * @param ctx
     * @return
     */
    public static double getScreenPhysicalSize(Activity ctx) {
        DisplayMetrics dm = new DisplayMetrics();
        ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);
        double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));
        return diagonalPixels / (160 * dm.density);
    }

    /**
     * 判断是否是平板(官方用法)
     *
     * @param context
     * @return
     */
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 获取屏幕高度
     *
     * @return
     */
    public static int getScreenHeight()

    {

        if (context == null) {

            Log.e("hck", TAG + "  getScreenHeight: " + "context 不能为空");

            return 0;

        }

        display = ((Activity) context).getWindowManager().getDefaultDisplay();

        return display.getHeight();

    }

    /**
     * 获取屏幕宽度
     *
     * @return
     */

    public static int getScreenWidth()

    {

        if (context == null) {

            Log.e("hck", TAG + "  getScreenHeight: " + "context 不能为空");

            return 0;

        }

        display = ((Activity) context).getWindowManager().getDefaultDisplay();

        return display.getWidth();

    }

    /**
     * SDK号
     *
     * @return
     */

    public static String getSDK() {

        return android.os.Build.VERSION.SDK;


    }

    /**
     * 手机型号
     *
     * @return
     */
    public static String getModel()

    {

        return android.os.Build.MODEL;

    }

    /**
     * android系统版本号
     *
     * @return
     */
    public static String getRelease()

    {

        return android.os.Build.VERSION.RELEASE;

    }

    /**
     * 获取手机身份证imei
     *
     * @param context
     * @return
     */
    public static String getImei(Context context)

    {

        TelephonyManager telephonyManager = (TelephonyManager) context

                .getSystemService(Context.TELEPHONY_SERVICE);

        return telephonyManager.getDeviceId();

    }

    /**
     * 获取版本名字
     *
     * @param context
     * @return
     */
    public static String getVerName(Context context) {

        try {

            String pkName = context.getPackageName();

            String versionName = context.getPackageManager().getPackageInfo(

                    pkName, 0).versionName;


            return versionName;

        } catch (Exception e) {

        }

        return null;

    }

    /**
     * 获取版本号
     *
     * @param context
     * @return
     */
    public static int getVerCode(Context context) {

        String pkName = context.getPackageName();

        try {

            int versionCode = context.getPackageManager().getPackageInfo(

                    pkName, 0).versionCode;

            return versionCode;

        } catch (PackageManager.NameNotFoundException e) {

            e.printStackTrace();

        }

        return 0;

    }

    /**
     * 判断网络连接是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);
//获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        if (connectivity == null)

            return false;

// 获取网络连接管理的对象

        NetworkInfo info = connectivity.getActiveNetworkInfo();

        if (info == null || !info.isConnected())

            return false;

// 判断当前网络是否已经连接

        return (info.getState() == NetworkInfo.State.CONNECTED);

    }

    /**
     * 字符串超出给定文字则截取
     *
     * @param str
     * @param limit
     * @return
     */
    public static String trim(String str, int limit) {

        String mStr = str.trim();

        return mStr.length() > limit ? mStr.substring(0, limit) : mStr;

    }

    /**
     * 获取手机号码,很多手机获取不到
     *
     * @param context
     * @return
     */
    public static String getTel(Context context) {

        TelephonyManager telManager = (TelephonyManager) context

                .getSystemService(Context.TELEPHONY_SERVICE);

        return telManager.getLine1Number();

    }

    /**
     * 获取时机mac地址
     *
     * @param context
     * @return
     */
    public static String getMac(Context context) {

        final WifiManager wifi = (WifiManager) context

                .getSystemService(Context.WIFI_SERVICE);

        if (wifi != null) {

            WifiInfo info = wifi.getConnectionInfo();

            if (info.getMacAddress() != null) {

                return info.getMacAddress().toLowerCase(Locale.ENGLISH)

                        .replace(":", "");

            }

            return "";

        }

        return "";

    }


    /**
     * 將 像素 转换成dp
     *
     * @param pxValue 像素
     * @returndp
     */

    public static int px2dip(int pxValue) {

        final float scale = context.getResources().getDisplayMetrics().density;

        return (int) (pxValue / scale + 0.5f);

    }


    /**
     * 將 畫素 轉換成sp
     *
     * @param px
     * @returnsp
     */

    public static int px2sp(int px) {

        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;

        return (int) (px / scaledDensity);

    }


    /**
     * 將 dip 轉換成畫素px
     *
     * @param dipValue dip 像素的值
     * @return 畫素px
     */

    public static int dip2px(float dipValue) {

        final float scale = context.getResources().getDisplayMetrics().density;

        return (int) (dipValue * scale + 0.5f);

    }


    public static int[][] getViewsPosition(List views) {

        int[][] location = new int[views.size()][2];

        for (int index = 0; index < views.size(); index++) {

            views.get(index).getLocationOnScreen(location[index]);

        }

        return location;

    }


    /**
     * 传入一个view,返回一个int数组来存放 view在手机屏幕上左上角的绝对坐标
     *
     * @param view 传入的view
     * @return 返回int型数组, location[0]表示x, location[1]表示y
     */

    public static int[] getViewPosition(View view) {

        int[] location = new int[2];

        view.getLocationOnScreen(location);

        return location;

    }


    /**
     * onTouch界面时指尖在views中的哪个view当中
     *
     * @param event ontouch事件
     * @param views view list
     * @return view
     */
    public static View getOnTouchedView(MotionEvent event, List views) {
        int[][] location = getViewsPosition(views);
        for (int index = 0; index < views.size(); index++) {
            if (event.getRawX() > location[index][0]
                    && event.getRawX() < location[index][0]
                    + views.get(index).getWidth()
                    && event.getRawY() > location[index][1]
                    && event.getRawY() < location[index][1]
                    + views.get(index).getHeight()) {
                return views.get(index);

            }

        }

        return null;

    }


    /**
     * 将传进的图片存储在手机上,并返回存储路径
     *
     * @param photo Bitmap 类型,传进的图片
     * @return String 返回存储路径
     */
    public static String savePic(Bitmap photo, String name, String path) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 创建一个

// outputstream

// 来读取文件流

        photo.compress(Bitmap.CompressFormat.PNG, 100, baos);// 把 bitmap 的图片转换成

// jpge

// 的格式放入输出流中

        byte[] byteArray = baos.toByteArray();

        String saveDir = Environment.getExternalStorageDirectory()

                .getAbsolutePath();

        File dir = new File(saveDir + "/" + path);// 定义一个路径

        if (!dir.exists()) {// 如果路径不存在,创建路径

            dir.mkdir();

        }

        File file = new File(saveDir, name + ".png");// 定义一个文件

        if (file.exists())

            file.delete(); // 删除原来有此名字文件,删除

        try {

            file.createNewFile();

            FileOutputStream fos;

            fos = new FileOutputStream(file);// 通过 FileOutputStream 关联文件

            BufferedOutputStream bos = new BufferedOutputStream(fos); // 通过 bos

// 往文件里写东西

            bos.write(byteArray);

            bos.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return file.getPath();

    }


    /**
     * 回收 bitmap 减小系统占用的资源消耗
     */

    public static void destoryBimap(Bitmap photo) {

        if (photo != null && !photo.isRecycled()) {

            photo.recycle();

            photo = null;

        }

    }


    /**
     * 將輸入字串做 md5 編碼
     *
     * @param s : 欲編碼的字串
     * @return 編碼後的字串, 如失敗, 返回 ""
     */

    public static String md5(String s) {

        try {

// Create MD5 Hash

            MessageDigest digest = MessageDigest

                    .getInstance("MD5");

            digest.update(s.getBytes("UTF-8"));

            byte messageDigest[] = digest.digest();


// Create Hex String

            StringBuffer hexString = new StringBuffer();

            for (byte b : messageDigest) {

                if ((b & 0xFF) < 0x10)

                    hexString.append("0");

                hexString.append(Integer.toHexString(b & 0xFF));

            }

            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {

            return "";

        } catch (UnsupportedEncodingException e) {

            return "";

        }

    }

    /**
     * 是否是数字
     *
     * @param c
     * @return
     */
    public static boolean isNumber(char c) {

        boolean isNumer = false;

        if (c >= '0' && c <= '9') {

            isNumer = true;

        }

        return isNumer;

    }

    /**
     * 是否是正确的邮箱地址
     *
     * @param strEmail
     * @return
     */
    public static boolean strEmail(String strEmail) {

        String checkemail = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";


        Pattern pattern = Pattern.compile(checkemail);


        Matcher matcher = pattern.matcher(strEmail);


        return matcher.matches();

    }

    /**
     * 字符串是否为空
     *
     * @param string
     * @return
     */
    public static boolean isNull(String string)

    {

        if (null == string || "".equals(string)) {

            return false;

        }

        return true;

    }

    /**
     * 字符串长度检测
     *
     * @param string
     * @param max
     * @param min
     * @return
     */
    public static boolean isLenghtOk(String string, int max, int min)

    {

        if (null != string) {

            if (string.length() > max || string.length() < min) {

                return false;

            }

        }

        return true;

    }

    /**
     * 字符串长度是否
     *
     * @param string
     * @param max
     * @return
     */
    public static boolean isLenghtOk(String string, int max)

    {

        if (null != string) {

            if (string.length() > max) {

                return false;

            }

        }

        return true;

    }


/**

 *activity管理类,保证应用退出后,销毁所有创建的activity

 **/


    /**
     * 应用程序Activity管理类:用于Activity管理和应用程序退出
     *
     * @author liux (http://my.oschina.net/liux)
     * @version 1.0
     * @created 2012-3-21
     */

    public static class AppManager {

        private static Stack activityStack;

        private static AppManager instance;

        private AppManager() {
        }

        /**
         * 单一实例
         */

        public static AppManager getAppManager() {

            if (instance == null) {

                instance = new AppManager();

            }

            return instance;

        }

        /**
         * 添加Activity到堆栈
         */

        public void addActivity(Activity activity) {

            if (activityStack == null) {

                activityStack = new Stack();

            }

            activityStack.add(activity);

        }

        /**
         * 获取当前Activity(堆栈中最后一个压入的)
         */

        public Activity currentActivity() {

            Activity activity = activityStack.lastElement();

            return activity;

        }

        /**
         * 结束当前Activity(堆栈中最后一个压入的)
         */

        public void finishActivity() {

            Activity activity = activityStack.lastElement();

            finishActivity(activity);

        }

        /**
         * 结束指定的Activity
         */

        public void finishActivity(Activity activity) {

            if (activity != null) {

                activityStack.remove(activity);

                activity.finish();

                activity = null;

            }

        }

        /**
         * 结束指定类名的Activity
         */

        public void finishActivity(Class cls) {

            for (Activity activity : activityStack) {

                if (activity.getClass().equals(cls)) {

                    finishActivity(activity);

                }

            }

        }

        /**
         * 结束所有Activity
         */

        public void finishAllActivity() {

            for (int i = 0, size = activityStack.size(); i < size; i++) {

                if (null != activityStack.get(i)) {

                    activityStack.get(i).finish();

                }

            }

            activityStack.clear();

        }

        /**
         * 退出应用程序
         */

        public void AppExit(Context context) {

            try {

                finishAllActivity();

                ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

                activityMgr.restartPackage(context.getPackageName());

                System.exit(0);

            } catch (Exception e) {
            }

        }

    }


    /**
     * 字符串相关工具类
     */
    private final static ThreadLocal dateFormater = new ThreadLocal() {

        @Override

        protected SimpleDateFormat initialValue() {

            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        }

    };


    private final static ThreadLocal dateFormater2 = new ThreadLocal() {

        @Override

        protected SimpleDateFormat initialValue() {

            return new SimpleDateFormat("yyyy-MM-dd");

        }

    };

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */

    public static Date toDate(String sdate) {

        try {

            return dateFormater.get().parse(sdate);

        } catch (ParseException e) {

            return null;

        }

    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */

    public static String friendly_time(String sdate) {

        Date time = toDate(sdate);

        if (time == null) {

            return "Unknown";

        }

        String ftime = "";

        Calendar cal = Calendar.getInstance();

//判断是否是同一天

        String curDate = dateFormater2.get().format(cal.getTime());

        String paramDate = dateFormater2.get().format(time);

        if (curDate.equals(paramDate)) {

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

            if (hour == 0)

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

            else

                ftime = hour + "小时前";

            return ftime;

        }

        long lt = time.getTime() / 86400000;

        long ct = cal.getTimeInMillis() / 86400000;

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

        if (days == 0) {

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

            if (hour == 0)

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

            else

                ftime = hour + "小时前";

        } else if (days == 1) {

            ftime = "昨天";

        } else if (days == 2) {

            ftime = "前天";

        } else if (days > 2 && days <= 10) {

            ftime = days + "天前";

        } else if (days > 10) {

            ftime = dateFormater2.get().format(time);

        }

        return ftime;

    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */

    public static boolean isToday(String sdate) {

        boolean b = false;

        Date time = toDate(sdate);

        Date today = new Date();

        if (time != null) {

            String nowDate = dateFormater2.get().format(today);

            String timeDate = dateFormater2.get().format(time);

            if (nowDate.equals(timeDate)) {

                b = true;

            }

        }

        return b;

    }

    /**
     * 判断给定字符串是否空白串。
     * 

* 空白串是指由空格、制表符、回车符、换行符组成的字符串 *

* 若输入字符串为null或空字符串,返回true * * @param input * @return boolean */ public static boolean isEmpty(String input) { if (input == null || "".equals(input)) return true; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c != ' ' && c != '\t' && c != '\r' && c != '\n') { return false; } } return true; } /** * 判断是不是一个合法的电子邮件地址 * * @param email * @return */ public static boolean isEmail(String email) { if (email == null || email.trim().length() == 0) return false; return email.matches(email); } /** * 字符串转整数 * * @param str * @param defValue * @return */ public static int toInt(String str, int defValue) { try { return Integer.parseInt(str); } catch (Exception e) { } return defValue; } /** * 对象转整数 * * @param obj * @return 转换异常返回 0 */ public static int toInt(Object obj) { if (obj == null) return 0; return toInt(obj.toString(), 0); } /** * 对象转整数 * * @param obj * @return 转换异常返回 0 */ public static long toLong(String obj) { try { return Long.parseLong(obj); } catch (Exception e) { } return 0; } /** * 字符串转布尔值 * * @param b * @return 转换异常返回 false */ public static boolean toBool(String b) { try { return Boolean.parseBoolean(b); } catch (Exception e) { } return false; } /** * 获取meta-data 里面的值 * * @param context * @param metaKey * @return */ public static String getMetaValue(Context context, String metaKey) { Bundle metaData = null; String apiKey = null; if (context == null || metaKey == null) { return null; } try { ApplicationInfo ai = context.getPackageManager() .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); if (null != ai) { metaData = ai.metaData; } if (null != metaData) { apiKey = metaData.getString(metaKey); } } catch (PackageManager.NameNotFoundException e) { } return apiKey; }


你可能感兴趣的:(android工具类)