一些在android開發中經常用的的代碼片段

撥打電話

1
2
3
public static void call(Context context, String phoneNumber) {
        context.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber)));
    }

跳轉至撥號界面

1
2
3
public static void callDial(Context context, String phoneNumber) {
        context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
    }

發送短信

1
2
3
4
5
6
7
8
public static void sendSms(Context context, String phoneNumber,
            String content) {
        Uri uri = Uri.parse("smsto:"
                + (TextUtils.isEmpty(phoneNumber) ? "" : phoneNumber));
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
        intent.putExtra("sms_body", TextUtils.isEmpty(content) ? "" : content);
        context.startActivity(intent);
    }

喚醒屏幕並解鎖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void wakeUpAndUnlock(Context context){ 
        KeyguardManager km= (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); 
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock"); 
        //解鎖 
        kl.disableKeyguard(); 
        //獲取電源管理器對象 
        PowerManager pm=(PowerManager) context.getSystemService(Context.POWER_SERVICE); 
        //獲取PowerManager.WakeLock對象,後面的參數|表示同時傳入兩個值,最後的是LogCat裏用的Tag 
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright"); 
        //點亮屏幕 
        wl.acquire(); 
        //釋放 
        wl.release(); 
    }

需要添加權限
1
2
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

判斷當前App處於前臺還是後臺狀態

1
2
3
4
5
6
7
8
9
10
11
12
13
public static boolean isApplicationBackground(final Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        @SuppressWarnings("deprecation")
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

需要添加權限
1
2
<uses-permission
     android:name="android.permission.GET_TASKS" />

判斷當前手機是否處於鎖屏(睡眠)狀態

1
2
3
4
5
6
public static boolean isSleeping(Context context) {
        KeyguardManager kgMgr = (KeyguardManager) context
                .getSystemService(Context.KEYGUARD_SERVICE);
        boolean isSleeping = kgMgr.inKeyguardRestrictedInputMode();
        return isSleeping;
    }

判斷當前是否有網絡連接

1
2
3
4
5
6
7
8
9
public static boolean isOnline(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            return true;
        }
        return false;
    }

判斷當前是否是WIFI連接狀態

1
2
3
4
5
6
7
8
9
10
public static boolean isWifiConnected(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifiNetworkInfo = connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetworkInfo.isConnected()) {
        return true;
    }
    return false;
}

安裝APK

