Android---工具類Utils(你想不到的完美)

/*
 * framework工具??
 */
public class Utils {

    /** tag */
    private static final String TAG = "Utils";

    /**
     * 安裝某個應用
     * 
     * @param context
     * @param apkFile
     * @return
     */
    public static boolean installApp(Context context, File apkFile) {
        try {
            context.startActivity(getInstallAppIntent(apkFile));
            return true;
        } catch (Exception e) {
            Log.w(TAG, e);
        }
        return false;
    }

    /**
     * 獲取安裝應用的Intent
     * 
     * @param apkFile
     * @return
     */
    public static Intent getInstallAppIntent(File apkFile) {
        if (apkFile == null || !apkFile.exists()) {
            return null;
        }

        Utils.chmod("777", apkFile.getAbsolutePath());
        Uri uri = Uri.fromFile(apkFile);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        return intent;
    }

    /**
     * ??查某個包名的App是否已經(jīng)安裝
     * 
     * @param context
     * @param packageName
     * @return
     */
    public static boolean hasAppInstalled(Context context, String packageName) {
        try {
            PackageManager packageManager = context.getPackageManager();
            packageManager.getPackageInfo(packageName,
                    PackageManager.GET_ACTIVITIES);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 根據(jù)包名啟動第三方App
     * 
     * @param context
     * @param packageName
     * @return
     */
    public static boolean launchAppByPackageName(Context context,
            String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }

        try {
            Intent intent = context.getPackageManager()
                    .getLaunchIntentForPackage(packageName);
            if (intent != null) {
                context.startActivity(intent);
                return true;
            }
        } catch (Exception e) {
            Log.w(TAG, e);
        }
        return false;
    }

    public static String getAssetsFie(Context context, String name)
            throws IOException {

        InputStream is = context.getAssets().open(name);
        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        String content = new String(buffer, "UTF-8");

        return content;

    }

    /**
     * 是否為wifi連接狀???
     * 
     * @param context
     * @return
     */
    public static boolean isWifiConnect(Context context) {
        ConnectivityManager connectivitymanager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
        if (networkinfo != null) {
            if ("wifi".equals(networkinfo.getTypeName().toLowerCase(Locale.US))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否有網(wǎng)絡連??
     * 
     * @param context
     * @return
     */
    public static boolean isNetConnect(Context context) {
        ConnectivityManager connectivitymanager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
        return networkinfo != null;
    }

    /**
     * 獲取權限
     * 
     * @param permission
     *            權限
     * @param path
     *            文件路徑
     */
    public static void chmod(String permission, String path) {
        try {
            String command = "chmod " + permission + " " + path;
            Runtime runtime = Runtime.getRuntime();
            runtime.exec(command);
        } catch (IOException e) {
            Log.e(TAG, "chmod", e);
        }
    }

    /**
     * 是否安裝了sdcard??
     * 
     * @return true表示有,false表示沒有
     */
    public static boolean haveSDCard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    /**
     * 獲取系統(tǒng)內(nèi)部可用空間大小
     * 
     * @return available size
     */
    public static long getSystemAvailableSize() {
        File root = Environment.getRootDirectory();
        StatFs sf = new StatFs(root.getPath());
        long blockSize = sf.getBlockSize();
        long availCount = sf.getAvailableBlocks();
        return availCount * blockSize;
    }

    /**
     * 獲取sd卡可用空間大??
     * 
     * @return available size
     */
    public static long getSDCardAvailableSize() {
        long available = 0;
        if (haveSDCard()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs statfs = new StatFs(path.getPath());
            long blocSize = statfs.getBlockSize();
            long availaBlock = statfs.getAvailableBlocks();

            available = availaBlock * blocSize;
        } else {
            available = -1;
        }
        return available;
    }

    /**
     * 獲取application層級的metadata
     * 
     * @param context
     * @param key
     * @return
     */
    public static String getApplicationMetaData(Context context, String key) {
        try {
            Object metaObj = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA).metaData
                    .get(key);
            if (metaObj instanceof String) {
                return metaObj.toString();
            } else if (metaObj instanceof Integer) {
                return ((Integer) metaObj).intValue() + "";
            } else if (metaObj instanceof Boolean) {
                return ((Boolean) metaObj).booleanValue() + "";
            }
        } catch (NameNotFoundException e) {
            Log.w(TAG, e);
        }
        return "";
    }

    /**
     * 獲取版本??
     * 
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            Log.w(TAG, e);
        }
        return null;
    }

    /**
     * 獲取版本??
     * 
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            Log.w(TAG, e);
        }
        return 0;
    }

    /**
     * 將px值轉換為dip或dp值,保證尺寸大小不變
     * 
     * @param pxValue
     * @param scale
     *            (DisplayMetrics類中屬???density??
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 將dip或dp值轉換為px值,保證尺寸大小不變
     * 
     * @param dipValue
     * @param scale
     *            (DisplayMetrics類中屬???density??
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 將px值轉換為sp值纱扭,保證文字大小不變
     * 
     * @param pxValue
     * @param fontScale
     *            (DisplayMetrics類中屬???scaledDensity??
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 將sp值轉換為px值萤皂,保證文字大小不變
     * 
     * @param spValue
     * @param fontScale
     *            (DisplayMetrics類中屬???scaledDensity??
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 隱藏鍵盤
     * 
     * @param activity
     *            activity
     */
    public static void hideInputMethod(Activity activity) {
        hideInputMethod(activity, activity.getCurrentFocus());
    }

    /**
     * 隱藏鍵盤
     * 
     * @param context
     *            context
     * @param view
     *            The currently focused view
     */
    public static void hideInputMethod(Context context, View view) {
        if (context == null || view == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 顯示輸入鍵盤
     * 
     * @param context
     *            context
     * @param view
     *            The currently focused view, which would like to receive soft
     *            keyboard input
     */
    public static void showInputMethod(Context context, View view) {
        if (context == null || view == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(view, 0);
        }
    }

    /**
     * Bitmap縮放,注意源Bitmap在縮放后將會被回收???
     * 
     * @param origin
     * @param width
     * @param height
     * @return
     */
    public static Bitmap getScaleBitmap(Bitmap origin, int width, int height) {
        float originWidth = origin.getWidth();
        float originHeight = origin.getHeight();

        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width) / originWidth;
        float scaleHeight = ((float) height) / originHeight;

        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap scale = Bitmap.createBitmap(origin, 0, 0, (int) originWidth,
                (int) originHeight, matrix, true);
        origin.recycle();
        return scale;
    }

    /**
     * 計算某一時間與現(xiàn)在時間間隔的文字提示
     */
    public static String countTimeIntervalText(long time) {
        long dTime = System.currentTimeMillis() - time;
        // 15分鐘
        if (dTime < 15 * 60 * 1000) {
            return "剛剛";
        } else if (dTime < 60 * 60 * 1000) {
            // ??小時
            return "??小時??";
        } else if (dTime < 24 * 60 * 60 * 1000) {
            return (int) (dTime / (60 * 60 * 1000)) + "小時??";
        } else {
            return DateFormat.format("MM-dd kk:mm", System.currentTimeMillis())
                    .toString();
        }
    }

    /**
     * 獲取通知欄高??
     * 
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int x = 0, statusBarHeight = 0;
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 獲取標題欄高??
     * 
     * @param context
     * @return
     */
    public static int getTitleBarHeight(Activity context) {
        int contentTop = context.getWindow()
                .findViewById(Window.ID_ANDROID_CONTENT).getTop();
        return contentTop - getStatusBarHeight(context);
    }

    /**
     * 獲取屏幕寬度硬贯,px
     * 
     * @param context
     * @return
     */
    public static float getScreenWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 獲取屏幕高度索烹,px
     * 
     * @param context
     * @return
     */
    public static float getScreenHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 獲取屏幕像素密度
     * 
     * @param context
     * @return
     */
    public static float getDensity(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.density;
    }

    /**
     * 獲取scaledDensity
     * 
     * @param context
     * @return
     */
    public static float getScaledDensity(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.scaledDensity;
    }

    /**
     * 獲取當前小時分鐘??24小時??
     * 
     * @return
     */
    public static String getTime24Hours() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.CHINA);
        Date curDate = new Date(System.currentTimeMillis());// 獲取當前時間
        return formatter.format(curDate);
    }

    /**
     * 獲取電池電量,0~1
     * 
     * @param context
     * @return
     */
    @SuppressWarnings("unused")
    public static float getBattery(Context context) {
        Intent batteryInfoIntent = context.getApplicationContext()
                .registerReceiver(null,
                        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int status = batteryInfoIntent.getIntExtra("status", 0);
        int health = batteryInfoIntent.getIntExtra("health", 1);
        boolean present = batteryInfoIntent.getBooleanExtra("present", false);
        int level = batteryInfoIntent.getIntExtra("level", 0);
        int scale = batteryInfoIntent.getIntExtra("scale", 0);
        int plugged = batteryInfoIntent.getIntExtra("plugged", 0);
        int voltage = batteryInfoIntent.getIntExtra("voltage", 0);
        int temperature = batteryInfoIntent.getIntExtra("temperature", 0); // 溫度的單位是10??
        String technology = batteryInfoIntent.getStringExtra("technology");
        return ((float) level) / scale;
    }

    /**
     * 獲取手機名稱
     * 
     * @return
     */
    public static String getMobileName() {
        return android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL;
    }

    /**
     * 是否安裝了sdcard??
     * 
     * @return true表示有届案,false表示沒有
     */
    public static boolean hasSDCard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    /**
     * 獲取sd卡可用空??
     * 
     * @return available size
     */
    public static long getAvailableExternalSize() {
        long available = 0;
        if (hasSDCard()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs statfs = new StatFs(path.getPath());
            long blocSize = statfs.getBlockSize();
            long availaBlock = statfs.getAvailableBlocks();

            available = availaBlock * blocSize;
        } else {
            available = -1;
        }
        return available;
    }

    /**
     * 獲取內(nèi)存可用空間
     * 
     * @return available size
     */
    public static long getAvailableInternalSize() {
        long available = 0;
        if (hasSDCard()) {
            File path = Environment.getRootDirectory();
            StatFs statfs = new StatFs(path.getPath());
            long blocSize = statfs.getBlockSize();
            long availaBlock = statfs.getAvailableBlocks();

            available = availaBlock * blocSize;
        } else {
            available = -1;
        }
        return available;
    }

    /*
     * 版本控制部分
     */

    /**
     * 是否??2.2版本及以??
     * 
     * @return
     */
    public static boolean hasFroyo() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    /**
     * 是否??2.3版本及以??
     * 
     * @return
     */
    public static boolean hasGingerbread() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
    }

    /**
     * 是否??3.0版本及以??
     * 
     * @return
     */
    public static boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    /**
     * 是否??3.1版本及以??
     * 
     * @return
     */
    public static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
    }

    /**
     * 是否??4.1版本及以??
     * 
     * @return
     */
    public static boolean hasJellyBean() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
    }

