Android工具類整合教程
Android-JSONUtil工具類
常用的Json工具類,包含Json轉(zhuǎn)換成實體、實體轉(zhuǎn)json字符串、list集合轉(zhuǎn)換成json、數(shù)組轉(zhuǎn)換成json
public class JSONUtil { private static final String TAG = JSONUtil.class.getSimpleName(); private JSONUtil(){} private static Gson gson = new Gson(); /** * 傳入一個頭部,獲取頭部管控中的所有String信息 * @return */ public static String getHeadContext(String jsonData, String head) { String jsonObjectString = null; try { JSONObject jsonObject = new JSONObject(jsonData); jsonObjectString = jsonObject.get(head).toString(); // LogUtil.d(TAG, "getHeadContext 只去頭部header的數(shù)據(jù)信息:" + jsonObjectString); } catch (Exception e) { e.printStackTrace(); } return jsonObjectString; } /** * 將一個對象轉(zhuǎn)換成一個Json字符串 * @param t * @return */ public static <T> String objectToJson(T t){ if (t instanceof String) { return t.toString(); } else { return gson.toJson(t); } } /** * 將Json字符串轉(zhuǎn)換成對應(yīng)對象 * @param jsonString Json字符串 * @param clazz 對應(yīng)字節(jié)碼文件.class * @return */ @SuppressWarnings("unchecked") public static<T> T jsonToObject(String jsonString, Class<T> clazz){ if (clazz == String.class) { return (T) jsonString; } else { return (T)gson.fromJson(jsonString, clazz); } } /** * 將List集合轉(zhuǎn)換為json字符串 * @param list List集合 * @return */ public static<T> String listToJson(List<T> list){ JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = null; try { for (int i = 0; i < list.size(); i++) { jsonObject = new JSONObject(objectToJson(list.get(i))); jsonArray.put(jsonObject); } } catch (JSONException e) { e.printStackTrace(); } finally { if (jsonObject != null) { jsonObject = null; } } return jsonArray.toString(); } /** * 將數(shù)組轉(zhuǎn)換成json字符串 * @param array 數(shù)組 * @return */ public static<T> String arrayToJson(T[] array){ JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = null; try { for (int i = 0; i < array.length; i++) { jsonObject = new JSONObject(objectToJson(array[i])); jsonArray.put(jsonObject); } } catch (JSONException e) { e.printStackTrace(); } finally { if (jsonObject != null) { jsonObject = null; } } return jsonArray.toString(); } /** * 獲取json字符串中的值 * @param json json字符串 * @param key 鍵值 * @param clazz 所取數(shù)據(jù)類型,例如:Integer.class,String.class,Double.class,JSONObject.class * @return 存在則返回正確值,不存在返回null */ public static<T> T getJsonObjectValue(String json, String key, Class<T> clazz){ try { return getJsonObjectValue(new JSONObject(json), key, clazz); } catch (JSONException e) { e.printStackTrace(); } return null; } /** * 獲取jsonObject對象中的值 * @param jsonObject jsonObject對象 * @param key 鍵值 * @param clazz 所取數(shù)據(jù)類型,例如:Integer.class,String.class,Double.class,JSONObject.class * @return 存在則返回正確值,不存在返回null */ @SuppressWarnings("unchecked") public static<T> T getJsonObjectValue(JSONObject jsonObject, String key, Class<T> clazz){ T t = null; try { if (clazz == Integer.class) { t = (T) Integer.valueOf(jsonObject.getInt(key)); }else if(clazz == Boolean.class){ t = (T) Boolean.valueOf(jsonObject.getBoolean(key)); }else if(clazz == String.class){ t = (T) String.valueOf(jsonObject.getString(key)); }else if(clazz == Double.class){ t = (T) Double.valueOf(jsonObject.getDouble(key)); }else if(clazz == JSONObject.class){ t = (T) jsonObject.getJSONObject(key); }else if(clazz == JSONArray.class){ t = (T) jsonObject.getJSONArray(key); }else if(clazz == Long.class){ t = (T) Long.valueOf(jsonObject.getLong(key)); } } catch (JSONException e) { e.printStackTrace(); } return t; } /** * json字符串轉(zhuǎn)換為ContentValues * @param json json字符串 * @return */ @SuppressWarnings("rawtypes") public static ContentValues jsonToContentValues(String json){ ContentValues contentValues = new ContentValues(); try { JSONObject jsonObject = new JSONObject(json); Iterator iterator = jsonObject.keys(); String key; Object value; while (iterator.hasNext()) { key = iterator.next().toString(); value = jsonObject.get(key); String valueString = value.toString(); if (value instanceof String) { contentValues.put(key, valueString); }else if(value instanceof Integer){ contentValues.put(key, Integer.valueOf(valueString)); }else if(value instanceof Long){ contentValues.put(key, Long.valueOf(valueString)); }else if(value instanceof Double){ contentValues.put(key, Double.valueOf(valueString)); }else if(value instanceof Float){ contentValues.put(key, Float.valueOf(valueString)); }else if(value instanceof Boolean){ contentValues.put(key, Boolean.valueOf(valueString)); } } } catch (JSONException e) { e.printStackTrace(); throw new Error("Json字符串不合法:" + json); } return contentValues; } }
Android-LogUtil工具類
Log日志級別打印相關(guān)工具類
public class LogUtil { private LogUtil(){} /** * 打印的信息日志信息 */ private final static String INFO = "??????????????????????????: "; /** * 打印的錯誤日志信息 */ private final static String ERROR = "??????????????????????????: "; /** * 打印的調(diào)試日志信息 */ private final static String DEBUG = "???????????????: "; /** * 打印的全面日志信息 */ private final static String VERBOSE = "▂▂▂▃▃▄▄▅▅▆▆▆▇▇: "; /** * 打印的警告日志信息 */ private final static String WARN = "!!!!!!!!!!!!!!!!!!!!!!!!!!: "; /** * 打印information日志 * @param tag 標簽 * @param msg 日志信息 */ public static void i(String tag,String msg){ Log.i(tag, INFO + msg); } /** * 打印information日志 * @param tag 標簽 * @param msg 日志信息 * @param throwable 異常 */ public static void i(String tag, String msg, Throwable throwable){ Log.i(tag, INFO + msg, throwable); } /** * 打印verbose日志 * @param tag 標簽 * @param msg 日志信息 */ public static void v(String tag, String msg){ Log.v(tag, VERBOSE + msg); } /** * 打印verbose日志 * @param tag 標簽 * @param msg 日志信息 * @param throwable 異常 */ public static void v(String tag, String msg, Throwable throwable){ Log.v(tag, VERBOSE + msg, throwable); } /** * 打印debug信息 * @param tag 標簽信息 * @param msg 日志信息 */ public static void d(String tag, String msg){ Log.d(tag, DEBUG + msg); } /** * 打印debug日志 * @param tag 標簽信息 * @param msg 日志信息 * @param throwable 異常 */ public static void d(String tag, String msg, Throwable throwable){ Log.d(tag, DEBUG + msg, throwable); } /** * 打印warn日志 * @param tag 標簽信息 * @param msg 日志信息 */ public static void w(String tag, String msg){ Log.w(tag, WARN + msg); } /** * 打印warn日志 * @param tag 標簽信息 * @param msg 日志信息 * @param throwable 異常 */ public static void w(String tag, String msg, Throwable throwable){ Log.w(tag, WARN + msg, throwable); } /** * 打印error日志 * @param tag * @param msg 標簽 */ public static void e(String tag, String msg){ Log.e(tag, ERROR + msg); } /** * 打印error日志 * @param tag 標簽 * @param msg 日志信息 * @param throwable 異常 */ public static void e(String tag, String msg, Throwable throwable){ Log.e(tag, ERROR + msg, throwable); } /** * 吐司提示 * @param msg */ public static void toast(Context mContext, String msg) { Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show(); } /** * 吐司提示 long類型 * @param msg */ public static void toastL(Context mContext, String msg) { Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show(); } /** * 吐司提示 自定義時間類型 * @param msg */ public static void toastD(Context mContext, String msg, int duration) { Toast.makeText(mContext, msg, duration).show(); } }
Android-MD5Util工具類
MD5 字符串加密 ,文件加密相關(guān)工具類
public class MD5Util { private static final String TAG = "MD5Util"; /** * 默認的密碼字符串組合,用來將字節(jié)轉(zhuǎn)換成 16 進制表示的字符,apache校驗下載的文件的正確性用的就是默認的這個組合 */ protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; protected static MessageDigest messagedigest = null; static { try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsaex) { ELog.e(TAG, MD5Util.class.getName() + "init failed ,MessageDigest un support MD5Util。"); nsaex.printStackTrace(); } } /** * 生成字符串的md5校驗值 * @param s * @return */ public static String getMD5String(String s) { return getMD5String(s.getBytes()); } /** * 生成字符串的md5校驗值 16位 * @param s * @return */ public static String getMD5String16(String s) { return getMD5String(s.getBytes()).substring(8, 24); } /** * 判斷字符串的md5校驗碼是否與一個已知的md5碼相匹配 * @param password 要校驗的字符串 * @param md5PwdStr 已知的md5校驗碼 * @return */ public static boolean checkPassword(String password, String md5PwdStr) { String s = getMD5String(password); return s.equals(md5PwdStr); } /** * 生成文件的md5校驗值 * @param file * @return * @throws IOException */ public static String getFileMD5String(File file) throws IOException { InputStream fis; fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int numRead = 0; while ((numRead = fis.read(buffer)) > 0) { messagedigest.update(buffer, 0, numRead); } fis.close(); return bufferToHex(messagedigest.digest()); } public static String getMD5String(byte[] bytes) { messagedigest.update(bytes); return bufferToHex(messagedigest.digest()); } private static String bufferToHex(byte bytes[]) { return bufferToHex(bytes, 0, bytes.length); } private static String bufferToHex(byte bytes[], int m, int n) { StringBuffer stringbuffer = new StringBuffer(2 * n); int k = m + n; for (int l = m; l < k; l++) { appendHexPair(bytes[l], stringbuffer); } return stringbuffer.toString(); } private static void appendHexPair(byte bt, StringBuffer stringbuffer) { char c0 = hexDigits[(bt & 0xf0) >> 4]; // 取字節(jié)中高 4 位的數(shù)字轉(zhuǎn)換, >>> 為邏輯右移,將符號位一起右移,此處未發(fā)現(xiàn)兩種符號有何不同 char c1 = hexDigits[bt & 0xf]; // 取字節(jié)中低 4 位的數(shù)字轉(zhuǎn)換 stringbuffer.append(c0); stringbuffer.append(c1); } /** * 自測方法 * @param args */ public static void main(String[] args) { System.out.println(getMD5String("test")); } }
Android-MeasureUtil工具類
常用測量相關(guān)的工具類:
public class MeasureUtil { private MeasureUtil(){} /** * 獲取控件的測量高度 * @param view 控件 * @return 返回測量高度(MeasuredHeight) */ public static int getMeasuredHeight(View view) { if (view == null) { throw new IllegalArgumentException("view is null"); } view.measure(0, 0); return view.getMeasuredHeight(); } /** * 控件的高度 * @param view 控件View * @return 返回控件的高度 */ public static int getHeight(View view){ if(view == null){ throw new IllegalArgumentException("view is null"); } view.measure(0, 0); return view.getHeight(); } /** * 獲取控件的測量寬度 * @param view 控件 * @return 返回控件的測量寬度 */ public static int getMeasuredWidth(View view){ if(view == null){ throw new IllegalArgumentException("view is null"); } view.measure(0, 0); return view.getMeasuredWidth(); } /** * 獲取控件的寬度 * @param view 控件 * @return 返回控件的寬度 */ public static int getWidth(View view){ if(view == null){ throw new IllegalArgumentException("view is null"); } view.measure(0, 0); return view.getWidth(); } /** * 設(shè)置高度 * @param view 控件 * @param height 高度 */ public static void setHeight(View view, int height) { if (view == null || view.getLayoutParams() == null) { throw new IllegalArgumentException("View LayoutParams is null"); } ViewGroup.LayoutParams params = view.getLayoutParams(); params.height = height; view.setLayoutParams(params); } /** * 設(shè)置View的寬度 * @param view view * @param width 寬度 */ public static void setWidth(View view, int width){ if(view == null || view.getLayoutParams() == null){ throw new IllegalArgumentException("View LayoutParams is null"); } ViewGroup.LayoutParams params = view.getLayoutParams(); params.width = width; view.setLayoutParams(params); } /** * 設(shè)置ListView的實際高度 * @param listView ListView控件 */ public static void setListHeight(ListView listView) { if (listView == null) { throw new IllegalArgumentException("ListView is null"); } Adapter adapter = listView.getAdapter(); if (adapter == null) { return; } int totalHeight = 0; int size = adapter.getCount(); for (int i = 0; i < size; i++) { View listItem = adapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (size - 1)); LogUtil.d("MeasureUtil", "listview-height--" + params.height); listView.setLayoutParams(params); } /** * 設(shè)置GridView的高度, * @param context 應(yīng)用程序上下文 * @param gv GridView控件 * @param n 行數(shù) * @param m 列數(shù) */ public static void setGridViewHeight(Context context, GridView gv, int n, int m) { if(gv == null){ throw new IllegalArgumentException("GridView is null"); } Adapter adapter = gv.getAdapter(); if (adapter == null) { return; } int totalHeight = 0; int size = adapter.getCount(); for (int i = 0; i < size; i++) { View listItem = adapter.getView(i, null, gv); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight() + ScreenUtil.dp2px(context, m); } ViewGroup.LayoutParams params = gv.getLayoutParams(); params.height = totalHeight + gv.getPaddingTop() + gv.getPaddingBottom() + 2; LogUtil.d("MeasureUtil", "gridview-height--" + params.height); gv.setLayoutParams(params); } }
Android-NetworkUtils工具類
網(wǎng)絡(luò)類型,網(wǎng)絡(luò)狀態(tài),網(wǎng)絡(luò)制式,等相關(guān)工具類
public final class NetworkUtils { private NetworkUtils() { throw new AssertionError(); } /** * 未找到合適匹配網(wǎng)絡(luò)類型 */ public static final int TYPE_NO = 0; /** * 中國移動CMNET網(wǎng)絡(luò) * 中國移動GPRS接入方式之一, 主要為PC、筆記本電腦、PDA設(shè)立 */ public static final int TYPE_MOBILE_CMNET = 1; /** * 中國移動CMWAP網(wǎng)絡(luò) * 中國移動GPRS接入方式之一,主要為手機WAP上網(wǎng)而設(shè)立 */ public static final int TYPE_MOBILE_CMWAP = 2; /** * 中國聯(lián)通UNIWAP網(wǎng)絡(luò) * 中國聯(lián)通劃分GPRS接入方式之一, 主要為手機WAP上網(wǎng)而設(shè)立 */ public static final int TYPE_MOBILE_UNIWAP = 3; /** * 中國聯(lián)通UNINET網(wǎng)絡(luò) * 中國聯(lián)通劃分GPRS接入方式之一, 主要為PC、筆記本電腦、PDA設(shè)立 */ public static final int TYPE_MOBILE_UNINET = 6; /** * 中國聯(lián)通3GWAP網(wǎng)絡(luò) */ public static final int TYPE_MOBILE_3GWAP = 4; // 中國聯(lián)通3HNET網(wǎng)絡(luò) public static final int TYPE_MOBLIE_3GNET = 5; /** * 中國電信CTWAP網(wǎng)絡(luò) */ public static final int TYPE_MOBILE_CTWAP = 7; /** * 中國電信CTNET網(wǎng)絡(luò) */ public static final int TYPE_MOBILE_CTNET = 8; /** * WIFI網(wǎng)絡(luò) */ public static final int TYPE_WIFI = 10; /** * 網(wǎng)絡(luò)類型 - 無連接 */ public static final int NETWORK_TYPE_NO_CONNECTION = -100000; /** * 連接模式WIFI網(wǎng) */ public static final String NETWORK_TYPE_WIFI = "WIFI"; /** * 連接模式快速網(wǎng) */ public static final String NETWORK_TYPE_FAST = "FAST"; /** * 連接模式慢速網(wǎng) */ public static final String NETWORK_TYPE_SLOW = "SLOW"; /** * 連接模式wap網(wǎng) */ public static final String NETWORK_TYPE_WAP = "WAP"; /** * 連接模式unknow */ public static final String NETWORK_TYPE_UNKNOWN = "UNKNOWN"; /** * 無連接 */ public static final String NETWORK_TYPE_DISCONNECT = "DISCONNECT"; /** * 獲取當前手機連接的網(wǎng)絡(luò)類型 * * @param context 上下文 * @return int 網(wǎng)絡(luò)類型 */ public static int getNetworkState(Context context) { int returnValue = TYPE_NO; // 獲取ConnectivityManager對象 ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // 獲得當前網(wǎng)絡(luò)信息 NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isAvailable()) { // 獲取網(wǎng)絡(luò)類型 int currentNetWork = networkInfo.getType(); // 手機網(wǎng)絡(luò)類型 if (currentNetWork == ConnectivityManager.TYPE_MOBILE) { if (networkInfo.getExtraInfo() != null) { if (networkInfo.getExtraInfo().equals("cmnet")) { returnValue = TYPE_MOBILE_CMNET; } if (networkInfo.getExtraInfo().equals("cmwap")) { returnValue = TYPE_MOBILE_CMWAP; } if (networkInfo.getExtraInfo().equals("uniwap")) { returnValue = TYPE_MOBILE_UNIWAP; } if (networkInfo.getExtraInfo().equals("3gwap")) { returnValue = TYPE_MOBILE_3GWAP; } if (networkInfo.getExtraInfo().equals("3gnet")) { returnValue = TYPE_MOBLIE_3GNET; } if (networkInfo.getExtraInfo().equals("uninet")) { returnValue = TYPE_MOBILE_UNINET; } if (networkInfo.getExtraInfo().equals("ctwap")) { returnValue = TYPE_MOBILE_CTWAP; } if (networkInfo.getExtraInfo().equals("ctnet")) { returnValue = TYPE_MOBILE_CTNET; } } // WIFI網(wǎng)絡(luò)類型 } else if (currentNetWork == ConnectivityManager.TYPE_WIFI) { returnValue = TYPE_WIFI; } } return returnValue; } /** * 判斷網(wǎng)絡(luò)是否連接 * * @param context 上下文 * @return boolean 網(wǎng)絡(luò)連接狀態(tài) */ public static boolean isNetworkConnected(Context context) { if (context != null) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); // 獲取連接對象 if (null != info && info.isConnected()) { return info.getState() == State.CONNECTED; } } return false; } /** * 打開網(wǎng)絡(luò)設(shè)置界面 * * @param activity Activity */ public static void openNetSetting(Activity activity) { Intent intent = new Intent("/"); ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings"); intent.setComponent(cm); intent.setAction("android.intent.action.VIEW"); activity.startActivityForResult(intent, 0); } /** * 是否是用手機網(wǎng)絡(luò)連接 * * @param context 上下文 * @return 結(jié)果 */ public static boolean isFlowConnect(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (null == cm || null == cm.getActiveNetworkInfo()) { return false; } return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; } /** * 是否是wifi連接 * * @param context app的context * @return true:是wifi連接 */ public static boolean isWifiConnect(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (null == cm || null == cm.getActiveNetworkInfo()) { return false; } return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; } /** * 獲取網(wǎng)絡(luò)連接類型 * * @param context context * @return NetworkType */ public static int getNetworkType(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (null == cm || null == cm.getActiveNetworkInfo()) { return TYPE_NO; } return cm.getActiveNetworkInfo().getType(); } /** * 獲取網(wǎng)絡(luò)連接類型名稱 * * @param context context * @return NetworkTypeName */ public static String getNetworkTypeName(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); String type = NETWORK_TYPE_DISCONNECT; if (cm == null || info == null) { return type; } if (info.isConnected()) { String typeName = info.getTypeName(); if ("WIFI".equalsIgnoreCase(typeName)) { type = NETWORK_TYPE_WIFI; } else if ("MOBILE".equalsIgnoreCase(typeName)) { String proxyHost = android.net.Proxy.getDefaultHost(); if (StringUtil.isEmpty(proxyHost)) { type = isFastMobileNetwork(context) ? NETWORK_TYPE_FAST : NETWORK_TYPE_SLOW; } else { type = NETWORK_TYPE_WAP; } } else { type = NETWORK_TYPE_UNKNOWN; } } return type; } /** * Whether is fast mobile network * * @param context context * @return FastMobileNetwork */ private static boolean isFastMobileNetwork(Context context) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE); if (telephonyManager == null) { return false; } switch (telephonyManager.getNetworkType()) { case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_HSPAP: case TelephonyManager.NETWORK_TYPE_LTE: return true; default: return false; } } /** * 獲取當前網(wǎng)絡(luò)的狀態(tài) * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的狀態(tài)。具體類型可參照NetworkInfo.State.CONNECTED、NetworkInfo.State.CONNECTED.DISCONNECTED等字段。 * 當前沒有網(wǎng)絡(luò)連接時返回null */ public static State getCurrentNetworkState(Context context) { NetworkInfo info = ((ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if (null == info) { return null; } return info.getState(); } /** * 獲取當前網(wǎng)絡(luò)的類型 * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型。具體類型可參照ConnectivityManager中的TYPE_BLUETOOTH、TYPE_MOBILE、TYPE_WIFI等字段。 * 當前沒有網(wǎng)絡(luò)連接時返回NetworkUtils.NETWORK_TYPE_NO_CONNECTION */ public static int getCurrentNetworkType(Context context) { NetworkInfo info = ((ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); return info != null ? info.getType() : NETWORK_TYPE_NO_CONNECTION; } /** * 獲取當前網(wǎng)絡(luò)的具體類型 * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的具體類型。具體類型可參照TelephonyManager中的NETWORK_TYPE_1xRTT、NETWORK_TYPE_CDMA等字段。 * 當前沒有網(wǎng)絡(luò)連接時返回NetworkUtils.NETWORK_TYPE_NO_CONNECTION */ public static int getCurrentNetworkSubtype(Context context) { NetworkInfo info = ((ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); return info != null ? info.getSubtype() : NETWORK_TYPE_NO_CONNECTION; } /** * 判斷當前網(wǎng)絡(luò)是否已經(jīng)連接 * * @param context 上下文 * @return 當前網(wǎng)絡(luò)是否已經(jīng)連接。false:尚未連接 */ public static boolean isConnectedByState(Context context) { return getCurrentNetworkState(context) == State.CONNECTED; } /** * 判斷當前網(wǎng)絡(luò)是否正在連接 * * @param context 上下文 * @return 當前網(wǎng)絡(luò)是否正在連接 */ public static boolean isConnectingByState(Context context) { return getCurrentNetworkState(context) == State.CONNECTING; } /** * 判斷當前網(wǎng)絡(luò)是否已經(jīng)斷開 * * @param context 上下文 * @return 當前網(wǎng)絡(luò)是否已經(jīng)斷開 */ public static boolean isDisconnectedByState(Context context) { return getCurrentNetworkState(context) == State.DISCONNECTED; } /** * 判斷當前網(wǎng)絡(luò)是否正在斷開 * * @param context 上下文 * @return 當前網(wǎng)絡(luò)是否正在斷開 */ public static boolean isDisconnectingByState(Context context) { return getCurrentNetworkState(context) == State.DISCONNECTING; } /** * 判斷當前網(wǎng)絡(luò)是否已經(jīng)暫停 * * @param context 上下文 * @return 當前網(wǎng)絡(luò)是否已經(jīng)暫停 */ public static boolean isSuspendedByState(Context context) { return getCurrentNetworkState(context) == State.SUSPENDED; } /** * 判斷當前網(wǎng)絡(luò)是否處于未知狀態(tài)中 * * @param context 上下文 * @return 當前網(wǎng)絡(luò)是否處于未知狀態(tài)中 */ public static boolean isUnknownByState(Context context) { return getCurrentNetworkState(context) == State.UNKNOWN; } /** * 判斷當前網(wǎng)絡(luò)的類型是否是藍牙 * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型是否是藍牙。false:當前沒有網(wǎng)絡(luò)連接或者網(wǎng)絡(luò)類型不是藍牙 */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static boolean isBluetoothByType(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) { return false; } else { return getCurrentNetworkType(context) == ConnectivityManager.TYPE_BLUETOOTH; } } /** * 判斷當前網(wǎng)絡(luò)的類型是否是虛擬網(wǎng)絡(luò) * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型是否是虛擬網(wǎng)絡(luò)。false:當前沒有網(wǎng)絡(luò)連接或者網(wǎng)絡(luò)類型不是虛擬網(wǎng)絡(luò) */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static boolean isDummyByType(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) { return false; } else { return getCurrentNetworkType(context) == ConnectivityManager.TYPE_DUMMY; } } /** * 判斷當前網(wǎng)絡(luò)的類型是否是ETHERNET * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型是否是ETHERNET。false:當前沒有網(wǎng)絡(luò)連接或者網(wǎng)絡(luò)類型不是ETHERNET */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static boolean isEthernetByType(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) { return false; } else { return getCurrentNetworkType(context) == ConnectivityManager.TYPE_ETHERNET; } } /** * 判斷當前網(wǎng)絡(luò)的類型是否是移動網(wǎng)絡(luò) * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型是否是移動網(wǎng)絡(luò)。false:當前沒有網(wǎng)絡(luò)連接或者網(wǎng)絡(luò)類型不是移動網(wǎng)絡(luò) */ public static boolean isMobileByType(Context context) { return getCurrentNetworkType(context) == ConnectivityManager.TYPE_MOBILE; } /** * 判斷當前網(wǎng)絡(luò)的類型是否是MobileDun * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型是否是MobileDun。false:當前沒有網(wǎng)絡(luò)連接或者網(wǎng)絡(luò)類型不是MobileDun */ public static boolean isMobileDunByType(Context context) { return getCurrentNetworkType(context) == ConnectivityManager.TYPE_MOBILE_DUN; } /** * 判斷當前網(wǎng)絡(luò)的類型是否是MobileHipri * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型是否是MobileHipri。false:當前沒有網(wǎng)絡(luò)連接或者網(wǎng)絡(luò)類型不是MobileHipri */ public static boolean isMobileHipriByType(Context context) { return getCurrentNetworkType(context) == ConnectivityManager.TYPE_MOBILE_HIPRI; } /** * 判斷當前網(wǎng)絡(luò)的類型是否是MobileMms * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型是否是MobileMms。false:當前沒有網(wǎng)絡(luò)連接或者網(wǎng)絡(luò)類型不是MobileMms */ public static boolean isMobileMmsByType(Context context) { return getCurrentNetworkType(context) == ConnectivityManager.TYPE_MOBILE_MMS; } /** * 判斷當前網(wǎng)絡(luò)的類型是否是MobileSupl * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型是否是MobileSupl。false:當前沒有網(wǎng)絡(luò)連接或者網(wǎng)絡(luò)類型不是MobileSupl */ public static boolean isMobileSuplByType(Context context) { return getCurrentNetworkType(context) == ConnectivityManager.TYPE_MOBILE_SUPL; } /** * 判斷當前網(wǎng)絡(luò)的類型是否是Wimax * * @param context 上下文 * @return 當前網(wǎng)絡(luò)的類型是否是Wimax。false:當前沒有網(wǎng)絡(luò)連接或者網(wǎng)絡(luò)類型不是Wimax */ public static boolean isWimaxByType(Context context) { return getCurrentNetworkType(context) == ConnectivityManager.TYPE_WIMAX; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是1XRTT * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是1XRTT。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是1XRTT */ public static boolean is1XRTTBySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_1xRTT; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是CDMA(Either IS95A or IS95B) * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是CDMA。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是CDMA */ public static boolean isCDMABySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_CDMA; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是EDGE * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是EDGE。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是EDGE */ public static boolean isEDGEBySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_EDGE; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是EHRPD * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是EHRPD。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是EHRPD */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static boolean isEHRPDBySubtype(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { return false; } else { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_EHRPD; } } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是EVDO_0 * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是EVDO_0。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是EVDO_0 */ public static boolean isEVDO0BySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_EVDO_0; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是EVDO_A * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是EVDO_A。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是EVDO_A */ public static boolean isEVDOABySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_EVDO_A; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是EDGE * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是EVDO_B。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是EVDO_B */ @TargetApi(Build.VERSION_CODES.GINGERBREAD) public static boolean isEVDOBBySubtype(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { return false; } else { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_EVDO_B; } } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是GPRS * * @param context app的context * @return false:當前網(wǎng)絡(luò)的具體類型是否是GPRS。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是GPRS */ public static boolean isGPRSBySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_GPRS; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是HSDPA * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是HSDPA。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是HSDPA */ public static boolean isHSDPABySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_HSDPA; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是HSPA * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是HSPA。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是HSPA */ public static boolean isHSPABySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_HSPA; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是HSPAP * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是HSPAP。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是HSPAP */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static boolean isHSPAPBySubtype(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) { return false; } else { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_HSPAP; } } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是HSUPA * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是HSUPA。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是HSUPA */ public static boolean isHSUPABySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_HSUPA; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是IDEN * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是IDEN。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是IDEN */ public static boolean isIDENBySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_IDEN; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是LTE * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是LTE。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是LTE */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static boolean isLTEBySubtype(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { return false; } else { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_LTE; } } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是UMTS * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是UMTS。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是UMTS */ public static boolean isUMTSBySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_UMTS; } /** * 判斷當前網(wǎng)絡(luò)的具體類型是否是UNKNOWN * * @param context 上下文 * @return false:當前網(wǎng)絡(luò)的具體類型是否是UNKNOWN。false:當前沒有網(wǎng)絡(luò)連接或者具體類型不是UNKNOWN */ public static boolean isUNKNOWNBySubtype(Context context) { return getCurrentNetworkSubtype(context) == TelephonyManager.NETWORK_TYPE_UNKNOWN; } /** * 判斷當前網(wǎng)絡(luò)是否是中國移動2G網(wǎng)絡(luò) * * @param context 上下文 * @return false:不是中國移動2G網(wǎng)絡(luò)或者當前沒有網(wǎng)絡(luò)連接 */ public static boolean isChinaMobile2G(Context context) { return isEDGEBySubtype(context); } /** * 判斷當前網(wǎng)絡(luò)是否是中國聯(lián)通2G網(wǎng)絡(luò) * * @param context 上下文 * @return false:不是中國聯(lián)通2G網(wǎng)絡(luò)或者當前沒有網(wǎng)絡(luò)連接 */ public static boolean isChinaUnicom2G(Context context) { return isGPRSBySubtype(context); } /** * 判斷當前網(wǎng)絡(luò)是否是中國聯(lián)通3G網(wǎng)絡(luò) * * @param context 上下文 * @return false:不是中國聯(lián)通3G網(wǎng)絡(luò)或者當前沒有網(wǎng)絡(luò)連接 */ public static boolean isChinaUnicom3G(Context context) { return isHSDPABySubtype(context) || isUMTSBySubtype(context); } /** * 判斷當前網(wǎng)絡(luò)是否是中國電信2G網(wǎng)絡(luò) * * @param context 上下文 * @return false:不是中國電信2G網(wǎng)絡(luò)或者當前沒有網(wǎng)絡(luò)連接 */ public static boolean isChinaTelecom2G(Context context) { return isCDMABySubtype(context); } /** * 判斷當前網(wǎng)絡(luò)是否是中國電信3G網(wǎng)絡(luò) * * @param context 上下文 * @return false:不是中國電信3G網(wǎng)絡(luò)或者當前沒有網(wǎng)絡(luò)連接 */ public static boolean isChinaTelecom3G(Context context) { return isEVDO0BySubtype(context) || isEVDOABySubtype(context) || isEVDOBBySubtype(context); } /** * 獲取Wifi的狀態(tài),需要ACCESS_WIFI_STATE權(quán)限 * * @param context 上下文 * @return 取值為WifiManager中的WIFI_STATE_ENABLED、WIFI_STATE_ENABLING、WIFI_STATE_DISABLED、 * WIFI_STATE_DISABLING、WIFI_STATE_UNKNOWN之一 * @throws Exception 沒有找到wifi設(shè)備 */ public static int getWifiState(Context context) throws Exception { WifiManager wifiManager = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)); if (wifiManager != null) { return wifiManager.getWifiState(); } else { throw new Exception("wifi device not found!"); } } /** * 判斷Wifi是否打開,需要ACCESS_WIFI_STATE權(quán)限 * * @param context 上下文 * @return true:打開;false:關(guān)閉 * @throws Exception */ public static boolean isWifiOpen(Context context) throws Exception { int wifiState = getWifiState(context); return wifiState == WifiManager.WIFI_STATE_ENABLED || wifiState == WifiManager.WIFI_STATE_ENABLING ? true : false; } /** * 設(shè)置Wifi,需要CHANGE_WIFI_STATE權(quán)限 * * @param context 上下文 * @param enable wifi狀態(tài) * @return 設(shè)置是否成功 * @throws Exception 是否授予WiFi權(quán)限 */ public static boolean setWifi(Context context, boolean enable) throws Exception { // 如果當前wifi的狀態(tài)和要設(shè)置的狀態(tài)不一樣 if (isWifiOpen(context) != enable) { ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).setWifiEnabled(enable); } return true; } /** * 判斷移動網(wǎng)絡(luò)是否打開,需要ACCESS_NETWORK_STATE權(quán)限 * * @param context 上下文 * @return true:打開;false:關(guān)閉 */ public static boolean isMobileNetworkOpen(Context context) { return (((ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE)).getNetworkInfo( ConnectivityManager.TYPE_MOBILE)).isConnected(); } /** * 獲取本機IP地址 * * @return null:沒有網(wǎng)絡(luò)連接 */ public static String getIpAddress() { try { NetworkInterface nerworkInterface; InetAddress inetAddress; for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements(); ) { nerworkInterface = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = nerworkInterface.getInetAddresses(); enumIpAddr .hasMoreElements(); ) { inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } return null; } catch (SocketException ex) { ex.printStackTrace(); return null; } } /** * 設(shè)置數(shù)據(jù)流量狀態(tài) * * @param context app的context * @param enabled 是否可用 */ public static void setDataEnabled(Context context, boolean enabled) { ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); Class<?> conMgrClass = null; Field iConMgrField = null; Object iConMgr = null; Class<?> iConMgrClass = null; Method setMobileDataEnabledMethod = null; try { conMgrClass = Class.forName(conMgr.getClass().getName()); iConMgrField = conMgrClass.getDeclaredField("mService"); iConMgrField.setAccessible(true); iConMgr = iConMgrField.get(conMgr); iConMgrClass = Class.forName(iConMgr.getClass().getName()); setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConMgr, enabled); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取wifi列表 * * @param context app的context * @return wifi列表 */ public static List<ScanResult> getWifiScanResults(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return wifiManager.startScan() ? wifiManager.getScanResults() : null; } /** * 過濾掃描結(jié)果 * * @param context app的context * @param bssid 過濾的字符串 * @return 過濾后的wifi列表 */ public static ScanResult getScanResultsByBSSID(Context context, String bssid) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); ScanResult scanResult = null; boolean f = wifiManager.startScan(); if (!f) { getScanResultsByBSSID(context, bssid); } List<ScanResult> list = wifiManager.getScanResults(); if (list != null) { for (int i = 0; i < list.size(); i++) { scanResult = list.get(i); if (scanResult.BSSID.equals(bssid)) { break; } } } return scanResult; } /** * 獲取wifi連接信息 * * @param context app的context * @return wifi信息 */ public static WifiInfo getWifiConnectionInfo(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return wifiManager.getConnectionInfo(); } /** * 獲得Proxy地址 * * @param context 上下文 * @return Proxy地址 */ public static String getProxy(Context context) { String proxy = null; ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { NetworkInfo networkinfo = connectivityManager.getActiveNetworkInfo(); if (networkinfo != null && networkinfo.isAvailable()) { String stringExtraInfo = networkinfo.getExtraInfo(); if (stringExtraInfo != null && ("cmwap".equals(stringExtraInfo) || "uniwap".equals(stringExtraInfo))) { proxy = "10.0.0.172:80"; } else if (stringExtraInfo != null && "ctwap".equals(stringExtraInfo)) { proxy = "10.0.0.200:80"; } } } return proxy; } // ------------- /** * 判斷當前是否有網(wǎng)絡(luò)連接 * @param context * @return 有網(wǎng)絡(luò)返回true;無網(wǎng)絡(luò)返回false */ @SuppressWarnings("null") public static boolean isNetWorkEnable(Context context){ ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo != null || networkInfo.isConnected()) { if (networkInfo.getState() == State.CONNECTED) { return true; } } return false; } /** * 判斷當前網(wǎng)絡(luò)是否為wifi * @param context * @return 如果為wifi返回true;否則返回false */ @SuppressWarnings("static-access") public static boolean isWiFiConnected(Context context){ ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); return networkInfo.getType() == manager.TYPE_WIFI ? true : false; } /** * 判斷MOBILE網(wǎng)絡(luò)是否可用 * @param context * @return * @throws Exception */ public static boolean isMobileDataEnable(Context context){ ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); boolean isMobileDataEnable = false; isMobileDataEnable = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); return isMobileDataEnable; } /** * 判斷wifi 是否可用 * @param context * @return * @throws Exception */ public static boolean isWifiDataEnable(Context context){ ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); boolean isWifiDataEnable = false; isWifiDataEnable = manager.getNetworkInfo( ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); return isWifiDataEnable; } /** * 跳轉(zhuǎn)到網(wǎng)絡(luò)設(shè)置頁面 * @param activity */ public static void GoSetting(Activity activity){ Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS); activity.startActivity(intent); } /** * 打開網(wǎng)絡(luò)設(shè)置界面 */ public static void openSetting(Activity activity) { Intent intent = new Intent("/"); ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings"); intent.setComponent(cn); intent.setAction("android.intent.action.VIEW"); activity.startActivityForResult(intent, 0); } }
Android-PhoneUtil工具類
手機組件調(diào)用工具類
public class PhoneUtil { private static long lastClickTime; private PhoneUtil() { throw new Error("Do not need instantiate!"); } /** * 調(diào)用系統(tǒng)發(fā)短信界面 * @param activity Activity * @param phoneNumber 手機號碼 * @param smsContent 短信內(nèi)容 */ public static void sendMessage(Context activity, String phoneNumber, String smsContent) { if (smsContent == null || phoneNumber.length() < 4) { return; } Uri uri = Uri.parse("smsto:" + phoneNumber); Intent intent = new Intent(Intent.ACTION_SENDTO, uri); intent.putExtra("sms_body", smsContent); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); } /** * 判斷是否為連擊 * @return boolean */ public static boolean isFastDoubleClick() { long time = System.currentTimeMillis(); long timeD = time - lastClickTime; if (0 < timeD && timeD < 500) { return true; } lastClickTime = time; return false; } /** * 獲取手機型號 * @param context 上下文 * @return String */ public static String getMobileModel(Context context) { try { String model = android.os.Build.MODEL; return model; } catch (Exception e) { return "未知!"; } } /** * 獲取手機品牌 * @param context 上下文 * @return String */ public static String getMobileBrand(Context context) { try { // android系統(tǒng)版本號 String brand = android.os.Build.BRAND; return brand; } catch (Exception e) { return "未知"; } } /** *拍照打開照相機! * @param requestcode 返回值 * @param activity 上下文 * @param fileName 生成的圖片文件的路徑 */ public static void toTakePhoto(int requestcode, Activity activity,String fileName) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra("camerasensortype", 2);// 調(diào)用前置攝像頭 intent.putExtra("autofocus", true);// 自動對焦 intent.putExtra("fullScreen", false);// 全屏 intent.putExtra("showActionIcons", false); try { //創(chuàng)建一個當前任務(wù)id的文件,然后里面存放任務(wù)的照片和路徑!這主文件的名字是用uuid到時候再用任務(wù)id去查路徑! File file = new File(fileName); //如果這個文件不存在就創(chuàng)建一個文件夾! if (!file.exists()) { file.mkdirs(); } Uri uri = Uri.fromFile(file); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); activity.startActivityForResult(intent, requestcode); } catch (Exception e) { e.printStackTrace(); } } /** *打開相冊 * @param requestcode 響應(yīng)碼 * @param activity 上下文 */ public static void toTakePicture(int requestcode, Activity activity){ Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); activity.startActivityForResult(intent, requestcode); } }
Android-PreferencesUtil工具類
SharedPreferences工具類,包含常用的數(shù)值獲取和存儲
public class PreferencesUtil { private PreferencesUtil(){} /** * 默認的SharePreference名稱 */ private static final String SHARED_NAME = "SharedPreferences"; /** * 查詢某個key是否已經(jīng)存在 * @param context 應(yīng)用程序上下文 * @param key key關(guān)鍵字 * @return 包含返回true;反之返回false */ public static boolean containsKey(Context context, String key){ SharedPreferences sp = getSharedPreferences(context); return sp.contains(key); } /** * 返回所有的鍵值對 * @param context 應(yīng)用程序上下文 * @return */ public static Map<String, ?> getAll(Context context) { SharedPreferences sp = getSharedPreferences(context); return sp.getAll(); } /** * 得到保存數(shù)據(jù)的方法,我們根據(jù)默認值得到保存的數(shù)據(jù)的具體類型,然后調(diào)用相對于的方法獲取值 * @param context 應(yīng)用程序上下文 * @param key key關(guān)鍵字 * @param defaultObject 默認值 * @return 返回獲取的String值 */ public static Object get(Context context, String key, Object defaultObject){ SharedPreferences sp = getSharedPreferences(context); if (defaultObject instanceof String) { return sp.getString(key, (String) defaultObject); } else if (defaultObject instanceof Integer) { return sp.getInt(key, (Integer) defaultObject); } else if (defaultObject instanceof Boolean) { return sp.getBoolean(key, (Boolean) defaultObject); } else if (defaultObject instanceof Float) { return sp.getFloat(key, (Float) defaultObject); } else if (defaultObject instanceof Long) { return sp.getLong(key, (Long) defaultObject); } return null; } /** * 獲取Set<String> 集合 * @param context 應(yīng)用程序上下文 * @param key key關(guān)鍵字 * @param defValues 默認值 * @return 返回Set<String>值 */ public static Set<String> getStringSet(Context context, String key, Set<String> defValues){ SharedPreferences sp = getSharedPreferences(context); return sp.getStringSet(key, defValues); } /** * 保存Set<String>集合的值 * @param context 應(yīng)用程序上下文 * @param key key關(guān)鍵字 * @param value 對應(yīng)值 * @return 成功返回true,失敗返回false */ public static boolean putStringSet(Context context, String key, Set<String> value){ return getEditor(context).putStringSet(key, value).commit(); } /** * 保存數(shù)據(jù)的方法,我們需要拿到保存數(shù)據(jù)的具體類型,然后根據(jù)類型調(diào)用不同的保存方法 * @param context 應(yīng)用程序上下文 * @param key key關(guān)鍵字 * @param object 對應(yīng)值 * @return 成功返回true,失敗返回false */ public static void put(Context context, String key, Object object){ if (object instanceof String) { getEditor(context).putString(key, (String) object); } else if (object instanceof Integer) { getEditor(context).putInt(key, (Integer) object); } else if (object instanceof Boolean) { getEditor(context).putBoolean(key, (Boolean) object); } else if (object instanceof Float) { getEditor(context).putFloat(key, (Float) object); } else if (object instanceof Long) { getEditor(context).putLong(key, (Long) object); } else { getEditor(context).putString(key, object.toString()); } SharedPreferencesCompat.apply(getEditor(context)); } /** * 刪除關(guān)鍵字key對應(yīng)的值 * @param context 應(yīng)用程序上下文 * @param key 關(guān)鍵字key */ public static void removeKey(Context context, String key){ getEditor(context).remove(key); SharedPreferencesCompat.apply(getEditor(context)); } /** * 清除所有的關(guān)鍵字對應(yīng)的值 * @param context 應(yīng)用程序上下文 */ public static void clearValues(Context context){ getEditor(context).clear(); SharedPreferencesCompat.apply(getEditor(context)); } /** * 獲取SharedPreferences對象 * @param context 應(yīng)用程序上下文 * @return 返回SharedPreferences對象 */ private static SharedPreferences getSharedPreferences(Context context){ return context.getSharedPreferences(SHARED_NAME, Context.MODE_PRIVATE); } /** * 獲取Editor對象 * @param context 應(yīng)用程序上下文 * @return 返回Editor對象 */ private static Editor getEditor(Context context){ return getSharedPreferences(context).edit(); } /** * 創(chuàng)建一個解決SharedPreferencesCompat.apply方法的一個兼容類 */ private static class SharedPreferencesCompat { private static final Method sApplyMethod = findApplyMethod(); /** * 反射查找apply的方法 * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static Method findApplyMethod() { try { Class clz = Editor.class; return clz.getMethod("apply"); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } /** * 如果找到則使用apply執(zhí)行,否則使用commit * @param editor */ public static void apply(Editor editor) { try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } editor.commit(); } } }
Android-ReflectUtil工具類
反射工具類:
public class ReflectUtil { private ReflectUtil(){} /** * 設(shè)置字段值 * @param t 對應(yīng)實體 * @param field 字段 * @param fieldName 字段名稱 * @param value 字段值 */ public static<T> void setFieldValue(T t,Field field, String fieldName, String value){ String name = field.getName(); //判斷該字段是否和目標字段相同 if (!fieldName.equals(name)) { return; } //獲取字段的類型 Type type = field.getType(); //獲取字段的修飾符號碼 int typeCode = field.getModifiers(); //獲取字段類型的名稱 String typeName = type.toString(); try { switch (typeName) { case "class java.lang.String": if (Modifier.isPublic(typeCode)) { field.set(t, value); } else { Method method = t.getClass().getMethod("set" + getMethodName(fieldName), String.class); method.invoke(t, value); } break; case "double": if(Modifier.isPublic(typeCode)){ field.setDouble(t, Double.valueOf(value)); }else{ Method method = t.getClass().getMethod("set" + getMethodName(fieldName),double.class); method.invoke(t, Double.valueOf(value)); } break; case "int": if(Modifier.isPublic(typeCode)){ field.setInt(t, Integer.valueOf(value)); }else{ Method method = t.getClass().getMethod("set" + getMethodName(fieldName),int.class); method.invoke(t, Integer.valueOf(value)); } break; case "float": if(Modifier.isPublic(typeCode)){ field.setFloat(t, Float.valueOf(value)); }else{ Method method = t.getClass().getMethod("set" + getMethodName(fieldName), float.class); method.invoke(t, Float.valueOf(value)); } break; } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 把字段名稱第一個字母換成大寫 * @param fieldName 字段名稱 * @return * @throws Exception 異常處理 */ private static String getMethodName(String fieldName) throws Exception{ byte[] items = fieldName.getBytes(); items[0] = (byte) ((char)items[0] - 'a' + 'A'); return new String(items); } /** * 根據(jù)字段名稱獲取指定Field字段 * @param clazz 實體的字節(jié)碼文件 * @param filedName 字段的名稱 * @return 返回對應(yīng)的字符按Field或者返回null */ public static Field getField(Class<?> clazz, String filedName){ if (clazz == null || TextUtils.isEmpty(filedName)) { throw new IllegalArgumentException("params is illegal"); } Field[] fields = clazz.getDeclaredFields(); return getFieldByName(fields, filedName); } /** * 根據(jù)字段名稱獲取指定的Field * @param fields 字段集合 * @param fieldName 字段名稱 * @return 返回對應(yīng)的Field字段或者返回null */ public static Field getFieldByName(Field[] fields, String fieldName){ if (fields == null || fields.length == 0 || TextUtils.isEmpty(fieldName)) { throw new IllegalArgumentException("params is illegal"); } for (Field field : fields) { String name = field.getName(); //判斷該字段是否和目標字段相同 if (fieldName.equals(name)) { return field; } } return null; } /** * 判斷該字段是否為FieldName對應(yīng)字段 * @param field Field字段 * @param fieldName 目標字段 * @return 是,返回true;否,返回false */ public static boolean isFiledWithName(Field field, String fieldName){ if(field == null || TextUtils.isEmpty(fieldName)){ throw new IllegalArgumentException("params is illegal"); } if (fieldName.equals(field.getName())) { return true; } return false; } }
Android-RSAUtils工具類
RSA加解密工具類
public class RSAUtils { private static final String TAG = "RSAUtils"; private final static String UTF_8 = "UTF-8"; // 10位公共偏移量 private final static String KEY_SUFFIX = "14293300FF"; private static byte[] iv; static { try { iv = "0123456789ABCDEF".getBytes(UTF_8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } static String AES_CBC_PKCS5Padding = "AES/CBC/PKCS5Padding"; static String RSA_ECB_PKCS1Padding = "RSA/ECB/PKCS1Padding"; static String MD5 = "MD5"; static int MD5_LEN = 32; private static String[] TYPES = {AES_CBC_PKCS5Padding, RSA_ECB_PKCS1Padding}; private static Integer[] MODES = {Cipher.ENCRYPT_MODE, Cipher.DECRYPT_MODE}; public static Key prvKey; public static Key pubKey; private static X509Certificate pubCert; // static String privateFile = RSAUtils.class.getClassLoader().getResource("").getPath() + "pkcs8_private_key.der"; static String privateFile; // 公鑰文件路徑 // static String publicFile = RSAUtils.class.getClassLoader().getResource("").getPath() + "rsacert.der"; public static InputStream publicFis; public static String encode = UTF_8;// 保持平臺兼容統(tǒng)一使用utf-8 private static String encryptMD5(String data) throws Exception { return doEncryptMD5(data, MD5); } public static SecretKey getKeyAES(String strKey) throws Exception { SecretKeySpec key = new SecretKeySpec(strKey.getBytes(encode), "AES"); return key; } public static HashMap<String, String> genMap(String acc) throws RuntimeException { System.out.println("accept data:" + acc); HashMap<String, String> tmpMap = new HashMap<String, String>(); if (acc == null || acc.length() < 26) { throw new RuntimeException("非法數(shù)據(jù)"); } // 第一個|在第24位(從0開始算) if (acc.indexOf("|") == MD5_LEN) { String md5 = acc.substring(0, MD5_LEN); acc = acc.substring(MD5_LEN + 1); tmpMap.put("md5", md5); // 第二個|在第8位及以后(從0開始算) int tmpInt = acc.indexOf("|"); if (acc.length() > 9 && tmpInt > 7 && tmpInt % 2 == 0) { String data = acc.substring(0, tmpInt); acc = acc.substring(tmpInt + 1); tmpMap.put("data", data); // 第二個|后數(shù)據(jù)長度都在16以上 tmpInt = acc.length(); if (tmpInt > 15) { tmpMap.put("key", acc); } else { throw new RuntimeException("非法key數(shù)據(jù)"); } } else { throw new RuntimeException("非法data數(shù)據(jù)"); } } else { throw new RuntimeException("非法md5數(shù)據(jù)"); } return tmpMap; } /** * //默認加密 MD5 AES_CBC_PKCS5Padding RSA_ECB_PKCS1Padding(私鑰加密) * * @param dataToEncypt 數(shù)據(jù) * @param pwd 對稱密鑰 * @return Map * @throws Exception */ public static HashMap<String, String> defaultEncrypt(byte[] dataToEncypt, String pwd) throws Exception { return encrypt(dataToEncypt, pwd, true); } /** * //默認加密 MD5 AES_CBC_PKCS5Padding RSA_ECB_PKCS1Padding(私鑰加密) * * @param dataToEncypt 數(shù)據(jù) * @param pwd 對稱密鑰 * @param isPrvEncrypt 是否使用私鑰加密 * @return Map * @throws Exception */ public static HashMap<String, String> encrypt(byte[] dataToEncypt, String pwd, boolean isPrvEncrypt) throws Exception { if (pwd == null || pwd.getBytes(encode).length != 6) { throw new RuntimeException("非法密鑰"); } Key key = prvKey; if (!isPrvEncrypt) { key = pubKey; } // md5 key+data // byte[] md5Byte = encryptMD5(pwd + new String(dataToEncypt, encode)); // String md5Base64 = Base64Utils.encode(md5Byte); String md5Base64 = doEncryptMD5(pwd + new String(dataToEncypt, encode), MD5); byte[] encryptData = doCrypt(AES_CBC_PKCS5Padding, Cipher.ENCRYPT_MODE, new IvParameterSpec(iv), getKeyAES(pwd + KEY_SUFFIX), dataToEncypt); // String dataBase64 = Base64Utils.encode(encryptData); String dataBase64 = doBase64Encode(encryptData); byte[] encryptKey = doCrypt(RSA_ECB_PKCS1Padding, Cipher.ENCRYPT_MODE, null, key, pwd.getBytes(encode)); // String keyBase64 = Base64Utils.encode(encryptKey); String keyBase64 = doBase64Encode(encryptKey); HashMap<String, String> data = new HashMap<String, String>(); data.put("data", dataBase64); data.put("key", keyBase64); data.put("md5", md5Base64); data.put("send", md5Base64 + "|" + dataBase64 + "|" + keyBase64); return data; } /** * //默認解密 MD5 AES_CBC_PKCS5Padding RSA_ECB_PKCS1Padding(公鑰解密) * * @paramdataToEncypt 數(shù)據(jù) * @parampwd 對稱密鑰 * @return Map * @throws Exception */ public static String defaultDecrypt(HashMap<String, String> data) throws Exception { return decrypt(data, true); } /** * //默認解密 MD5 AES_CBC_PKCS5Padding RSA_ECB_PKCS1Padding(公鑰解密) * * @paramdataToEncypt 數(shù)據(jù) * @parampwd 對稱密鑰 * @param isPubDecrypt 是否使用公鑰解密 * @return Map * @throws Exception */ public static String decrypt(HashMap<String, String> data, boolean isPubDecrypt) throws Exception { Key key = pubKey; if (!isPubDecrypt) { key = prvKey; } String dataBase64 = data.get("data"); String keyBase64 = data.get("key"); String md5Base64Src = data.get("md5"); // byte[] encryptedKey = Base64Utils.decode(keyBase64); byte[] encryptedKey = doBase64Decode(keyBase64); byte[] decryptedKey = doCrypt(RSA_ECB_PKCS1Padding, Cipher.DECRYPT_MODE, null, key, encryptedKey); String pwd = new String(decryptedKey, encode); if (pwd == null || pwd.getBytes(encode).length != 6) { throw new RuntimeException("偽造密鑰"); } // byte[] encryptedData = Base64Utils.decode(dataBase64); byte[] encryptedData = doBase64Decode(dataBase64); byte[] decryptedData = doCrypt(AES_CBC_PKCS5Padding, Cipher.DECRYPT_MODE, new IvParameterSpec(iv), getKeyAES(pwd + KEY_SUFFIX), encryptedData); String textDecrypt = new String(decryptedData, encode); // md5 key+data // byte[] md5Byte = encryptMD5(pwd + textDecrypt); // String md5Base64 = Base64Utils.encode(md5Byte); String md5Base64 = doEncryptMD5(pwd + textDecrypt, MD5); if (!md5Base64.equals(md5Base64Src)) { throw new RuntimeException("偽造數(shù)據(jù)"); } return textDecrypt; } public static Key getPubKey() throws CertificateException, IOException { // 讀取公鑰 CertificateFactory certificatefactory = CertificateFactory .getInstance("X.509"); InputStream bais = publicFis; Certificate cert = certificatefactory.generateCertificate(bais); bais.close(); pubCert = (X509Certificate) cert; PublicKey puk = cert.getPublicKey(); return puk; } public static Key getPrvKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { FileInputStream in = new FileInputStream(privateFile); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] tmpbuf = new byte[1024]; int count = 0; while ((count = in.read(tmpbuf)) != -1) { bout.write(tmpbuf, 0, count); } in.close(); // 讀取私鑰 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec( bout.toByteArray()); PrivateKey prk = keyFactory.generatePrivate(privateKeySpec); return prk; } public static String doEncryptMD5(String data, String type) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(data.getBytes("UTF-8")); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } if (MD5_LEN == 32) { // 32位加密 return buf.toString().toUpperCase(); } else { // 16位的加密 return buf.toString().substring(8, 24); } } public static String getPassword() { String pwd = (new Random().nextInt(1000000) + 1000000 + "") .substring(1); return pwd; } // pkcs8_der.key文件為私鑰 只能保存在服務(wù)端 // public_key.der為公鑰文件,保存在客戶端 public static void main(String[] args) { try { prvKey = getPrvKey(); pubKey = getPubKey(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } String text = "{\"TxnCode\":\"hce1003\",\"TxnStatus\":\"true\",\"ReplyCode\":\"000000\",\"ReplyMsg\":\"交易成功\",\"Data\":\"[{\\\"accountNo\\\":\\\"623091019******3297\\\",\\\"accountType\\\":\\\"1\\\",\\\"certNo\\\":\\\"***\\\",\\\"certType\\\":\\\"101\\\",\\\"customerName\\\":\\\"***\\\",\\\"mobileNo\\\":\\\"***\\\"},{\\\"accountNo\\\":\\\"***\\\",\\\"accountType\\\":\\\"1\\\",\\\"certNo\\\":\\\"***\\\",\\\"certType\\\":\\\"101\\\",\\\"customerName\\\":\\\"***\\\",\\\"mobileNo\\\":\\\"***\\\"}]\"}"; // String text = "c"; // String text = "提起黃飛鴻,我們隱隱約約地知道他是一個真實的歷史人物,但恐怕很少有人能在腦海中勾勒出他本人真實的面貌,上了歲數(shù)的人大概還依稀記得關(guān)德興那張冷峻硬朗的面龐;三四十歲左右的人想到的應(yīng)該是風(fēng)度翩翩的李連杰,關(guān)之琳扮演嬌美的十三姨,如影隨形不離左右;再年輕一點的觀眾或許更傾心于趙文卓甚至是彭于晏的扮相。“黃飛鴻”這個名字,經(jīng)過文學(xué)和影視作品的塑造,早已由一個平凡的歷史人物變成了整個華人世界的偶像,俠之大者、一代宗師的化身。那么,真實歷史中的黃飛鴻,究竟是怎樣一個人?為什么在他死后,會由一介平凡的嶺南武師,變?yōu)槿w華人心目中的英雄?"; String pwd = getPassword(); // String pwd="663810"; // 加密 HashMap<String, String> data; try { data = defaultEncrypt(text.getBytes(encode), pwd); } catch (Exception e) { e.printStackTrace(); return; } String accept = data.get("send"); // String accept = // "mQ6uBpadJfNFxFHez3zWwQ==|2xZJpm3xO5gKaID9pYYqfTQ8e64GHo4esj7E51DlyCZM32DJAPUN3RKqLFkfR5rUCA+SsSD8vQOH+iS/Uh7YlCZhatuTOgNqJi6TfLbp4yZx4iTqFRda5jBVD1vNgsUf8jZdoJLY6rg2OhvcOjL+/lGeijdVv5f0RkykAtfKUHWeO5jWk+jUALQqx/ugO46Npna6MoeelUDzIbmdHL2NmZRmDzPvqpkQmUz9Pk8P19R/kWZuVfxVuOzPuaic69Roq1zbNyrKhGfqITQRwSsVOGMQi3qGYfY3Sv/hrbIuwZ4=|eAoqLUr9bC+sfACRZN6UFnm9g8R8h/jtq1k50m5aOB6AhxtaJWN/PiE2iaHBwF8a5z1gqdQdt0HERLFZm6tzvE6N2+RwF/XylK4oxfhLeCGOW85ahpnwlEpVGD86oCq8JRp4fglhaFkt9MAwmfpWGnT6GIlB9OiXFzNkIgrUdIk="; HashMap<String, String> acceptMap = genMap(accept); // 解密 try { defaultDecrypt(acceptMap); } catch (Exception e) { e.printStackTrace(); } } /** * @param type 算法/加密方式/填充方式 如:AES/CBC/PKCS5Padding * @param mode 加密/或者解密 Cipher.DECRYPT_MODE/Cipher.ENCRYPT_MODE * @param zeroIv 初始化向量 如:new IvParameterSpec(iv) * @param key 密鑰 * @param data 需要加密的數(shù)據(jù) * @return byte[] * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] doCrypt(String type, int mode, IvParameterSpec zeroIv, Key key, byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { if (!checkCrypt(type, mode, zeroIv, key, data)) { throw new RuntimeException("參數(shù)非法"); } if (!pubCertValid()) { throw new RuntimeException("證書失效"); } Cipher cipher = Cipher.getInstance(type); if (type.contains("CBC") && zeroIv != null) { cipher.init(mode, key, zeroIv); } else { cipher.init(mode, key); } return cipher.doFinal(data); } private static boolean checkCrypt(String type, int mode, IvParameterSpec zeroIv, Key key, byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { if (type == null || !isValid(TYPES, type)) { return false; } if (!isValid(MODES, mode)) { return false; } if (key == null) { return false; } if (type.contains("RSA") && zeroIv != null) { return false; } if (data == null || data.length == 0) { return false; } return true; } private static boolean isValid(Object[] ts, Object t) { if (ts instanceof String[] && t instanceof String) { String[] strs = (String[]) ts; String tmp = (String) t; for (String str : strs) { if (tmp.equals(str)) { return true; } } } if (ts instanceof Integer[] && t instanceof Integer) { Integer[] ints = (Integer[]) ts; Integer intT = (Integer) t; for (Integer str : ints) { if (intT == str) { return true; } } } return false; } public static boolean pubCertValid() { if (pubCert == null) { return false; } try { pubCert.checkValidity(new Date()); } catch (Exception e) { System.err.println("證書失效" + e.getMessage()); e.printStackTrace(); return false; } return true; } public static String doBase64Encode(byte[] abc) throws UnsupportedEncodingException { String abce = null; abce = new String(Base64.encode(abc, 0)); // 劉德利修改過 // Base64.getEncoder().encodeToString(abc); return abce; } public static byte[] doBase64Decode(String abc) throws UnsupportedEncodingException { byte[] abce = null; abce = Base64.decode(abc,0); // 劉德利修改過 return abce; } public static void getPublicKeyFile(Context context) { if (publicFis == null) { //獲取解密公鑰文件 publicFis = context.getResources().openRawResource(R.raw.rsacert); try { pubKey = getPubKey(); } catch (IOException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } } }
注意:在自測的時候,需要公鑰文件:
public static void mainTest() { String result = "test123456789"; try { JSONObject jsonObject = new JSONObject(result); String data = jsonObject.getString("data"); String resultCode = jsonObject.getString("code"); String msg = jsonObject.getString("msg"); LogUtil.i(TAG, "resultCode=====>" + resultCode); if ("200".equals(resultCode)) { HashMap<String, String> acceptMap = RSAUtils.genMap(data); String decryptText = defaultDecrypt(acceptMap); LogUtil.i(TAG, "解密明文=====>" + decryptText); // progressLoginRequest(decryptText); } else { // 其他情況直接顯示后臺內(nèi)容 // LoginActivity.this.showDialog(BaseActivity.MODAL_DIALOG, msg); LogUtil.d(TAG, "msg:" + msg); } } catch (Exception e) { e.printStackTrace(); } }
Android-ScreenUtil工具類
屏幕工具類,涉及到屏幕寬度、高度、密度比、(像素、dp、sp)之間的轉(zhuǎn)換等。
public class ScreenUtil { private ScreenUtil(){} /** * 獲取屏幕寬度,單位為px * @param context 應(yīng)用程序上下文 * @return 屏幕寬度,單位px */ public static int getScreenWidth(Context context){ return getDisplayMetrics(context).widthPixels; } /** * 獲取屏幕高度,單位為px * @param context 應(yīng)用程序上下文 * @return 屏幕高度,單位px */ public static int getScreenHeight(Context context){ return getDisplayMetrics(context).heightPixels; } /** * 獲取系統(tǒng)dp尺寸密度值 * @param context 應(yīng)用程序上下文 * @return */ public static float getDensity(Context context){ return getDisplayMetrics(context).density; } /** * 獲取系統(tǒng)字體sp密度值 * @param context 應(yīng)用程序上下文 * @return */ public static float getScaledDensity(Context context){ return getDisplayMetrics(context).scaledDensity; } /** * dip轉(zhuǎn)換為px大小 * @param context 應(yīng)用程序上下文 * @param dpValue dp值 * @return 轉(zhuǎn)換后的px值 */ public static int dp2px(Context context, int dpValue){ return (int) (dpValue * getDensity(context) + 0.5f); } /** * px轉(zhuǎn)換為dp值 * @param context 應(yīng)用程序上下文 * @param pxValue px值 * @return 轉(zhuǎn)換后的dp值 */ public static int px2dp(Context context, int pxValue){ return (int) (pxValue / getDensity(context) + 0.5f); } /** * sp轉(zhuǎn)換為px * @param context 應(yīng)用程序上下文 * @param spValue sp值 * @return 轉(zhuǎn)換后的px值 */ public static int sp2px(Context context, int spValue){ return (int) (spValue * getScaledDensity(context) + 0.5f); } /** * px轉(zhuǎn)換為sp * @param context 應(yīng)用程序上下文 * @param pxValue px值 * @return 轉(zhuǎn)換后的sp值 */ public static int px2sp(Context context, int pxValue){ return (int) (pxValue / getScaledDensity(context) + 0.5f); } /** * 獲得狀態(tài)欄的高度 * * @param context * @return */ public static int getStatusHeight(Context context){ int statusHeight = -1; try { Class<?> clazz = Class.forName("com.android.internal.R$dimen"); Object object = clazz.newInstance(); int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString()); statusHeight = context.getResources().getDimensionPixelSize(height); } catch (Exception e) { e.printStackTrace(); } return statusHeight; } /** * 獲取當前屏幕截圖,包含狀態(tài)欄 * @param activity * @return */ public static Bitmap snapShotWithStatusBar(Activity activity){ View decorView = activity.getWindow().getDecorView(); decorView.setDrawingCacheEnabled(true); decorView.buildDrawingCache(); Bitmap bmp = decorView.getDrawingCache(); int width = getScreenWidth(activity); int height = getScreenHeight(activity); Bitmap bitmap = null; bitmap = Bitmap.createBitmap(bmp, 0, 0, width, height); decorView.destroyDrawingCache(); return bitmap; } /** * 獲取當前屏幕截圖,不包含狀態(tài)欄 * @param activity * @return */ public static Bitmap snapShotWithoutStatusBar(Activity activity){ View decorView = activity.getWindow().getDecorView(); decorView.setDrawingCacheEnabled(true); decorView.buildDrawingCache(); Bitmap bmp = decorView.getDrawingCache(); Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusHeight = frame.top; int width = getScreenWidth(activity); int height = getScreenHeight(activity); Bitmap bitmap = null; bitmap = Bitmap.createBitmap(bmp, 0, statusHeight, width, height - statusHeight); decorView.destroyDrawingCache(); return bitmap; } /** * 獲取DisplayMetrics對象 * @param context 應(yīng)用程序上下文 * @return */ public static DisplayMetrics getDisplayMetrics(Context context){ WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(metrics); return metrics; } }
Android-SDCardUtil工具類
SD卡工具類,包含SD卡狀態(tài)、路徑、容量大小
public class SDCardUtil { private SDCardUtil(){} /** * 判斷SD卡是否可用 * @return * ture:可用;false:不可用 */ public static boolean isSDCardEnable(){ return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } /** * 獲取SD卡路徑 * @return * SD卡存在返回正常路徑;SD卡不存在返回"" */ public static String getSDCradPath(){ if (isSDCardEnable()) { return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator; } else { return ""; } } /** * 獲取SD卡路徑文件 * @return * SD卡存在返回正常路徑;SD卡不存在返回null */ public static File getSDCardFile(){ if(isSDCardEnable()){ return Environment.getExternalStorageDirectory(); }else{ return null; } } /** * 獲取SD卡DownloadCache路徑 * @return * SD卡存在返回正常路徑;SD卡不存在返回"" */ public static String getSDCardDownloadCachePath(){ if(isSDCardEnable()){ return Environment.getDownloadCacheDirectory().getAbsolutePath() + File.separator; }else{ return ""; } } /** * 獲取SD卡DownloadCache路徑文件 * @return * SD卡存在返回正常路徑;SD卡不存在返回null */ public static File getSDCardDownloadCacheFile(){ if(isSDCardEnable()){ return Environment.getDownloadCacheDirectory(); }else{ return null; } } /** * 獲取系統(tǒng)存儲路徑 * @return * SD卡存在返回正常路徑;SD卡不存在返回"" */ public static String getSDCardRootPath(){ if(isSDCardEnable()){ return Environment.getRootDirectory().getAbsolutePath() + File.separator; }else{ return ""; } } /** * 獲取系統(tǒng)存儲路徑文件 * @return * SD卡存在返回正常路徑;SD卡不存在返回null */ public static File getSDCardRootFile(){ if(isSDCardEnable()){ return Environment.getRootDirectory(); }else{ return null; } } /** * 獲取應(yīng)用程序的/data/data目錄 * @param context * @return */ public static String getDataFilePath(Context context){ return context.getFilesDir().getAbsolutePath() + File.separator; } /** * /data/data/PackageName/cache的路徑 * @param context * @return */ public static String getDataCachePath(Context context){ return context.getCacheDir().getAbsolutePath() + File.separator; } /** * 獲取SD卡大小 * @return * SD卡存在返回大??;SD卡不存在返回-1 */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public static long getSDCardSize(){ if (isSDCardEnable()) { StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator); if (android.os.Build.VERSION.SDK_INT < 18) { int blockSize = statFs.getBlockSize(); int blockCount = statFs.getBlockCount(); return blockSize * blockCount; } else { long blockSize = statFs.getBlockSizeLong(); long blockCount = statFs.getBlockCountLong(); return blockSize * blockCount; } } return -1; } /** * 獲取SD卡可用大小 * @return * SD卡存在返回大??;SD卡不存在返回-1 */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public static long getSDCardAvailableSize(){ if (isSDCardEnable()) { StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator); if (android.os.Build.VERSION.SDK_INT < 18) { int blockSize = statFs.getBlockSize(); int blockCount = statFs.getAvailableBlocks(); return blockSize * blockCount; } else { long blockSize = statFs.getBlockSizeLong(); long blockCount = statFs.getAvailableBlocksLong(); return blockSize * blockCount; } } return -1; } /** * 獲得手機內(nèi)存總大小 * @return */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public long getRomTotalSize() { File path = Environment.getDataDirectory(); StatFs statFs = new StatFs(path.getPath()); if (android.os.Build.VERSION.SDK_INT < 18) { int blockSize = statFs.getBlockSize(); int blockCount = statFs.getBlockCount(); return blockSize * blockCount; } else { long blockSize = statFs.getBlockSizeLong(); long blockCount = statFs.getBlockCountLong(); return blockSize * blockCount; } } /** * 獲得手機可用內(nèi)存 * @return */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public long getRomAvailableSize() { File path = Environment.getDataDirectory(); StatFs statFs = new StatFs(path.getPath()); if (android.os.Build.VERSION.SDK_INT < 18) { int blockSize = statFs.getBlockSize(); int blockCount = statFs.getAvailableBlocks(); return blockSize * blockCount; } else { long blockSize = statFs.getBlockSizeLong(); long blockCount = statFs.getAvailableBlocksLong(); return blockSize * blockCount; } } }
Android-ShortCutUtil工具類
創(chuàng)建刪除快捷圖標的工具類
注意:需要增加權(quán)限
權(quán)限: com.android.launcher.permission.INSTALL_SHORTCUT
com.android.launcher.permission.UNINSTALL_SHORTCUT
public class ShortCutUtil { private ShortCutUtil() { throw new Error("Do not need instantiate!"); } /** * 檢測是否存在快捷鍵 * @param activity Activity * @return 是否存在桌面圖標 */ public static boolean hasShortcut(Activity activity) { boolean isInstallShortcut = false; ContentResolver cr = activity.getContentResolver(); String AUTHORITY = "com.android.launcher.settings"; Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true"); Cursor c = cr.query(CONTENT_URI, new String[]{"title", "iconResource"}, "title=?", new String[]{activity.getString(R.string.app_name).trim()}, null); if (c != null && c.getCount() > 0) { isInstallShortcut = true; } return isInstallShortcut; } /** * 為程序創(chuàng)建桌面快捷方式 * @param activity Activity * @param res res */ public static void addShortcut(Activity activity,int res) { Intent shortcut = new Intent( "com.android.launcher.action.INSTALL_SHORTCUT"); //快捷方式的名稱 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, activity.getString(R.string.app_name)); //不允許重復(fù)創(chuàng)建 shortcut.putExtra("duplicate", false); Intent shortcutIntent = new Intent(Intent.ACTION_MAIN); shortcutIntent.setClassName(activity, activity.getClass().getName()); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); //快捷方式的圖標 Intent.ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(activity, res); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); activity.sendBroadcast(shortcut); } /** * 刪除程序的快捷方式 * @param activity Activity */ public static void delShortcut(Activity activity) { Intent shortcut = new Intent( "com.android.launcher.action.UNINSTALL_SHORTCUT"); shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, activity.getString(R.string.app_name)); String appClass = activity.getPackageName() + "." + activity.getLocalClassName(); ComponentName cn = new ComponentName(activity.getPackageName(), appClass); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent( Intent.ACTION_MAIN).setComponent(cn)); activity.sendBroadcast(shortcut); } }
Android-SharedPreferences工具類
共享首選項工具類:
public class SPUtil { /** * 保存在手機里面的文件名 */ // public static final String FILE_NAME = "share_data"; /** * 保存數(shù)據(jù)的方法,我們需要拿到保存數(shù)據(jù)的具體類型,然后根據(jù)類型調(diào)用不同的保存方法 */ /*public static void put(Context context, String key, Object object) { put(context, FILE_NAME, key, object); }*/ public static void put(Context context, String spFileName, String key, Object object) { SharedPreferences sp = context.getSharedPreferences(spFileName, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); if (object instanceof String) { editor.putString(key, (String) object); } else if (object instanceof Integer) { editor.putInt(key, (Integer) object); } else if (object instanceof Boolean) { editor.putBoolean(key, (Boolean) object); } else if (object instanceof Float) { editor.putFloat(key, (Float) object); } else if (object instanceof Long) { editor.putLong(key, (Long) object); } else { editor.putString(key, object.toString()); } SharedPreferencesCompat.apply(editor); } public static void putString(Context context, String spFileName, String key, String stringData) { SharedPreferences sp = context.getSharedPreferences(spFileName, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString(key, stringData); editor.commit(); // SharedPreferencesCompat.apply(editor); } /** * 得到保存數(shù)據(jù)的方法,我們根據(jù)默認值得到保存的數(shù)據(jù)的具體類型,然后調(diào)用相對于的方法獲取值 */ /*public static Object get(Context context, String key, Object defaultObject) { return get(context, FILE_NAME, key, defaultObject); }*/ public static Object get(Context context, String spName, String key, Object defaultObject) { SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE); if (defaultObject instanceof String) { return sp.getString(key, (String) defaultObject); } else if (defaultObject instanceof Integer) { return sp.getInt(key, (Integer) defaultObject); } else if (defaultObject instanceof Boolean) { return sp.getBoolean(key, (Boolean) defaultObject); } else if (defaultObject instanceof Float) { return sp.getFloat(key, (Float) defaultObject); } else if (defaultObject instanceof Long) { return sp.getLong(key, (Long) defaultObject); } return null; } public static String getString(Context context, String spName, String key, String stringDataDefault) { SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE); return sp.getString(key, stringDataDefault); } /** * 移除某個key值已經(jīng)對應(yīng)的值 */ /*public static void remove(Context context, String key) { remove(context, FILE_NAME, key); }*/ public static void remove(Context context, String spFileName, String key) { SharedPreferences sp = context.getSharedPreferences(spFileName, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); SharedPreferencesCompat.apply(editor); } /** * 清除所有數(shù)據(jù) */ /*public static void clear(Context context) { clear(context, FILE_NAME); }*/ public static void clear(Context context, String spFileName) { SharedPreferences sp = context.getSharedPreferences(spFileName, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); SharedPreferencesCompat.apply(editor); } /** * 查詢某個key是否已經(jīng)存在 */ /*public static boolean contains(Context context, String key) { return contains(context, FILE_NAME, key); }*/ public static boolean contains(Context context, String spFileName, String key) { SharedPreferences sp = context.getSharedPreferences(spFileName, Context.MODE_PRIVATE); return sp.contains(key); } /** * 返回所有的鍵值對 */ /*public static Map<String, ?> getAll(Context context) { return getAll(context, FILE_NAME); }*/ public static Map<String, ?> getAll(Context context, String spName) { SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE); return sp.getAll(); } /** * 創(chuàng)建一個解決SharedPreferencesCompat.apply方法的一個兼容類 */ private static class SharedPreferencesCompat { private static final Method sApplyMethod = findApplyMethod(); /** * 反射查找apply的方法 */ @SuppressWarnings({"unchecked", "rawtypes"}) private static Method findApplyMethod() { try { Class clz = SharedPreferences.Editor.class; return clz.getMethod("apply"); } catch (NoSuchMethodException e) { } return null; } /** * 如果找到則使用apply執(zhí)行,否則使用commit */ public static void apply(SharedPreferences.Editor editor) { try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } editor.commit(); } }
Android-StringHandler工具類
字符串處理類:
public class StringHandler { private static final String TAG = "StringHandler"; /** * 根據(jù)分隔符截取字符串 * @param str 字符串 * @param separator 分隔符 * @return 截取的字符串數(shù)組 */ public static String[] split(String str, String separator) { if (str == null || str.equals("") || separator == null) { return null; } int index; ArrayList<String> list = new ArrayList<String>(); while((index = str.indexOf(separator)) != -1) { list.add(str.substring(0, index)); str = str.substring(index + separator.length()); } list.add(str); return list.toArray(new String[list.size()]); } /** * 使用StringBuffer追加字符串 * @param str 字符串數(shù)組 * @return 完整字符串 */ public static String append(String...str) { StringBuffer sb = new StringBuffer(); int len = str.length; for (int i = 0; i < len; i++) { if (null != str[i]) { sb.append(str[i]); } } return sb.toString(); } public static final String MSG_REPLACE_STR = "%s"; public static String replace(String src, String...str) { if (str == null) { return src; } int count = countStr(src, MSG_REPLACE_STR); if (count != str.length) { ELog.w(TAG, "str len error."); return null; } for (int i = 0; i < str.length; i++) { src = src.replaceFirst(MSG_REPLACE_STR, str[i]); } count = 0; return src; } /** * 計算src中包含str的個數(shù) * 可以優(yōu)化 --> indexOf(a, b) * @return */ public static int countStr(String src, String str) { int count = 0; if (src.indexOf(str) == -1) { return 0; } else if (src.indexOf(str) != -1) { count += countStr(src.substring(src.indexOf(str) + str.length()), str); return count + 1; } return 0; } /** * 去除字符串中的空格、回車、換行符、制表符 * @param str * @return */ public static String replaceBlank(String str) { String dest = ""; if (str!=null) { Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(str); dest = m.replaceAll(""); } return dest; } /** * 將二進制數(shù)據(jù)轉(zhuǎn)換為文件 * @param data * @param fileName */ public static boolean data2file(byte[] data, String fileName) { FileOutputStream out = null; try { out = new FileOutputStream(fileName); out.write(data); } catch (FileNotFoundException e) { // e.printStackTrace(); ELog.e(TAG, e.toString()); try { out.close(); } catch (IOException e1) { e1.printStackTrace(); } out = null; return false; } catch (IOException e) { // e.printStackTrace(); ELog.e(TAG, e.toString()); try { out.close(); } catch (IOException e1) { e1.printStackTrace(); } out = null; return false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { ELog.e(TAG, e.toString()); return false; } out = null; } } return true; } }
Android-StringUtil2工具類
字符串工具類,提供一些字符串相關(guān)的便捷方法:
public class StringUtil2 { private StringUtil2() { throw new AssertionError(); } /** * <pre> * isBlank(null) = true; * isBlank("") = true; * isBlank(" ") = true; * isBlank("a") = false; * isBlank("a ") = false; * isBlank(" a") = false; * isBlank("a b") = false; * </pre> * * @param str 字符串 * @return 如果字符串為空或者長度為0,返回true,否則返回false */ public static boolean isBlank(String str) { return (str == null || str.trim().length() == 0); } /** * <pre> * isEmpty(null) = true; * isEmpty("") = true; * isEmpty(" ") = false; * </pre> * * @param c 字符序列 * @return 如果字符序列為空或者長度為0,返回true,否則返回false */ public static boolean isEmpty(CharSequence c) { return (c == null || c.length() == 0); } /** * 獲取字符序列的長度 * <pre> * length(null) = 0; * length(\"\") = 0; * length(\"abc\") = 3; * </pre> * * @param c 字符序列 * @return 如果字符序列為空,返回0,否則返回字符序列的長度 */ public static int length(CharSequence c) { return c == null ? 0 : c.length(); } /** * null Object to empty string * 空對象轉(zhuǎn)化成空字符串 * <pre> * nullStrToEmpty(null) = ""; * nullStrToEmpty("") = ""; * nullStrToEmpty("aa") = "aa"; * </pre> * * @param object 對象 * @return String */ public static String nullStrToEmpty(Object object) { return object == null ? "" : (object instanceof String ? (String)object : object.toString()); } /** * @param str str * @return String */ public static String capitalizeFirstLetter(String str) { if (isEmpty(str)) { return str; } char c = str.charAt(0); return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str : new StringBuilder(str.length()).append( Character.toUpperCase(c)) .append(str.substring(1)) .toString(); } /** * 用utf-8編碼 * @param str 字符串 * @return 返回一個utf8的字符串 */ public static String utf8Encode(String str) { if (!isEmpty(str) || str.getBytes().length != str.length()) { try { return URLEncoder.encode(str, "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "UnsupportedEncodingException occurred. ", e); } } return str; } /** * @param href 字符串 * @return 返回一個html */ public static String getHrefInnerHtml(String href) { if (isEmpty(href)) { return ""; } String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*"; Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE); Matcher hrefMatcher = hrefPattern.matcher(href); if (hrefMatcher.matches()) { return hrefMatcher.group(1); } return href; } /** * @param source 字符串 * @return 返回htmL到字符串 */ /*public static String htmlEscapeCharsToString(String source) { return StringUtil.isEmpty(source) ? source : source.replaceAll("<", "<") .replaceAll(">", ">") .replaceAll("&", "&") .replaceAll(""", "\""); }*/ /** * @param s 字符串 * @return String */ public static String fullWidthToHalfWidth(String s) { if (isEmpty(s)) { return s; } char[] source = s.toCharArray(); for (int i = 0; i < source.length; i++) { if (source[i] == 12288) { source[i] = ' '; // } else if (source[i] == 12290) { // source[i] = '.'; } else if (source[i] >= 65281 && source[i] <= 65374) { source[i] = (char) (source[i] - 65248); } else { source[i] = source[i]; } } return new String(source); } /** * @param s 字符串 * @return 返回的數(shù)值 */ public static String halfWidthToFullWidth(String s) { if (isEmpty(s)) { return s; } char[] source = s.toCharArray(); for (int i = 0; i < source.length; i++) { if (source[i] == ' ') { source[i] = (char) 12288; // } else if (source[i] == '.') { // source[i] = (char)12290; } else if (source[i] >= 33 && source[i] <= 126) { source[i] = (char) (source[i] + 65248); } else { source[i] = source[i]; } } return new String(source); } /** * @param str 資源 * @return 特殊字符串切換 */ public static String replaceBlanktihuan(String str) { String dest = ""; if (str != null) { Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(str); dest = m.replaceAll(""); } return dest; } /** * 判斷給定的字符串是否為null或者是空的 * @param string 給定的字符串 */ public static boolean isEmpty(String string) { return string == null || "".equals(string.trim()); } /** * 判斷給定的字符串是否不為null且不為空 * @param string 給定的字符串 */ public static boolean isNotEmpty(String string) { return !isEmpty(string); } /** * 判斷給定的字符串數(shù)組中的所有字符串是否都為null或者是空的 * @param strings 給定的字符串 */ public static boolean isEmpty(String... strings) { boolean result = true; for (String string : strings) { if (isNotEmpty(string)) { result = false; break; } } return result; } /** * 判斷給定的字符串數(shù)組中是否全部都不為null且不為空 * * @param strings 給定的字符串數(shù)組 * @return 是否全部都不為null且不為空 */ public static boolean isNotEmpty(String... strings) { boolean result = true; for (String string : strings) { if (isEmpty(string)) { result = false; break; } } return result; } /** * 如果字符串是null或者空就返回"" */ public static String filterEmpty(String string) { return StringUtil.isNotEmpty(string) ? string : ""; } /** * 在給定的字符串中,用新的字符替換所有舊的字符 * @param string 給定的字符串 * @param oldchar 舊的字符 * @param newchar 新的字符 * @return 替換后的字符串 */ public static String replace(String string, char oldchar, char newchar) { char chars[] = string.toCharArray(); for (int w = 0; w < chars.length; w++) { if (chars[w] == oldchar) { chars[w] = newchar; break; } } return new String(chars); } /** * 把給定的字符串用給定的字符分割 * @param string 給定的字符串 * @param ch 給定的字符 * @return 分割后的字符串數(shù)組 */ public static String[] split(String string, char ch) { ArrayList<String> stringList = new ArrayList<String>(); char chars[] = string.toCharArray(); int nextStart = 0; for (int w = 0; w < chars.length; w++) { if (ch == chars[w]) { stringList.add(new String(chars, nextStart, w - nextStart)); nextStart = w + 1; if (nextStart == chars.length) { //當最后一位是分割符的話,就再添加一個空的字符串到分割數(shù)組中去 stringList.add(""); } } } if (nextStart < chars.length) { //如果最后一位不是分隔符的話,就將最后一個分割符到最后一個字符中間的左右字符串作為一個字符串添加到分割數(shù)組中去 stringList.add(new String(chars, nextStart, chars.length - 1 - nextStart + 1)); } return stringList.toArray(new String[stringList.size()]); } /** * 計算給定的字符串的長度,計算規(guī)則是:一個漢字的長度為2,一個字符的長度為1 * * @param string 給定的字符串 * @return 長度 */ public static int countLength(String string) { int length = 0; char[] chars = string.toCharArray(); for (int w = 0; w < string.length(); w++) { char ch = chars[w]; if (ch >= '\u0391' &amamp;& ch <= '\uFFE5') { length++; length++; } else { length++; } } return length; } private static char[] getChars(char[] chars, int startIndex) { int endIndex = startIndex + 1; //如果第一個是數(shù)字 if (Character.isDigit(chars[startIndex])) { //如果下一個是數(shù)字 while (endIndex < chars.length && Character.isDigit(chars[endIndex])) { endIndex++; } } char[] resultChars = new char[endIndex - startIndex]; System.arraycopy(chars, startIndex, resultChars, 0, resultChars.length); return resultChars; } /** * 是否全是數(shù)字 */ public static boolean isAllDigital(char[] chars) { boolean result = true; for (int w = 0; w < chars.length; w++) { if (!Character.isDigit(chars[w])) { result = false; break; } } return result; } /** * 刪除給定字符串中所有的舊的字符 * * @param string 源字符串 * @param ch 要刪除的字符 * @return 刪除后的字符串 */ public static String removeChar(String string, char ch) { StringBuffer sb = new StringBuffer(); for (char cha : string.toCharArray()) { if (cha != '-') { sb.append(cha); } } return sb.toString(); } /** * 刪除給定字符串中給定位置處的字符 * * @param string 給定字符串 * @param index 給定位置 */ public static String removeChar(String string, int index) { String result = null; char[] chars = string.toCharArray(); if (index == 0) { result = new String(chars, 1, chars.length - 1); } else if (index == chars.length - 1) { result = new String(chars, 0, chars.length - 1); } else { result = new String(chars, 0, index) + new String(chars, index + 1, chars.length - index); ; } return result; } /** * 刪除給定字符串中給定位置處的字符 * * @param string 給定字符串 * @param index 給定位置 * @param ch 如果同給定位置處的字符相同,則將給定位置處的字符刪除 */ public static String removeChar(String string, int index, char ch) { String result = null; char[] chars = string.toCharArray(); if (chars.length > 0 && chars[index] == ch) { if (index == 0) { result = new String(chars, 1, chars.length - 1); } else if (index == chars.length - 1) { result = new String(chars, 0, chars.length - 1); } else { result = new String(chars, 0, index) + new String(chars, index + 1, chars.length - index); ; } } else { result = string; } return result; } /** * 對給定的字符串進行空白過濾 * * @param string 給定的字符串 * @return 如果給定的字符串是一個空白字符串,那么返回null;否則返回本身。 */ public static String filterBlank(String string) { if ("".equals(string)) { return null; } else { return string; } } /** * 將給定字符串中給定的區(qū)域的字符轉(zhuǎn)換成小寫 * * @param str 給定字符串中 * @param beginIndex 開始索引(包括) * @param endIndex 結(jié)束索引(不包括) * @return 新的字符串 */ public static String toLowerCase(String str, int beginIndex, int endIndex) { return str.replaceFirst(str.substring(beginIndex, endIndex), str.substring(beginIndex, endIndex) .toLowerCase(Locale.getDefault())); } /** * 將給定字符串中給定的區(qū)域的字符轉(zhuǎn)換成大寫 * * @param str 給定字符串中 * @param beginIndex 開始索引(包括) * @param endIndex 結(jié)束索引(不包括) * @return 新的字符串 */ public static String toUpperCase(String str, int beginIndex, int endIndex) { return str.replaceFirst(str.substring(beginIndex, endIndex), str.substring(beginIndex, endIndex) .toUpperCase(Locale.getDefault())); } /** * 將給定字符串的首字母轉(zhuǎn)為小寫 * * @param str 給定字符串 * @return 新的字符串 */ public static String firstLetterToLowerCase(String str) { return toLowerCase(str, 0, 1); } /** * 將給定字符串的首字母轉(zhuǎn)為大寫 * * @param str 給定字符串 * @return 新的字符串 */ public static String firstLetterToUpperCase(String str) { return toUpperCase(str, 0, 1); } /** * 將給定的字符串MD5加密 * * @param string 給定的字符串 * @return MD5加密后生成的字符串 */ public static String MD5(String string) { String result = null; try { char[] charArray = string.toCharArray(); byte[] byteArray = new byte[charArray.length]; for (int i = 0; i < charArray.length; i++) { byteArray[i] = (byte) charArray[i]; } StringBuffer hexValue = new StringBuffer(); byte[] md5Bytes = MessageDigest.getInstance("MD5") .digest(byteArray); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } result = hexValue.toString(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * 判斷給定的字符串是否以一個特定的字符串開頭,忽略大小寫 * * @param sourceString 給定的字符串 * @param newString 一個特定的字符串 */ public static boolean startsWithIgnoreCase(String sourceString, String newString) { int newLength = newString.length(); int sourceLength = sourceString.length(); if (newLength == sourceLength) { return newString.equalsIgnoreCase(sourceString); } else if (newLength < sourceLength) { char[] newChars = new char[newLength]; sourceString.getChars(0, newLength, newChars, 0); return newString.equalsIgnoreCase(String.valueOf(newChars)); } else { return false; } } /** * 判斷給定的字符串是否以一個特定的字符串結(jié)尾,忽略大小寫 * * @param sourceString 給定的字符串 * @param newString 一個特定的字符串 */ public static boolean endsWithIgnoreCase(String sourceString, String newString) { int newLength = newString.length(); int sourceLength = sourceString.length(); if (newLength == sourceLength) { return newString.equalsIgnoreCase(sourceString); } else if (newLength < sourceLength) { char[] newChars = new char[newLength]; sourceString.getChars(sourceLength - newLength, sourceLength, newChars, 0); return newString.equalsIgnoreCase(String.valueOf(newChars)); } else { return false; } } /** * 檢查字符串長度,如果字符串的長度超過maxLength,就截取前maxLength個字符串并在末尾拼上appendString */ public static String checkLength(String string, int maxLength, String appendString) { if (string.length() > maxLength) { string = string.substring(0, maxLength); if (appendString != null) { string += appendString; } } return string; } /** * 檢查字符串長度,如果字符串的長度超過maxLength,就截取前maxLength個字符串并在末尾拼上… */ public static String checkLength(String string, int maxLength) { return checkLength(string, maxLength, "…"); } }
Android-StringUtil工具類
字符串處理相關(guān)的工具類:
public final class StringUtil { private static final String ALLCHAR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String CHINA_PHONE_REG = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$"; /** * 編譯后的正則表達式緩存 */ private static final Map<String, Pattern> PATTERN_CACHE = new ConcurrentHashMap<>(); private static final char CN_CHAR_START = '\u4e00'; private static final char CN_CHAR_END = '\u9fa5'; private static final int SECOND = 2; private static final int FF = 0xff; private StringUtil() { throw new UnsupportedOperationException("StringUtils cannot be instantiated"); } /** * 字符串是否為空 * * @param str 需要判斷的字符串 * @return true :空 */ public static boolean isEmpty(String str) { return null == str || TextUtils.isEmpty(str); } /** * 字符串是否非空 * * @param str 需要判斷的字符串 * @return true:非空 */ public static boolean isNotEmpty(String str) { return !isEmpty(str); } /** * 字符串是否相同 * * @param str 需要比較的字符串 * @param equalStr 被比較的字符串 * @return true:相等 */ public static boolean isEqual(String str, String equalStr) { if (StringUtil.isEmpty(str)) { return false; } return str.equals(equalStr); } /** * 字符串從左向右插入字符 * * @param index 要插入的位置 * @param oldString 舊字符串 * @param insertString 要插入的字符串 * @return 最終生成的字符串 */ public static String insertChar(int index, String oldString, String insertString) { StringBuffer buffer = new StringBuffer(oldString); for (int i = index; i < buffer.length(); i = i + index + 1) { buffer.insert(i, insertString); } return buffer.toString(); } /** * 翻轉(zhuǎn)字符串 * * @param str 需要翻轉(zhuǎn)的字符串 * @return 翻轉(zhuǎn)后的字符串 */ public static String reverseString(String str) { return new StringBuffer(str).reverse().toString(); } /** * 返回一個定長的隨機字符串(只包含大小寫字母、數(shù)字) * * @param length 隨機字符串長度 * @return 隨機字符串 */ public static String generateString(int length) { StringBuffer sb = new StringBuffer(); Random random = new Random(); for (int i = 0; i < length; i++) { sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length()))); } return sb.toString(); } /** * 判斷是否是手機號 * * @param phone 手機號 * @return true 是手機號 */ public static boolean isChinaPhone(String phone) { if (isEmpty(phone)) { return false; } Pattern pattern = compileRegex(CHINA_PHONE_REG); Matcher matcher = pattern.matcher(phone); return matcher.matches(); } /** * 檢測String是否全是中文 * * @param name 需要操作的字符串 * @return true 是全中文 */ public static boolean checkNameChese(String name) { boolean res = true; char[] cTemp = name.toCharArray(); for (int i = 0; i < name.length(); i++) { if (!isChinese(cTemp[i])) { res = false; break; } } return res; } /** * 判定輸入漢字 * * @param c 需要判斷的字符 * @return true 是漢字 */ public static boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { return true; } return false; } /** * 編譯一個正則表達式,并且進行緩存,如果緩存已存在則使用緩存 * * @param regex 表達式 * @return 編譯后的Pattern */ public static Pattern compileRegex(String regex) { Pattern pattern = PATTERN_CACHE.get(regex); if (pattern == null) { pattern = Pattern.compile(regex); PATTERN_CACHE.put(regex, pattern); } return pattern; } /** * 將字符串的第一位轉(zhuǎn)為小寫 * * @param str 需要轉(zhuǎn)換的字符串 * @return 轉(zhuǎn)換后的字符串 */ public static String toLowerCaseFirstOne(String str) { if (Character.isLowerCase(str.charAt(0))) { return str; } else { char[] chars = str.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } } /** * 將字符串的第一位轉(zhuǎn)為大寫 * * @param str 需要轉(zhuǎn)換的字符串 * @return 轉(zhuǎn)換后的字符串 */ public static String toUpperCaseFirstOne(String str) { if (Character.isUpperCase(str.charAt(0))) { return str; } else { char[] chars = str.toCharArray(); chars[0] = Character.toUpperCase(chars[0]); return new String(chars); } } /** * 下劃線命名轉(zhuǎn)為駝峰命名 * * @param str 下劃線命名格式 * @return 駝峰命名格式 */ public static String underScoreCase2CamelCase(String str) { if (!str.contains("_")) { return str; } StringBuilder sb = new StringBuilder(); char[] chars = str.toCharArray(); boolean hitUnderScore = false; sb.append(chars[0]); for (int i = 1; i < chars.length; i++) { char c = chars[i]; if (c == '_') { hitUnderScore = true; } else { if (hitUnderScore) { sb.append(Character.toUpperCase(c)); hitUnderScore = false; } else { sb.append(c); } } } return sb.toString(); } /** * 駝峰命名法轉(zhuǎn)為下劃線命名 * * @param str 駝峰命名格式 * @return 下劃線命名格式 */ public static String camelCase2UnderScoreCase(String str) { StringBuilder sb = new StringBuilder(); char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (Character.isUpperCase(c)) { sb.append("_").append(Character.toLowerCase(c)); } else { sb.append(c); } } return sb.toString(); } /** * 將異常棧信息轉(zhuǎn)為字符串 * * @param e 字符串 * @return 異常棧 */ public static String throwable2String(Throwable e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); return writer.toString(); } /** * 字符串連接,將參數(shù)列表拼接為一個字符串 * * @param more 追加 * @return 返回拼接后的字符串 */ public static String concat(Object... more) { return concatSpiltWith("", more); } /** * 字符串連接,將參數(shù)列表拼接為一個字符串 * * @param split 拼接的字符 * @param more 拼接的參數(shù)個數(shù) * @return 回拼接后的字符串 */ @NonNull public static String concatSpiltWith(String split, Object... more) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < more.length; i++) { if (i != 0) { buf.append(split); } buf.append(more[i]); } return buf.toString(); } /** * 將字符串轉(zhuǎn)移為ASCII碼 * * @param str 字符串 * @return 字符串ASCII碼 */ public static String toASCII(String str) { StringBuffer strBuf = new StringBuffer(); byte[] bGBK = str.getBytes(); for (int i = 0; i < bGBK.length; i++) { strBuf.append(Integer.toHexString(bGBK[i] & FF)); } return strBuf.toString(); } /** * 將字符串轉(zhuǎn)移為Unicode碼 * * @param str 字符串 * @return 返回Unicode 的字符串 */ public static String toUnicode(String str) { StringBuffer strBuf = new StringBuffer(); char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { strBuf.append("\\u").append(Integer.toHexString(chars[i])); } return strBuf.toString(); } /** * 將字符串轉(zhuǎn)移為Unicode碼 * * @param chars 字符數(shù)組 * @return 轉(zhuǎn)移為Unicode碼 字符串 */ public static String toUnicodeString(char[] chars) { StringBuffer strBuf = new StringBuffer(); for (int i = 0; i < chars.length; i++) { strBuf.append("\\u").append(Integer.toHexString(chars[i])); } return strBuf.toString(); } /** * 是否包含中文字符 * * @param str 要判斷的字符串 * @return 是否包含中文字符 */ public static boolean containsChineseChar(String str) { char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { if (chars[i] >= CN_CHAR_START && chars[i] <= CN_CHAR_END) { return true; } } return false; } /** * 對象是否為無效值 * * @param obj 要判斷的對象 * @return 是否為有效值(不為null 和 "" 字符串) */ public static boolean isNullOrEmpty(Object obj) { return obj == null || "".equals(obj.toString()); } /** * 參數(shù)是否是有效數(shù)字 (整數(shù)或者小數(shù)) * * @param obj 參數(shù)(對象將被調(diào)用string()轉(zhuǎn)為字符串類型) * @return 是否是數(shù)字 */ public static boolean isNumber(Object obj) { if (obj instanceof Number) { return true; } return isInt(obj) || isDouble(obj); } /** * 匹配到第一個字符串 * * @param patternStr 正則表達式 * @param text 字符串 * @return 返回字符串 */ public static String matcherFirst(String patternStr, String text) { Pattern pattern = compileRegex(patternStr); Matcher matcher = pattern.matcher(text); String group = null; if (matcher.find()) { group = matcher.group(); } return group; } /** * 參數(shù)是否是有效整數(shù) * * @param obj 參數(shù)(對象將被調(diào)用string()轉(zhuǎn)為字符串類型) * @return 是否是整數(shù) */ public static boolean isInt(Object obj) { if (isNullOrEmpty(obj)) { return false; } if (obj instanceof Integer) { return true; } return obj.toString().matches("[-+]?\\d+"); } /** * 字符串參數(shù)是否是double * * @param obj 參數(shù)(對象將被調(diào)用string()轉(zhuǎn)為字符串類型) * @return 是否是double */ public static boolean isDouble(Object obj) { if (isNullOrEmpty(obj)) { return false; } if (obj instanceof Double || obj instanceof Float) { return true; } return compileRegex("[-+]?\\d+\\.\\d+").matcher(obj.toString()).matches(); } /** * 判斷一個對象是否為boolean類型,包括字符串中的true和false * * @param obj 要判斷的對象 * @return 是否是一個boolean類型 */ public static boolean isBoolean(Object obj) { if (obj instanceof Boolean) { return true; } String strVal = String.valueOf(obj); return "true".equalsIgnoreCase(strVal) || "false".equalsIgnoreCase(strVal); } /** * 對象是否為true * * @param obj 判斷的對象 * @return true 是 */ public static boolean isTrue(Object obj) { return "true".equals(String.valueOf(obj)); } /** * 判斷一個數(shù)組里是否包含指定對象 * * @param arr 對象數(shù)組 * @param obj 要判斷的對象 * @return 是否包含 */ public static boolean contains(Object obj, Object... arr) { if (arr == null || obj == null || arr.length == 0) { return false; } return Arrays.asList(arr).containsAll(Arrays.asList(obj)); } /** * 將對象轉(zhuǎn)為int值,如果對象無法進行轉(zhuǎn)換,則使用默認值 * * @param object 要轉(zhuǎn)換的對象 * @param defaultValue 默認值 * @return 轉(zhuǎn)換后的值 */ public static int toInt(Object object, int defaultValue) { int returnValue = defaultValue; if (object instanceof Number) { returnValue = ((Number) object).intValue(); } if (isInt(object)) { returnValue = Integer.parseInt(object.toString()); } if (isDouble(object)) { returnValue = (int) Double.parseDouble(object.toString()); } return returnValue; } /** * 將對象轉(zhuǎn)為int值,如果對象不能轉(zhuǎn)為,將返回0 * * @param object 要轉(zhuǎn)換的對象 * @return 轉(zhuǎn)換后的值 */ public static int toInt(Object object) { return toInt(object, 0); } /** * 將對象轉(zhuǎn)為long類型,如果對象無法轉(zhuǎn)換,將返回默認值 * * @param object 要轉(zhuǎn)換的對象 * @param defaultValue 默認值 * @return 轉(zhuǎn)換后的值 */ public static long toLong(Object object, long defaultValue) { long returnValue = defaultValue; if (object instanceof Number) { returnValue = ((Number) object).longValue(); } if (isInt(object)) { returnValue = Long.parseLong(object.toString()); } if (isDouble(object)) { returnValue = (long) Double.parseDouble(object.toString()); } return returnValue; } /** * 將對象轉(zhuǎn)為 long值,如果無法轉(zhuǎn)換,則轉(zhuǎn)為0 * * @param object 要轉(zhuǎn)換的對象 * @return 轉(zhuǎn)換后的值 */ public static long toLong(Object object) { return toLong(object, 0); } /** * 將對象轉(zhuǎn)為Double,如果對象無法轉(zhuǎn)換,將使用默認值 * * @param object 要轉(zhuǎn)換的對象 * @param defaultValue 默認值 * @return 轉(zhuǎn)換后的值 */ public static double toDouble(Object object, double defaultValue) { double returnValue = defaultValue; if (object instanceof Number) { returnValue = ((Number) object).doubleValue(); } if (isNumber(object)) { returnValue = Double.parseDouble(object.toString()); } if (null == object) { returnValue = defaultValue; } return returnValue; } /** * 將對象轉(zhuǎn)為Double,如果對象無法轉(zhuǎn)換,將使用默認值0 * * @param object 要轉(zhuǎn)換的對象 * @return 轉(zhuǎn)換后的值 */ public static double toDouble(Object object) { return toDouble(object, 0); } /** * 分隔字符串,根據(jù)正則表達式分隔字符串,只分隔首個,剩下的的不進行分隔, * 如: 1,2,3,4 將分隔為 ['1','2,3,4'] * * @param str 要分隔的字符串 * @param regex 分隔表達式 * @return 分隔后的數(shù)組 */ public static String[] splitFirst(String str, String regex) { return str.split(regex, SECOND); } /** * 將對象轉(zhuǎn)為字符串,如果對象為null,則返回null,而不是"null" * * @param object 要轉(zhuǎn)換的對象 * @return 轉(zhuǎn)換后的對象 */ public static String toString(Object object) { return toString(object, null); } /** * 將對象轉(zhuǎn)為字符串,如果對象為null,則使用默認值 * * @param object 要轉(zhuǎn)換的對象 * @param defaultValue 默認值 * @return 轉(zhuǎn)換后的字符串 */ public static String toString(Object object, String defaultValue) { if (object == null) { return defaultValue; } return String.valueOf(object); } /** * 將對象轉(zhuǎn)為String后進行分割,如果為對象為空或者空字符,則返回null * * @param object 要分隔的對象 * @param regex 分隔規(guī)則 * @return 分隔后的對象 */ public static String[] toStringAndSplit(Object object, String regex) { if (isNullOrEmpty(object)) { return null; } return String.valueOf(object).split(regex); } private static final float MESSY_PERCENT = 0.4f; /** * 是否為亂碼 * * @param strName 需要判斷的字符串 * @return true 是亂碼 */ public static boolean isMessyCode(String strName) { Pattern p = compileRegex("\\s*|\t*|\r*|\n*"); Matcher m = p.matcher(strName); String after = m.replaceAll(""); String temp = after.replaceAll("\\p{P}", ""); char[] ch = temp.trim().toCharArray(); float chLength = 0; float count = 0; for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (!Character.isLetterOrDigit(c)) { if (!isChinese(c)) { count = count + 1; } chLength++; } } float result = count / chLength; return result >= MESSY_PERCENT; } }
Android-TimeUtil工具類
與時間處理相關(guān)的工具類:
public class TimeUtil { /** * 獲取當前時間 * @return */ public static String getNowTime(){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(System.currentTimeMillis()); return simpleDateFormat.format(date); } /** * 獲取當前時間 * @return */ public static String getThisTiem() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss // 獲取當前時間 Date date = new Date(System.currentTimeMillis()); return simpleDateFormat.format(date); } /** * 獲取時間戳 * * @return 獲取時間戳 */ public static String getTimeString() { SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); Calendar calendar = Calendar.getInstance(); return df.format(calendar.getTime()); } /** * 獲取時間戳 * * @return 獲取時間戳 */ public static String getTimeString2() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); return df.format(calendar.getTime()); } /** * 時間轉(zhuǎn)換為時間戳 * @param time:需要轉(zhuǎn)換的時間 * @return */ public static String dateToStamp(String time) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = simpleDateFormat.parse(time); } catch (ParseException e) { e.printStackTrace(); } long ts = date.getTime(); return String.valueOf(ts); } /** * 時間戳轉(zhuǎn)換為字符串 * @param time:時間戳 * @return */ public static String times(String time) { SimpleDateFormat sdr = new SimpleDateFormat("yyyy年MM月dd日 HH時mm分"); @SuppressWarnings("unused") long lcc = Long.valueOf(time); int i = Integer.parseInt(time); String times = sdr.format(new Date(i * 1000L)); return times; } /** *獲取距現(xiàn)在某一小時的時刻 * @param hour hour=-1為上一個小時,hour=1為下一個小時 * @return */ public static String getLongTime(int hour){ Calendar c = Calendar.getInstance(); // 當時的日期和時間 int h; // 需要更改的小時 h = c.get(Calendar.HOUR_OF_DAY) - hour; c.set(Calendar.HOUR_OF_DAY, h); SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); Log.v("time",df.format(c.getTime())); return df.format(c.getTime()); } /** * 比較時間大小 * @param str1:要比較的時間 * @param str2:要比較的時間 * @return */ public static boolean isDateOneBigger(String str1, String str2) { boolean isBigger = false; SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); Date dt1 = null; Date dt2 = null; try { dt1 = sdf.parse(str1); dt2 = sdf.parse(str2); } catch (ParseException e) { e.printStackTrace(); } if (dt1.getTime() > dt2.getTime()) { isBigger = true; } else if (dt1.getTime() < dt2.getTime()) { isBigger = false; } return isBigger; } /** * 當?shù)貢r間 ---> UTC時間 * @return */ public static String Local2UTC(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("gmt")); String gmtTime = sdf.format(new Date()); return gmtTime; } /** * UTC時間 ---> 當?shù)貢r間 * @param utcTime UTC時間 * @return */ public static String utc2Local(String utcTime) { SimpleDateFormat utcFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//UTC時間格式 utcFormater.setTimeZone(TimeZone.getTimeZone("UTC")); Date gpsUTCDate = null; try { gpsUTCDate = utcFormater.parse(utcTime); } catch (ParseException e) { e.printStackTrace(); } SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//當?shù)貢r間格式 localFormater.setTimeZone(TimeZone.getDefault()); String localTime = localFormater.format(gpsUTCDate.getTime()); return localTime; } }
Android-UIUtils
所有與UI相關(guān)操縱的工具類,通常情況下是在Activity中使用:
public class UIUtils { private static final String TAG = UIUtils.class.getSimpleName(); /** * 通過ID獲取顏色值 * @param colorId * @return */ public static int getColor(Context mContext, int colorId) { return mContext.getResources().getColor(colorId); } /** * 通過ID獲取View * @param layoutId * @return */ public static View getXmlVIew(Context mContext, int layoutId) { return View.inflate(mContext, layoutId, null); } /** * 通過ID獲取 View Item 布局的View * @param mContext * @param layoutId * @return */ public static View getItemView(Context mContext, int layoutId) { return LayoutInflater.from(mContext).inflate(layoutId, null); } /** * dp轉(zhuǎn)換px * @param dp * @return */ public static int dp2px(Context mContext, int dp) { float density = mContext.getResources().getDisplayMetrics().density; return (int) (dp*density+0.5); } /** * px轉(zhuǎn)換dp * @param px * @return */ public static int px2dp(Context mContext, int px) { float density = mContext.getResources().getDisplayMetrics().density; return (int) (px/density+0.5); } /** * 通過arrayId獲取string.xml里面指定的arrayId字符串數(shù)組 * @param arrayId * @return */ public static String[] getStringArray(Context mContext, int arrayId) { return mContext.getResources().getStringArray(arrayId); } /** * 用于跳轉(zhuǎn)Activity * @param cls */ public static void startActivity(Activity activity, Class<?> cls) { activity.startActivity(new Intent(activity, cls)); } /** * 用于ForResult方式跳轉(zhuǎn)Activity * @param activity * @param cls * @param requestCode */ public static void startActivityForResult(Activity activity, Class<?> cls, int requestCode) { activity.startActivityForResult(new Intent(activity, cls), requestCode); } /** * 待參數(shù)的方式跳轉(zhuǎn)Activity * @param activity * @param cls * @param params * @param <T> */ public static <T extends String> void startActivityForIntentParam(Activity activity, Class<?> cls, Map<String, T> params) { Intent intent = new Intent(activity, cls); for (Map.Entry<String, T> entry : params.entrySet()) { intent.putExtra(entry.getKey(), entry.getValue()); } activity.startActivity(intent); } /** * 獲取其他Activity傳過來的參數(shù),轉(zhuǎn)成Map集合 * @param activity * @param params * @return */ public static Map receiveForIntentParam(Activity activity, String ... params) { Intent intent = activity.getIntent(); Map<String, String> mMap = new HashMap<>(); for (int i = 0; i<params.length; i++) { mMap.put(params[i], intent.getStringExtra(params[i])); } return mMap.size()==0?null:mMap; } /** * 設(shè)置EditText的hint字體大小 * @param editText * @param dpSize * @param textString */ public static void setEditTextHint(EditText editText, int dpSize,String textString) { SpannableString ss = new SpannableString(textString); AbsoluteSizeSpan ass = new AbsoluteSizeSpan(dpSize, true); ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_USER); editText.setHint(new SpannedString(ss)); } /** * 設(shè)置EditText的hint顏色與字體大小 * @param editText * @param color * @param dpSize * @param textString */ public static void setEditTextHint(EditText editText, int color, int dpSize,String textString) { SpannableString ss = new SpannableString(textString); AbsoluteSizeSpan ass = new AbsoluteSizeSpan(dpSize, true); editText.setHintTextColor(color); ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_USER); editText.setHint(new SpannedString(ss)); } /** * 設(shè)置EditText的hint顏色與字體大小 * @param editText * @param color * @param dpSize * @param textString * @param isDip */ public static void setEditTextHint(EditText editText, int color, int dpSize,String textString, boolean isDip) { SpannableString ss = new SpannableString(textString); AbsoluteSizeSpan ass = new AbsoluteSizeSpan(dpSize, isDip); editText.setHintTextColor(color); ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); editText.setHint(new SpannedString(ss)); }
Android-WebViewUtils工具類
/** * WebView操作處理相關(guān)工具類 */ public class WebViewUtils extends WebView{ public WebViewUtils(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public WebViewUtils(Context context) { super(context); } public WebViewUtils(Context context, AttributeSet attrs) { super(context, attrs); } /** * 初始化webview * @param url * @param openWay:true :在webview打開,false在手機默認瀏覽器打開 */ public void initWebView(final ProgressBar progressBar,final String url, final boolean openWay){ this.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { progressBar.setVisibility(View.INVISIBLE); } else { if (View.INVISIBLE == progressBar.getVisibility()) { progressBar.setVisibility(View.VISIBLE); } progressBar.setProgress(newProgress); } super.onProgressChanged(view, newProgress); } }); this.post(new Runnable() { @Override public void run() { WebViewUtils.this.loadUrl(url); } }); this.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return openWay; } }); } /** * 得到html并顯示到webView中 * @param url 要打開html的路徑 * @param web WebView控件 */ public static void getHtml( String url , WebView web){ initSetting(web); web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//設(shè)置js可以直接打開窗口,如window.open(),默認為false web.getSettings().setSupportZoom(true);// 是否可以縮放,默認true web.getSettings().setBuiltInZoomControls(true);// 是否顯示縮放按鈕,默認false web.getSettings().setUseWideViewPort(true);// 設(shè)置此屬性,可任意比例縮放。大視圖模式 web.getSettings().setLoadWithOverviewMode(true);// 和setUseWideViewPort(true)一起解決網(wǎng)頁自適應(yīng)問題 web.getSettings().setAppCacheEnabled(true);// 是否使用緩存 web.getSettings().setDomStorageEnabled(true);// DOM Storage // w.getSettings().setUserAgentString("User-Agent:Android");//設(shè)置用戶代理,一般不用 web.loadUrl(url); web.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub //返回值是true的時候控制去WebView打開,為false調(diào)用系統(tǒng)瀏覽器或第三方瀏覽器 view.loadUrl(url); return true; } }); } /** * 設(shè)置webView初始值信息 * @param web */ private static void initSetting(WebView web) { // TODO Auto-generated method stub WebSettings settings = web.getSettings(); // 是否允許執(zhí)行js,默認為false。設(shè)置true時,會提醒可能造成XSS漏洞 settings.setJavaScriptEnabled(true); /* * LOAD_DEFAULT設(shè)置如何緩存 默認使用緩存,當緩存沒有,或者緩存過期,才使用網(wǎng)絡(luò) * LOAD_CACHE_ELSE_NETWORK 設(shè)置默認使用緩存,即使是緩存過期,也使用緩存 * 只有緩存消失,才使用網(wǎng)絡(luò) */ settings.setCacheMode(WebSettings.LOAD_DEFAULT); //是否展示一個縮放按鈕() settings.setBuiltInZoomControls(true); } /** * 設(shè)置webView初始值信息并且綁定url等操作 * @param webView * @param url */ public static void initSetting(WebView webView, String url) { // 登錄西安交通發(fā)布,查詢交通 // webView.loadUrl("https://www.xaglkp.com.cn/BusPage/bus_realtime"); webView.loadUrl(url); webView.requestFocus();//獲取焦點 webView.setHorizontalScrollBarEnabled(false); webView.setVerticalScrollBarEnabled(false); webView.setVerticalScrollbarOverlay(true); //添加客戶端支持 webView.setWebViewClient(new WebViewClient(){ //點擊不會跳轉(zhuǎn)到瀏覽器外 @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true;//super.shouldOverrideUrlLoading(view, url); } }); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); //設(shè)置可以訪問文件 webSettings.setAllowFileAccess(true); //設(shè)置支持縮放 webSettings.setBuiltInZoomControls(true); webSettings.setUseWideViewPort(true); //設(shè)置加載進來的頁面自適應(yīng)手機屏幕(可縮放) webSettings.setLoadWithOverviewMode(true); } /** * 返回Html的上一個頁面 * @param webView */ public static void backHtml(WebView webView) { webView.goBack();// 返回前一個頁面 } }
Android-XmlUtil工具類
/** * XML文件工具類,包含:將xml文件解析成實體集合、獲取xml標簽值、將標簽值解析成實體集合 */ public class XmlUtil { private XmlUtil(){} /*- * XML文件解析成實體,不涉及到標簽的屬性值。 * @param xml xml字符串文件 * @param clazz 對應(yīng)實體的class文件 * @param tagEntity * 開始解析實體的標簽,例如下面的實例中就是student<br> * <person> * <student> * <name>Lucy</name> * <age>21</age> * </student> * </person> * @return 返回解析的對應(yīng)實體文件 */ public static<T> List<T> xmlToObject(String xml, Class<T> clazz, String tagEntity){ List<T> list = null; XmlPullParser xmlPullParser = Xml.newPullParser(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); try { xmlPullParser.setInput(inputStream, "utf-8"); Field[] fields = clazz.getDeclaredFields(); int type = xmlPullParser.getEventType(); String lastTag = ""; T t = null; while (type != XmlPullParser.END_DOCUMENT) { switch (type) { case XmlPullParser.START_DOCUMENT: list = new ArrayList<T>(); break; case XmlPullParser.START_TAG: String tagName = xmlPullParser.getName(); if(tagEntity.equals(tagName)){ t = clazz.newInstance(); lastTag = tagEntity; }else if(tagEntity.equals(lastTag)){ String textValue = xmlPullParser.nextText(); String fieldName = xmlPullParser.getName(); for(Field field : fields){ ReflectUtil.setFieldValue(t,field,fieldName,textValue); } } break; case XmlPullParser.END_TAG: tagName = xmlPullParser.getName(); if(tagEntity.equals(tagName)){ list.add(t); lastTag = ""; } break; case XmlPullParser.END_DOCUMENT: break; } } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return list; } /** * 獲取xml字符串標簽中的屬性值 * @param xml xml字符串 * @param clazz 轉(zhuǎn)換成對應(yīng)的實體 * @param tagName 實體對應(yīng)xml字符串的起始標簽,如下面實例中的person標簽<br> * <person name="Lucy" age="12"> * <student> * <name>Lucy</name> * <age>21</age> * </student> * </person> * @return 返回屬性值組成的List對象集合。 */ public static<T> List<T> attributeToObject(String xml, Class<T> clazz, String tagName){ if(TextUtils.isEmpty(tagName))return null; List<T> list = null; XmlPullParser xmlPullParser = Xml.newPullParser(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); try { xmlPullParser.setInput(inputStream, "utf-8"); int type = xmlPullParser.getEventType(); T t = null; while(type != XmlPullParser.END_DOCUMENT){ switch(type){ case XmlPullParser.START_DOCUMENT: list = new ArrayList<T>(); break; case XmlPullParser.START_TAG: if(tagName.equals(xmlPullParser.getName())){ t = clazz.newInstance(); Field[] fields = clazz.getDeclaredFields(); for(Field field : fields){ String fieldName = field.getName(); for(int index = 0;index < xmlPullParser.getAttributeCount();index++){ if(fieldName.equals(xmlPullParser.getAttributeName(index))){ ReflectUtil.setFieldValue(t,field,fieldName,xmlPullParser.getAttributeValue(index)); } } } } break; case XmlPullParser.END_TAG: if(tagName.equals(xmlPullParser.getName())){ list.add(t); } break; case XmlPullParser.END_DOCUMENT: break; } type = xmlPullParser.next(); } }catch(Exception ex){ ex.printStackTrace(); } return list; } /** * 獲取Xml文件中的屬性值 * @param xml xml文件字符串 * @param tagName 標簽名稱 * @param attributeName 屬性名稱 * @return 返回獲取的值,或者null */ public static String getTagAttribute(String xml, String tagName, String attributeName){ if(TextUtils.isEmpty(tagName) || TextUtils.isEmpty(attributeName)){ throw new IllegalArgumentException("請?zhí)顚憳撕灻Q或?qū)傩悦Q"); } XmlPullParser xmlPullParser = Xml.newPullParser(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); try { xmlPullParser.setInput(inputStream, "utf-8"); int type = xmlPullParser.getEventType(); while(type != XmlPullParser.END_DOCUMENT){ switch(type){ case XmlPullParser.START_TAG: if(tagName.equals(xmlPullParser.getName())){ for(int i=0; i < xmlPullParser.getAttributeCount();i++){ if(attributeName.equals(xmlPullParser.getAttributeName(i))){ return xmlPullParser.getAttributeValue(i); } } } break; } type = xmlPullParser.next(); } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Android使用CountDownTimer實現(xiàn)倒數(shù)定時器效果
這篇文章主要介紹了Android使用CountDownTimer實現(xiàn)倒數(shù)定時器效果的資料,這里整理了詳細的代碼,有需要的小伙伴可以參考下。2017-02-02Android操作系統(tǒng)的架構(gòu)設(shè)計分析
這篇文章主要介紹了Android操作系統(tǒng)的架構(gòu)設(shè)計分析,Android系統(tǒng)架構(gòu)分為Linux內(nèi)核驅(qū)動、C/C ++框架、Java框架、Java應(yīng)用程序,本文分別講解了它的作用,需要的朋友可以參考下2015-06-06Android ViewPager實現(xiàn)無限循環(huán)效果
這篇文章主要為大家詳細介紹了Android ViewPager實現(xiàn)無限循環(huán)效果的相關(guān)資料,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-03-03