1
2
3
4
5
6
7
8
9
10
public static void installApk(Context context, File file) {
    Intent intent = new Intent();
    intent.setAction("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.setType("application/vnd.android.package-archive");
    intent.setDataAndType(Uri.fromFile(file),
            "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

判斷當前設備是否爲手機

1
2
3
4
5
6
7
8
9
public static boolean isPhone(Context context) {
    TelephonyManager telephony = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
        return false;
    else {
        return true;
    }
}

獲取當前設備寬高,單位px

1
2
3
4
5
6
7
8
9
10
11
12
13
@SuppressWarnings("deprecation")
public static int getDeviceWidth(Context context) {
    WindowManager manager = (WindowManager) context
            .getSystemService(Context.WINDOW_SERVICE);
    return manager.getDefaultDisplay().getWidth();
}
 
@SuppressWarnings("deprecation")
public static int getDeviceHeight(Context context) {
    WindowManager manager = (WindowManager) context
            .getSystemService(Context.WINDOW_SERVICE);
    return manager.getDefaultDisplay().getHeight();
}

獲取當前設備的IMEI,需要與上面的isPhone()一起使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@TargetApi(Build.VERSION_CODES.CUPCAKE)
public static String getDeviceIMEI(Context context) {
    String deviceId;
    if (isPhone(context)) {
        TelephonyManager telephony = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        deviceId = telephony.getDeviceId();
    else {
        deviceId = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.ANDROID_ID);
 
    }
    return deviceId;
}

獲取當前設備的MAC地址

1
2
3
4
5
6
7
8
9
10
11
12
public static String getMacAddress(Context context) {
    String macAddress;
    WifiManager wifi = (WifiManager) context
            .getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifi.getConnectionInfo();
    macAddress = info.getMacAddress();
    if (null == macAddress) {
        return "";
    }
    macAddress = macAddress.replace(":""");
    return macAddress;
}

獲取當前程序的版本號

1
2
3
4
5
6
7
8
9
10
public static String getAppVersion(Context context) {
    String version = "0";
    try {
        version = context.getPackageManager().getPackageInfo(
                context.getPackageName(), 0).versionName;
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return version;
}

收集設備信息,用於信息統計分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public static Properties collectDeviceInfo(Context context) {
        Properties mDeviceCrashInfo = new Properties();
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                mDeviceCrashInfo.put(VERSION_NAME,
                        pi.versionName == null "not set" : pi.versionName);
                mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode);
            }
        catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Error while collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                mDeviceCrashInfo.put(field.getName(), field.get(null));
            catch (Exception e) {
                Log.e(TAG, "Error while collect crash info", e);
            }
        }
 
        return mDeviceCrashInfo;
    }
 
public static String collectDeviceInfoStr(Context context) {
        Properties prop = collectDeviceInfo(context);
        Set deviceInfos = prop.keySet();
        StringBuilder deviceInfoStr = new StringBuilder("{\n");
        for (Iterator iter = deviceInfos.iterator(); iter.hasNext();) {
            Object item = iter.next();
            deviceInfoStr.append("\t\t\t" + item + ":" + prop.get(item)
                    ", \n");
        }
        deviceInfoStr.append("}");
        return deviceInfoStr.toString();
    }

是否有SD卡

1
2
3
4
public static boolean haveSDCard() {
        return android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
    }

動態隱藏軟鍵盤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@TargetApi(Build.VERSION_CODES.CUPCAKE)
    public static void hideSoftInput(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
 
    @TargetApi(Build.VERSION_CODES.CUPCAKE)
public static void hideSoftInput(Context context, EditText edit) {
        edit.clearFocus();
        InputMethodManager inputmanger = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanger.hideSoftInputFromWindow(edit.getWindowToken(), 0);
    }

動態顯示軟鍵盤

1
2
3
4
5
6
7
8
9
@TargetApi(Build.VERSION_CODES.CUPCAKE)
public static void showSoftInput(Context context, EditText edit) {
        edit.setFocusable(true);
        edit.setFocusableInTouchMode(true);
        edit.requestFocus();
        InputMethodManager inputManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(edit, 0);
    }

動態顯示或者是隱藏軟鍵盤

1
2
3
4
5
6
7
8
9
@TargetApi(Build.VERSION_CODES.CUPCAKE)
public static void toggleSoftInput(Context context, EditText edit) {
        edit.setFocusable(true);
        edit.setFocusableInTouchMode(true);
        edit.requestFocus();
        InputMethodManager inputManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }

主動回到Home,後臺運行

1
2
3
4
5
6
7
public static void goHome(Context context) {
        Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        context.startActivity(mHomeIntent);
    }

獲取狀態欄高度

注意,要在onWindowFocusChanged中調用,在onCreate中獲取高度爲0

1
2
3
4
5
6
@TargetApi(Build.VERSION_CODES.CUPCAKE)
public static int getStatusBarHeight(Activity activity) {
    Rect frame = new Rect();
    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        return frame.top;
    }

獲取狀態欄高度+標題欄(ActionBar)高度

(注意,如果沒有ActionBar,那麼獲取的高度將和上面的是一樣的,只有狀態欄的高度)

1
2
3
4
public static int getTopBarHeight(Activity activity) {
        return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT)
                .getTop();
    }

獲取MCC+MNC代碼 (SIM卡運營商國家代碼和運營商網絡代碼)

僅當用戶已在網絡註冊時有效, CDMA 可能會無效(中國移動:46000 46002, 中國聯通:46001,中國電信:46003)

1
2
3
4
5
public static String getNetworkOperator(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getNetworkOperator();
    }

返回移動網絡運營商的名字

(例:中國聯通、中國移動、中國電信) 僅當用戶已在網絡註冊時有效, CDMA 可能會無效)