    public static String getPhoneType() {

        String phoneType = android.os.Build.MODEL;

        Log.d(TAG, "phoneType is : " + phoneType);

        return phoneType;
    }

    /**
     * 獲取系統(tǒng)版本??
     * 
     * @return
     */
    public static String getOsVersion() {
        String osversion;
        int osversion_int = getOsVersionInt();
        osversion = osversion_int + "";
        return osversion;

    }

    /**
     * 獲取系統(tǒng)版本??
     * 
     * @return
     */
    public static int getOsVersionInt() {
        return Build.VERSION.SDK_INT;

    }

    /**
     * 獲取ip地址
     * 
     * @return
     */
    public static String getHostIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(inetAddress
                                    .getHostAddress())) {
                        if (!inetAddress.getHostAddress().toString()
                                .equals("null")
                                && inetAddress.getHostAddress() != null) {
                            return inetAddress.getHostAddress().toString()
                                    .trim();
                        }
                    }
                }
            }
        } catch (Exception ex) {
            Log.e("WifiPreference IpAddress", ex.toString());
        }
        return "";
    }

    /**
     * 獲取手機號,幾乎獲取不到
     * 
     * @param context
     * @return
     */
    public static String getPhoneNum(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context
                .getApplicationContext().getSystemService(
                        Context.TELEPHONY_SERVICE);
        String phoneNum = mTelephonyMgr.getLine1Number();
        return TextUtils.isEmpty(phoneNum) ? "" : phoneNum;
    }

    /**
     * 獲取imei??
     * 
     * @param context
     * @return
     */
    public static String getPhoneImei(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context
                .getApplicationContext().getSystemService(
                        Context.TELEPHONY_SERVICE);
        String phoneImei = mTelephonyMgr.getDeviceId();
        Log.d(TAG, "IMEI is : " + phoneImei);
        return TextUtils.isEmpty(phoneImei) ? "" : phoneImei;
    }

    /**
     * 獲取imsi??
     * 
     * @param context
     * @return
     */
    public static String getPhoneImsi(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context
                .getApplicationContext().getSystemService(
                        Context.TELEPHONY_SERVICE);
        String phoneImsi = mTelephonyMgr.getSubscriberId();
        Log.d(TAG, "IMSI is : " + phoneImsi);

        return TextUtils.isEmpty(phoneImsi) ? "" : phoneImsi;
    }

    /**
     * 獲取mac地址
     * 
     * @return
     */
    public static String getLocalMacAddress() {
        String Mac = null;
        try {
            String path = "sys/class/net/wlan0/address";
            if ((new File(path)).exists()) {
                FileInputStream fis = new FileInputStream(path);
                byte[] buffer = new byte[8192];
                int byteCount = fis.read(buffer);
                if (byteCount > 0) {
                    Mac = new String(buffer, 0, byteCount, "utf-8");
                }
                fis.close();
            }

            if (Mac == null || Mac.length() == 0) {
                path = "sys/class/net/eth0/address";
                FileInputStream fis = new FileInputStream(path);
                byte[] buffer_name = new byte[8192];
                int byteCount_name = fis.read(buffer_name);
                if (byteCount_name > 0) {
                    Mac = new String(buffer_name, 0, byteCount_name, "utf-8");
                }
                fis.close();
            }

            if (Mac == null || Mac.length() == 0) {
                return "";
            } else if (Mac.endsWith("\n")) {
                Mac = Mac.substring(0, Mac.length() - 1);
            }
        } catch (Exception io) {
            Log.w(TAG, "Exception", io);
        }

        return TextUtils.isEmpty(Mac) ? "" : Mac;
    }

    /**
     * 獲取重復字段??多的個數(shù)
     * 
     * @param s
     * @return
     */
    public static int getRepeatTimes(String s) {
        if (TextUtils.isEmpty(s)) {
            return 0;
        }

        int mCount = 0;
        char[] mChars = s.toCharArray();
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        for (int i = 0; i < mChars.length; i++) {
            char key = mChars[i];
            Integer value = map.get(key);
            int count = value == null ? 0 : value.intValue();
            map.put(key, ++count);
            if (mCount < count) {
                mCount = count;
            }
        }

        return mCount;
    }

    /**
     * ??單判斷是否為手機號碼
     * 
     * @param num
     * @return
     */
    public static boolean isPhoneNum(String num) {
        // 確保每一位都是數(shù)??
        return !TextUtils.isEmpty(num) && num.matches("1[0-9]{10}")
                && !isRepeatedStr(num) && !isContinuousNum(num);
    }

    /**
     * 判斷是否400服務代碼
     * 
     * @param num
     * @return
     */
    public static boolean is400or800(String num) {
        return !TextUtils.isEmpty(num)
                && (num.startsWith("400") || num.startsWith("800"))
                && num.length() == 10;
    }

    /**
     * 判斷是否區(qū)域號碼
     * 
     * @param num
     * @return
     */
    public static boolean isAdCode(String num) {
        return !TextUtils.isEmpty(num) && num.matches("[0]{1}[0-9]{2,3}")
                && !isRepeatedStr(num);
    }

    /**
     * 判斷是否座機號碼
     * 
     * @param num
     * @return
     */
    public static boolean isPhoneHome(String num) {
        return !TextUtils.isEmpty(num) && num.matches("[0-9]{7,8}")
                && !isRepeatedStr(num);
    }

    /**
     * 判斷是否為重復字符串
     * 
     * @param str
     *            啦逆,需要檢查的字符??
     */
    public static boolean isRepeatedStr(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        int len = str.length();
        if (len <= 1) {
            return false;
        } else {
            char firstChar = str.charAt(0);// 第一個字??
            for (int i = 1; i < len; i++) {
                char nextChar = str.charAt(i);// 第i個字??
                if (firstChar != nextChar) {
                    return false;
                }
            }
            return true;
        }
    }

    /**
     * 判斷字符串是否為連續(xù)數(shù)字 45678901??
     */
    public static boolean isContinuousNum(String str) {
        if (TextUtils.isEmpty(str))
            return false;
        if (!isNumbericString(str))
            return true;
        int len = str.length();
        for (int i = 0; i < len - 1; i++) {
            char curChar = str.charAt(i);
            char verifyChar = (char) (curChar + 1);
            if (curChar == '9')
                verifyChar = '0';
            char nextChar = str.charAt(i + 1);
            if (nextChar != verifyChar) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判斷字符串是否為連續(xù)字母 xyZaBcd??
     */
    public static boolean isContinuousWord(String str) {
        if (TextUtils.isEmpty(str))
            return false;
        if (!isAlphaBetaString(str))
            return true;
        int len = str.length();
        String local = str.toLowerCase();
        for (int i = 0; i < len - 1; i++) {
            char curChar = local.charAt(i);
            char verifyChar = (char) (curChar + 1);
            if (curChar == 'z')
                verifyChar = 'a';
            char nextChar = local.charAt(i + 1);
            if (nextChar != verifyChar) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判斷是否為純數(shù)字
     * 
     * @param str
     *            伞矩,需要檢查的字符??
     */
    public static boolean isNumbericString(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }

        Pattern p = Pattern.compile("^[0-9]+$");// 從開頭到結尾必須全部為數(shù)??
        Matcher m = p.matcher(str);

        return m.find();
    }

    /**
     * 判斷是否為純字母
     * 
     * @param str
     * @return
     */
    public static boolean isAlphaBetaString(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }

        Pattern p = Pattern.compile("^[a-zA-Z]+$");// 從開頭到結尾必須全部為字母或者數(shù)??
        Matcher m = p.matcher(str);

        return m.find();
    }

    /**
     * 判斷是否為純字母或數(shù)??
     * 
     * @param str
     * @return
     */
    public static boolean isAlphaBetaNumbericString(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }

        Pattern p = Pattern.compile("^[a-zA-Z0-9]+$");// 從開頭到結尾必須全部為字母或者數(shù)??
        Matcher m = p.matcher(str);

        return m.find();
    }

    private static String regEx = "[\u4e00-\u9fa5]";
    private static Pattern pat = Pattern.compile(regEx);

    /**
     * 判斷是否包含中文
     * 
     * @param str
     * @return
     */
    public static boolean isContainsChinese(String str) {
        return pat.matcher(str).find();
    }

    public static boolean patternMatcher(String pattern, String input) {
        if (TextUtils.isEmpty(pattern) || TextUtils.isEmpty(input)) {
            return false;
        }
        Pattern pat = Pattern.compile(pattern);
        Matcher matcher = pat.matcher(input);

        return matcher.find();
    }

    /****************************************************************************/
    // import PPutils
    private static int id = 1;

    public static int getNextId() {
        return id++;
    }

    /**
     * 將輸入流轉為字節(jié)數(shù)組
     * 
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] read2Byte(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();

        return outSteam.toByteArray();
    }

    /**
     * 判斷是否符合月和年的過期時間規(guī)則
     * 
     * @param date
     * @return
     */
    public static boolean isMMYY(String date) {
        try {
            if (!TextUtils.isEmpty(date) && date.length() == 4) {
                int mm = Integer.parseInt(date.substring(0, 2));
                return mm > 0 && mm < 13;
            }

        } catch (Exception e) {
            Log.e(TAG, "Exception", e);
        }

        return false;
    }

    /**
     * 20120506 共八位,前四??-年夏志,中間兩位-月乃坤,??后兩??-??
     * 
     * @param date
     * @return
     */
    public static boolean isRealDate(String date, int yearlen) {
        // if(yearlen != 2 && yearlen != 4)
        // return false;
        int len = 4 + yearlen;
        if (date == null || date.length() != len)
            return false;

        if (!date.matches("[0-9]+"))
            return false;

        int year = Integer.parseInt(date.substring(0, yearlen));
        int month = Integer.parseInt(date.substring(yearlen, yearlen + 2));
        int day = Integer.parseInt(date.substring(yearlen + 2, yearlen + 4));

        if (year <= 0)
            return false;
        if (month <= 0 || month > 12)
            return false;
        if (day <= 0 || day > 31)
            return false;

        switch (month) {
        case 4:
        case 6:
        case 9:
        case 11:
            return day > 30 ? false : true;
        case 2:
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
                return day > 29 ? false : true;
            return day > 28 ? false : true;
        default:
            return true;
        }
    }

    /**
     * 判斷字符串是否為連續(xù)字符 abcdef 45678??
     */
    public static boolean isContinuousStr(String str) {
        if (TextUtils.isEmpty(str))
            return false;
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char curChar = str.charAt(i);
            char nextChar = (char) (curChar + 1);
            if (i + 1 < len) {
                nextChar = str.charAt(i + 1);
            }
            if (nextChar != (curChar + 1)) {
                return false;
            }
        }
        return true;
    }

    public static final String REGULAR_NUMBER = "(-?[0-9]+)(,[0-9]+)*(\\.[0-9]+)?";

    /**
     * 為字符串中的數(shù)字染顏??
     * 
     * @param str
     *            ,待處理的字符串
     * @param color
     *            ,需要染的顏??
     * @return
     */
    public static SpannableString setDigitalColor(String str, int color) {
        if (str == null)
            return null;
        SpannableString span = new SpannableString(str);

        Pattern p = Pattern.compile(REGULAR_NUMBER);
        Matcher m = p.matcher(str);
        while (m.find()) {
            int start = m.start();
            int end = start + m.group().length();
            span.setSpan(new ForegroundColorSpan(color), start, end,
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        return span;
    }

    public static boolean isChineseByREG(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("[\\u4E00-\\u9FBF]+");
        return pattern.matcher(str.trim()).find();
    }

    public static String getFixedNumber(String str, int length) {
        if (str == null || length <= 0 || str.length() < length) {
            return null;
        }
        Log.d(TAG, "getFixedNumber, str is : " + str);
        Pattern p = Pattern.compile("\\d{" + length + "}");
        Matcher m = p.matcher(str);
        String result = null;
        if (m.find()) {
            int start = m.start();
            int end = start + m.group().length();
            result = str.substring(start, end);
        }

        return result;
    }

    public static int getLengthWithoutSpace(CharSequence s) {
        int len = s.length();

        int rlen = 0;
        for (int i = 0; i < len; i++) {
            if (s.charAt(i) != ' ')
                rlen++;
        }

        return rlen;
    }

    /**
     * 獲取控件的寬度湿诊,如果獲取的高度為0狱杰,則重新計算尺寸后再返回高度
     * 
     * @param view
     * @return
     */
    public static int getViewMeasuredWidth(TextView view) {
        // int height = view.getMeasuredHeight();
        // if(0 < height){
        // return height;
        // }
        calcViewMeasure(view);
        return view.getMeasuredWidth();
    }

    /**
     * 獲取控件的高度,如果獲取的高度為0厅须,則重新計算尺寸后再返回高度
     * 
     * @param view
     * @return
     */
    public static int getViewMeasuredHeight(TextView view) {
        // int height = view.getMeasuredHeight();
        // if(0 < height){
        // return height;
        // }
        calcViewMeasure(view);
        return view.getMeasuredHeight();
    }

    /**
     * 測量控件的尺??
     * 
     * @param view
     */
    public static void calcViewMeasure(View view) {
        // int width =
        // View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        // int height =
        // View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        // view.measure(width,height);

        int width = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int expandSpec = View.MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
        view.measure(width, expandSpec);
    }

    public static String getDisDsrc(float dis) {
        if (dis <= 0) {
            return "";
        }
        String disStr = null;
        if (dis > 1000) {
            disStr = (float) Math.round(dis / 1000 * 10) / 10 + "km";
        } else {
            disStr = dis + "m";
        }
        return disStr;
    }
    public static boolean isValidDate(String str) {
        boolean convertSuccess = true;
        // 指定日期格式為四位年/兩位月份/兩位日期仿畸,注意yyyy/MM/dd區(qū)分大小寫;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        try {
            // 設置lenient為false.
            // 否則SimpleDateFormat會比較寬松地驗證日期朗和,比??2007/02/29會被接受错沽,并轉換??2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或???NullPointerException,就說明格式不對
            convertSuccess = false;
        }
        return convertSuccess;
    }
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末眶拉,一起剝皮案震驚了整個濱河市千埃,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌忆植,老刑警劉巖放可,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異唱逢,居然都是意外死亡吴侦,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門坞古,熙熙樓的掌柜王于貴愁眉苦臉地迎上來备韧,“玉大人,你說我怎么就攤上這事痪枫≈茫” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵奶陈,是天一觀的道長易阳。 經(jīng)常有香客問我,道長吃粒,這世上最難降的妖魔是什么潦俺? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮徐勃,結果婚禮上事示,老公的妹妹穿的比我還像新娘。我一直安慰自己僻肖,他們只是感情好肖爵,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著臀脏,像睡著了一般劝堪。 火紅的嫁衣襯著肌膚如雪冀自。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天秒啦,我揣著相機與錄音熬粗,去河邊找鬼。 笑死帝蒿,一個胖子當著我的面吹牛荐糜,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播葛超,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼暴氏,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了绣张?” 一聲冷哼從身側響起答渔,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎侥涵,沒想到半個月后沼撕,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡芜飘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年务豺,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嗦明。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡笼沥,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出娶牌,到底是詐尸還是另有隱情奔浅,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布诗良,位于F島的核電站汹桦,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏鉴裹。R本人自食惡果不足惜舞骆,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望径荔。 院中可真熱鬧督禽,春花似錦、人聲如沸猖凛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽辨泳。三九已至虱岂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間菠红,已是汗流浹背第岖。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留试溯,地道東北人蔑滓。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像遇绞,于是被迫代替她去往敵國和親键袱。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容

  • “思維導圖是表達發(fā)散性思維的有效圖形思維工具舵匾,是一種流行的全腦式學習方法俊抵。制作思維導圖的工具也有很多種,有免費的坐梯、...
    效率火箭閱讀 985評論 2 10
  • 久違的晴天徽诲,家長會。 家長大會開好到教室時烛缔,離放學已經(jīng)沒多少時間了馏段。班主任說已經(jīng)安排了三個家長分享經(jīng)驗。 放學鈴聲...
    飄雪兒5閱讀 7,523評論 16 22
  • 創(chuàng)業(yè)是很多人的夢想践瓷,多少人為了理想和不甘選擇了創(chuàng)業(yè)來實現(xiàn)自我價值院喜,我就是其中一個。 創(chuàng)業(yè)后晕翠,我由女人變成了超人喷舀,什...
    亦寶寶閱讀 1,812評論 4 1
  • 今天感恩節(jié)哎,感謝一直在我身邊的親朋好友淋肾。感恩相遇硫麻!感恩不離不棄。 中午開了第一次的黨會樊卓,身份的轉變要...
    迷月閃星情閱讀 10,567評論 0 11
  • 可愛進取拿愧,孤獨成精。努力飛翔碌尔,天堂翱翔浇辜。戰(zhàn)爭美好券敌,孤獨進取。膽大飛翔柳洋,成就輝煌待诅。努力進取,遙望熊镣,和諧家園卑雁。可愛游走...
    趙原野閱讀 2,727評論 1 1