1
2
3
4
5
public static String getNetworkOperatorName(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getNetworkOperatorName();
    }

返回移動終端類型

  1. PHONE_TYPE_NONE :0 手機制式未知
  2. PHONE_TYPE_GSM :1 手機制式爲GSM,移動和聯通
  3. PHONE_TYPE_CDMA :2 手機制式爲CDMA,電信
  4. PHONE_TYPE_SIP:3
1
2
3
4
5
public static int getPhoneType(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getPhoneType();
    }

判斷手機連接的網絡類型(2G,3G,4G)

聯通的3G爲UMTS或HSDPA,移動和聯通的2G爲GPRS或EGDE,電信的2G爲CDMA,電信的3G爲EVDO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class Constants {
    /**
     * Unknown network class
     */
    public static final int NETWORK_CLASS_UNKNOWN = 0;
 
    /**
     * wifi net work
     */
    public static final int NETWORK_WIFI = 1;
 
    /**
     * "2G" networks
     */
    public static final int NETWORK_CLASS_2_G = 2;
 
    /**
     * "3G" networks
     */
    public static final int NETWORK_CLASS_3_G = 3;
 
    /**
     * "4G" networks
     */
    public static final int NETWORK_CLASS_4_G = 4;
 
}
 
public static int getNetWorkClass(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
 
        switch (telephonyManager.getNetworkType()) {
        case TelephonyManager.NETWORK_TYPE_GPRS:
        case TelephonyManager.NETWORK_TYPE_EDGE:
        case TelephonyManager.NETWORK_TYPE_CDMA:
        case TelephonyManager.NETWORK_TYPE_1xRTT:
        case TelephonyManager.NETWORK_TYPE_IDEN:
            return Constants.NETWORK_CLASS_2_G;
 
        case TelephonyManager.NETWORK_TYPE_UMTS:
        case TelephonyManager.NETWORK_TYPE_EVDO_0:
        case TelephonyManager.NETWORK_TYPE_EVDO_A:
        case TelephonyManager.NETWORK_TYPE_HSDPA:
        case TelephonyManager.NETWORK_TYPE_HSUPA:
        case TelephonyManager.NETWORK_TYPE_HSPA:
        case TelephonyManager.NETWORK_TYPE_EVDO_B:
        case TelephonyManager.NETWORK_TYPE_EHRPD:
        case TelephonyManager.NETWORK_TYPE_HSPAP:
            return Constants.NETWORK_CLASS_3_G;
 
        case TelephonyManager.NETWORK_TYPE_LTE:
            return Constants.NETWORK_CLASS_4_G;
 
        default:
            return Constants.NETWORK_CLASS_UNKNOWN;
        }
    }

判斷當前手機的網絡類型(WIFI還是2,3,4G)

需要用到上面的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static int getNetWorkStatus(Context context) {
        int netWorkType = Constants.NETWORK_CLASS_UNKNOWN;
 
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
 
        if (networkInfo != null && networkInfo.isConnected()) {
            int type = networkInfo.getType();
 
            if (type == ConnectivityManager.TYPE_WIFI) {
                netWorkType = Constants.NETWORK_WIFI;
            else if (type == ConnectivityManager.TYPE_MOBILE) {
                netWorkType = getNetWorkClass(context);
            }
        }
 
        return netWorkType;
    }

px-dp轉換

1
2
3
4
5
6
7
8
9
public static int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}
 
public static int px2dip(Context context, float pxValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pxValue / scale + 0.5f);
}

px-sp轉換

1
2
3
4
5
6
7
8
9
public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }
 
public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

把一個毫秒數轉化成時間字符串

格式爲小時/分/秒/毫秒(如:24903600 –> 06小時55分03秒600毫秒)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
     * @param millis
     *            要轉化的毫秒數。
     * @param isWhole
     *            是否強制全部顯示小時/分/秒/毫秒。
     * @param isFormat
     *            時間數字是否要格式化,如果true:少位數前面補全;如果false:少位數前面不補全。
     * @return 返回時間字符串:小時/分/秒/毫秒的格式(如:24903600 --> 06小時55分03秒600毫秒)。
     */
    public static String millisToString(long millis, boolean isWhole,
            boolean isFormat) {
        String h = "";
        String m = "";
        String s = "";
        String mi = "";
        if (isWhole) {
            h = isFormat ? "00小時" "0小時";
            m = isFormat ? "00分" "0分";
            s = isFormat ? "00秒" "0秒";
            mi = isFormat ? "00毫秒" "0毫秒";
        }
 
        long temp = millis;
 
        long hper = 60 60 1000;
        long mper = 60 1000;
        long sper = 1000;
 
        if (temp / hper > 0) {
            if (isFormat) {
                h = temp / hper < 10 "0" + temp / hper : temp / hper + "";
            else {
                h = temp / hper + "";
            }
            h += "小時";
        }
        temp = temp % hper;
 
        if (temp / mper > 0) {
            if (isFormat) {
                m = temp / mper < 10 "0" + temp / mper : temp / mper + "";
            else {
                m = temp / mper + "";
            }
            m += "分";
        }
        temp = temp % mper;
 
        if (temp / sper > 0) {
            if (isFormat) {
                s = temp / sper < 10 "0" + temp / sper : temp / sper + "";
            else {
                s = temp / sper + "";
            }
            s += "秒";
        }
        temp = temp % sper;
        mi = temp + "";
 
        if (isFormat) {
            if (temp < 100 && temp >= 10) {
                mi = "0" + temp;
            }
            if (temp < 10) {
                mi = "00" + temp;
            }
        }
 
        mi += "毫秒";
        return h + m + s + mi;
    }

格式爲小時/分/秒/毫秒(如:24903600 –> 06小時55分03秒)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
     *
     * @param millis
     *            要轉化的毫秒數。
     * @param isWhole
     *            是否強制全部顯示小時/分/秒/毫秒。
     * @param isFormat
     *            時間數字是否要格式化,如果true:少位數前面補全;如果false:少位數前面不補全。
     * @return 返回時間字符串:小時/分/秒/毫秒的格式(如:24903600 --> 06小時55分03秒)。
     */
    public static String millisToStringMiddle(long millis, boolean isWhole,
            boolean isFormat) {
        return millisToStringMiddle(millis, isWhole, isFormat, "小時""分鐘""秒");
    }
 
    public static String millisToStringMiddle(long millis, boolean isWhole,
            boolean isFormat, String hUnit, String mUnit, String sUnit) {
        String h = "";
        String m = "";
        String s = "";
        if (isWhole) {
            h = isFormat ? "00" + hUnit : "0" + hUnit;
            m = isFormat ? "00" + mUnit : "0" + mUnit;
            s = isFormat ? "00" + sUnit : "0" + sUnit;
        }
 
        long temp = millis;
 
        long hper = 60 60 1000;
        long mper = 60 1000;
        long sper = 1000;
 
        if (temp / hper > 0) {
            if (isFormat) {
                h = temp / hper < 10 "0" + temp / hper : temp / hper + "";
            else {
                h = temp / hper + "";
            }
            h += hUnit;
        }
        temp = temp % hper;
 
        if (temp / mper > 0) {
            if (isFormat) {
                m = temp / mper < 10 "0" + temp / mper : temp / mper + "";
            else {
                m = temp / mper + "";
            }
            m += mUnit;
        }
        temp = temp % mper;
 
        if (temp / sper > 0) {
            if (isFormat) {
                s = temp / sper < 10 "0" + temp / sper : temp / sper + "";
            else {
                s = temp / sper + "";
            }
            s += sUnit;
        }
        return h + m + s;
    }

把一個毫秒數轉化成時間字符串。格式爲小時/分/秒/毫秒(如:24903600 –> 06小時55分鐘)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
     *
     * @param millis
     *            要轉化的毫秒數。
     * @param isWhole
     *            是否強制全部顯示小時/分。
     * @param isFormat
     *            時間數字是否要格式化,如果true:少位數前面補全;如果false:少位數前面不補全。
     * @return 返回時間字符串:小時/分/秒/毫秒的格式(如:24903600 --> 06小時55分鐘)。
     */
    public static String millisToStringShort(long millis, boolean isWhole,
            boolean isFormat) {
        String h = "";
        String m = "";
        if (isWhole) {
            h = isFormat ? "00小時" "0小時";
            m = isFormat ? "00分鐘" "0分鐘";
        }
 
        long temp = millis;
 
        long hper = 60 60 1000;
        long mper = 60 1000;
        long sper = 1000;
 
        if (temp / hper > 0) {
            if (isFormat) {
                h = temp / hper < 10 "0" + temp / hper : temp / hper + "";
            else {
                h = temp / hper + "";
            }
            h += "小時";
        }
        temp = temp % hper;
 
        if (temp / mper > 0) {
            if (isFormat) {
                m = temp / mper < 10 "0" + temp / mper : temp / mper + "";
            else {
                m = temp / mper + "";
            }
            m += "分鐘";
        }
 
        return h + m;
    }

把日期毫秒轉化爲字符串

1
2
3
4
5
6
7
8
9
10
11
12
/**
     * @param millis
     *            要轉化的日期毫秒數。
     * @param pattern
     *            要轉化爲的字符串格式(如:yyyy-MM-dd HH:mm:ss)。
     * @return 返回日期字符串。
     */
    public static String millisToStringDate(long millis, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern,
                Locale.getDefault());
        return format.format(new Date(millis));
    }

把日期毫秒轉化爲字符串(文件名)

1
2
3
4
5
6
7
8
9
10
11
/**
     * @param millis
     *            要轉化的日期毫秒數。
     * @param pattern
     *            要轉化爲的字符串格式(如:yyyy-MM-dd HH:mm:ss)。
     * @return 返回日期字符串(yyyy_MM_dd_HH_mm_ss)。
     */
    public static String millisToStringFilename(long millis, String pattern) {
        String dateStr = millisToStringDate(millis, pattern);
        return dateStr.replaceAll("[- :]""_");
    }

轉換當前時間爲易用時間格式

1小時內用,多少分鐘前; 超過1小時,顯示時間而無日期; 如果是昨天,則顯示昨天 超過昨天再顯示日期; 超過1年再顯示年。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public static long oneHourMillis = 60 60 1000// 一小時的毫秒數
public static long oneDayMillis = 24 * oneHourMillis; // 一天的毫秒數
public static long oneYearMillis = 365 * oneDayMillis; // 一年的毫秒數
 
public static String millisToLifeString(long millis) {
        long now = System.currentTimeMillis();
        long todayStart = string2Millis(millisToStringDate(now, "yyyy-MM-dd"),
                "yyyy-MM-dd");
 
        // 一小時內
        if (now - millis <= oneHourMillis && now - millis > 0l) {
            String m = millisToStringShort(now - millis, falsefalse);
            return "".equals(m) ? "1分鐘內" : m + "前";
        }
 
         // 大於今天開始開始值,小於今天開始值加一天(即今天結束值)
        if (millis >= todayStart && millis <= oneDayMillis + todayStart) {
            return "今天 " + millisToStringDate(millis, "HH:mm");
        }
 
         // 大於(今天開始值減一天,即昨天開始值)
        if (millis > todayStart - oneDayMillis) {
            return "昨天 " + millisToStringDate(millis, "HH:mm");
        }
 
        long thisYearStart = string2Millis(millisToStringDate(now, "yyyy"),
                "yyyy");
         // 大於今天小於今年
        if (millis > thisYearStart) {
            return millisToStringDate(millis, "MM月dd日 HH:mm");
        }
 
        return millisToStringDate(millis, "yyyy年MM月dd日 HH:mm");
    }

字符串解析成毫秒數

1
2
3
4
5
6
7
8
9
10
11
public static long string2Millis(String str, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern,
                Locale.getDefault());
        long millis = 0;
        try {
            millis = format.parse(str).getTime();
        catch (ParseException e) {
            Log.e("TAG", e.getMessage());
        }
        return millis;
    }

手機號碼正則

1
public static final String REG_PHONE_CHINA = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";

郵箱正則

1
public static final String REG_EMAIL = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章