1.屏幕相關
package com.example.coshenwancheng.utils; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.graphics.Rect; import android.util.DisplayMetrics; import android.view.Window; /** * @desc: 屏幕相關 */ public class DisplayUtils { /** * 是否橫屏 * * @param context * @return */ public static boolean isLandscape(Context context) { return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; } /** * 是否豎屏 * * @param context * @return */ public static boolean isPortrait(Context context) { return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; } /** * Get screen width, in pixels * * @param context * @return */ public static int getScreenWidth(Context context) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); return dm.widthPixels; } /** * Get screen height, in pixels * * @param context * @return */ public static int getScreenHeight(Context context) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); return dm.heightPixels; } /** * Get screen density, the logical density of the display * * @param context * @return */ public static float getScreenDensity(Context context) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); return dm.density; } /** * Get screen density dpi, the screen density expressed as dots-per-inch * * @param context * @return */ public static int getScreenDensityDPI(Context context) { DisplayMetrics dm = context.getResources().getDisplayMetrics(); return dm.densityDpi; } /** * Get titlebar height, this method cannot be used in onCreate(),onStart(),onResume(), unless it is called in the * post(Runnable). * * @param activity * @return */ public static int getTitleBarHeight(Activity activity) { int statusBarHeight = getStatusBarHeight(activity); int contentViewTop = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); int titleBarHeight = contentViewTop - statusBarHeight; return titleBarHeight < 0 ? 0 : titleBarHeight; } /** * Get statusbar height, this method cannot be used in onCreate(),onStart(),onResume(), unless it is called in the * post(Runnable). * * @param activity * @return */ public static int getStatusBarHeight(Activity activity) { Rect rect = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); return rect.top; } /** * Get statusbar height * * @param activity * @return */ public static int getStatusBarHeight2(Activity activity) { int statusBarHeight = getStatusBarHeight(activity); if (0 == statusBarHeight) { Class<?> localClass; try { localClass = Class.forName("com.android.internal.R$dimen"); Object localObject = localClass.newInstance(); int id = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString()); statusBarHeight = activity.getResources().getDimensionPixelSize(id); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } return statusBarHeight; } /** * Convert dp to px by the density of phone * * @param context * @param dp * @return */ public static int dip2px(Context context, float dp) { if (context == null) { return -1; } return (int) (dipToPx(context, dp) + 0.5f); } /** * Convert dp to px * * @param context * @param dp * @return */ private static float dipToPx(Context context, float dp) { if (context == null) { return -1; } float scale = context.getResources().getDisplayMetrics().density; return dp * scale; } /** * Convert px to dp by the density of phone * * @param context * @param px * @return */ public static int px2dip(Context context, float px) { if (context == null) { return -1; } return (int) (pxToDip(context, px) + 0.5f); } /** * Convert px to dp * * @param context * @param px * @return */ private static float pxToDip(Context context, float px) { if (context == null) { return -1; } float scale = context.getResources().getDisplayMetrics().density; return px / scale; } /** * Convert px to sp * * @param context * @param px * @return */ public static int px2sp(Context context, float px) { return (int) (pxToSp(context, px) + 0.5f); } /** * Convert px to sp * * @param context * @param px * @return */ private static float pxToSp(Context context, float px) { float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return px / fontScale; } /** * Convert sp to px * * @param context * @param sp * @return */ public static int sp2px(Context context, float sp) { return (int) (spToPx(context, sp) + 0.5f); } /** * Convert sp to px * * @param context * @param sp * @return */ private static float spToPx(Context context, float sp) { float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return sp * fontScale; } }
2獲取文件大小的類
/* * Copyright 2016 北京博瑞彤芸文化傳播股份有限公司 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.example.coshenwancheng.utils; import android.text.TextUtils; import java.io.File; import java.io.IOException; import java.math.BigDecimal; /** * @description 獲取文件大小的類 */ public class FileSize { public static final long SIZE_BT = 1024L; public static final long SIZE_KB = SIZE_BT * 1024L; public static final long SIZE_MB = SIZE_KB * 1024L; public static final long SIZE_GB = SIZE_MB * 1024L; public static final long SIZE_TB = SIZE_GB * 1024L; public static final int SACLE = 2; private File file; private long longSize; public FileSize(File file) { this.file = file; } private void getFileSize() throws RuntimeException, IOException { getFileSize(file); } private void getFileSize(File file) { if (file == null || !file.exists()) { return; } if (file.isFile()) { this.longSize += file.length(); return; } File[] childArray = file.listFiles(); if (childArray == null || childArray.length == 0) { return; } for (File child : childArray) { getFileSize(child); } } public String toString() throws RuntimeException { try { try { getFileSize(); } catch (RuntimeException e) { return ""; } return convertSizeToString(this.longSize); } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex.getMessage()); } } /** * 格式化輸出文件大小 * @param fileSize * @return */ public static String convertSizeToString(long fileSize) { if (fileSize >= 0 && fileSize < SIZE_BT) { return fileSize + "B"; } else if (fileSize >= SIZE_BT && fileSize < SIZE_KB) { return fileSize / SIZE_BT + "KB"; } else if (fileSize >= SIZE_KB && fileSize < SIZE_MB) { return fileSize / SIZE_KB + "MB"; } else if (fileSize >= SIZE_MB && fileSize < SIZE_GB) { BigDecimal longs = new BigDecimal(Double.valueOf(fileSize + "").toString()); BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_MB + "").toString()); String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString(); // double result=this.longSize/(double)SIZE_MB; return result + "GB"; } else { BigDecimal longs = new BigDecimal(Double.valueOf(fileSize + "").toString()); BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_GB + "").toString()); String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString(); return result + "TB"; } } /** * MB轉KB * @param fileSize * @return */ public static double getKBSize(String fileSize) { if (TextUtils.isEmpty(fileSize)) { return 0; } fileSize = fileSize.toUpperCase(); int index; if ((index = fileSize.indexOf("MB")) > 0) { String str = fileSize.substring(0, index).trim(); return string2double(str) * 1024; } if ((index = fileSize.indexOf("KB")) > 0) { String str = fileSize.substring(0, index).trim(); return string2double(str); } return 0; } public static double string2double(String doubleStr) { try { return Double.valueOf(doubleStr); } catch (Exception e) { } return 0; } /** * 獲取文件的大小單位是byte * @return 返回文件的大小 * @throws RuntimeException */ public long getLongSize() throws RuntimeException { try { getFileSize(); return longSize; } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex.getMessage()); } } }
3文件工具類
package com.example.coshenwancheng.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; /** * @desc: 文件工具類 */ public class FileUtils { public final static String FILE_SUFFIX_SEPARATOR = "."; /** * Read file * * @param filePath * @param charsetName * @return */ public static StringBuilder readFile(String filePath, String charsetName) { File file = new File(filePath); StringBuilder fileContent = new StringBuilder(""); if (file == null || !file.isFile()) { return null; } BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { if (!fileContent.toString().equals("")) { fileContent.append("\r\n"); } fileContent.append(line); } return fileContent; } catch (IOException e) { throw new RuntimeException("IOException", e); } finally { IOUtils.close(reader); } } /** * Write file * * @param filePath * @param content * @param append * @return */ public static boolean writeFile(String filePath, String content, boolean append) { if (StringUtils.isEmpty(content)) { return false; } FileWriter fileWriter = null; try { makeDirs(filePath); fileWriter = new FileWriter(filePath, append); fileWriter.write(content); return true; } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { IOUtils.close(fileWriter); } } /** * write file, the string will be written to the begin of the file * * @param filePath * @param content * @return */ public static boolean writeFile(String filePath, String content) { return writeFile(filePath, content, false); } /** * Write file * * @param filePath * @param is * @return */ public static boolean writeFile(String filePath, InputStream is) { return writeFile(filePath, is, false); } /** * Write file * * @param filePath * @param is * @param append * @return */ public static boolean writeFile(String filePath, InputStream is, boolean append) { return writeFile(filePath != null ? new File(filePath) : null, is, append); } /** * Write file * * @param file * @param is * @return */ public static boolean writeFile(File file, InputStream is) { return writeFile(file, is, false); } /** * Write file * * @param file * @param is * @param append * @return */ public static boolean writeFile(File file, InputStream is, boolean append) { OutputStream o = null; try { makeDirs(file.getAbsolutePath()); o = new FileOutputStream(file, append); byte data[] = new byte[1024]; int length = -1; while ((length = is.read(data)) != -1) { o.write(data, 0, length); } o.flush(); return true; } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException", e); } catch (IOException e) { throw new RuntimeException("IOException", e); } finally { IOUtils.close(o); IOUtils.close(is); } } /** * Move file * * @param srcFilePath * @param destFilePath */ public static void moveFile(String srcFilePath, String destFilePath) throws FileNotFoundException { if (StringUtils.isEmpty(srcFilePath) || StringUtils.isEmpty(destFilePath)) { throw new RuntimeException("Both srcFilePath and destFilePath cannot be null."); } moveFile(new File(srcFilePath), new File(destFilePath)); } /** * Move file * * @param srcFile * @param destFile */ public static void moveFile(File srcFile, File destFile) throws FileNotFoundException { boolean rename = srcFile.renameTo(destFile); if (!rename) { copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); deleteFile(srcFile.getAbsolutePath()); } } /** * Copy file * * @param srcFilePath * @param destFilePath * @return * @throws FileNotFoundException */ public static boolean copyFile(String srcFilePath, String destFilePath) throws FileNotFoundException { InputStream inputStream = new FileInputStream(srcFilePath); return writeFile(destFilePath, inputStream); } /** * rename file * * @param file * @param newFileName * @return */ public static boolean renameFile(File file, String newFileName) { File newFile = null; if (file.isDirectory()) { newFile = new File(file.getParentFile(), newFileName); } else { String temp = newFileName + file.getName().substring( file.getName().lastIndexOf('.')); newFile = new File(file.getParentFile(), temp); } if (file.renameTo(newFile)) { return true; } return false; } /** * Get file name without suffix * * @param filePath * @return */ public static String getFileNameWithoutSuffix(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR); int fp = filePath.lastIndexOf(File.separator); if (fp == -1) { return (suffix == -1 ? filePath : filePath.substring(0, suffix)); } if (suffix == -1) { return filePath.substring(fp + 1); } return (fp < suffix ? filePath.substring(fp + 1, suffix) : filePath.substring(fp + 1)); } /** * Get file name * * @param filePath * @return */ public static String getFileName(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int fp = filePath.lastIndexOf(File.separator); return (fp == -1) ? filePath : filePath.substring(fp + 1); } /** * Get folder name * * @param filePath * @return */ public static String getFolderName(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int fp = filePath.lastIndexOf(File.separator); return (fp == -1) ? "" : filePath.substring(0, fp); } /** * Get suffix of file * * @param filePath * @return */ public static String getFileSuffix(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR); int fp = filePath.lastIndexOf(File.separator); if (suffix == -1) { return ""; } return (fp >= suffix) ? "" : filePath.substring(suffix + 1); } /** * Create the directory * * @param filePath * @return */ public static boolean makeDirs(String filePath) { String folderName = getFolderName(filePath); if (StringUtils.isEmpty(folderName)) { return false; } File folder = new File(folderName); return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs(); } /** * Judge whether a file is exist * * @param filePath * @return */ public static boolean isFileExist(String filePath) { if (StringUtils.isEmpty(filePath)) { return false; } File file = new File(filePath); return (file.exists() && file.isFile()); } /** * Judge whether a folder is exist * * @param directoryPath * @return */ public static boolean isFolderExist(String directoryPath) { if (StringUtils.isEmpty(directoryPath)) { return false; } File dire = new File(directoryPath); return (dire.exists() && dire.isDirectory()); } /** * Delete file or folder * * @param path * @return */ public static boolean deleteFile(String path) { if (StringUtils.isEmpty(path)) { return true; } File file = new File(path); if (!file.exists()) { return true; } if (file.isFile()) { return file.delete(); } if (!file.isDirectory()) { return false; } if (file.isDirectory()) { for (File f : file.listFiles()) { if (f.isFile()) { f.delete(); } else if (f.isDirectory()) { deleteFile(f.getAbsolutePath()); } } } return file.delete(); } /** * Delete file or folder * * @param file * @return */ public static boolean deleteFile(File file) { if (!file.exists()) { return true; } if (file.isFile()) { return file.delete(); } if (!file.isDirectory()) { return false; } if (file.isDirectory()) { File[] childFile = file.listFiles(); if (childFile == null || childFile.length == 0) { return file.delete(); } for (File f : childFile) { deleteFile(f); } } return file.delete(); } /** * Get file size * * @param path * @return */ public static long getFileSize(String path) { if (StringUtils.isEmpty(path)) { return -1; } File file = new File(path); return (file.exists() && file.isFile() ? file.length() : -1); } /** * Get folder size * * @param file * @return * @throws Exception */ public static long getFolderSize(File file) throws Exception { long size = 0; try { File[] fileList = file.listFiles(); for (int i = 0; i < fileList.length; i++) { if (fileList[i].isDirectory()) { size = size + getFolderSize(fileList[i]); } else { size = size + fileList[i].length(); } } } catch (Exception e) { e.printStackTrace(); } return size; } }
4Http請求的工具類
package com.example.coshenwancheng.utils; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; /** * Http請求的工具類 */ public class HttpUtils { private static final int TIMEOUT_IN_MILLIONS = 5000; public interface CallBack { void onRequestComplete(String result); } /** * 異步的Get請求 * * @param urlStr * @param callBack */ public static void doGetAsyn(final String urlStr, final CallBack callBack) { new Thread() { @Override public void run() { try { String result = doGet(urlStr); if (callBack != null) { callBack.onRequestComplete(result); } } catch (Exception e) { e.printStackTrace(); } }; }.start(); } /** * 異步的Post請求 * @param urlStr * @param params * @param callBack * @throws Exception */ public static void doPostAsyn(final String urlStr, final String params, final CallBack callBack) throws Exception { new Thread() { @Override public void run() { try { String result = doPost(urlStr, params); if (callBack != null) { callBack.onRequestComplete(result); } } catch (Exception e) { e.printStackTrace(); } }; }.start(); } /** * Get請求,獲得返回數據 * * @param urlStr * @return * @throws Exception */ public static String doGet(String urlStr) { URL url = null; HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toString(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { } try { if (baos != null) { baos.close(); } } catch (IOException e) { } conn.disconnect(); } return null ; } /** * 向指定 URL 發送POST方法的請求 * * @param url * 發送請求的 URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return 所代表遠程資源的響應結果 * @throws Exception */ public static String doPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 HttpURLConnection conn = (HttpURLConnection) realUrl .openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setUseCaches(false); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); if (param != null && !param.trim().equals("")) { // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(param); // flush輸出流的緩衝 out.flush(); } // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }
5json的轉換
package com.example.coshenwancheng.utils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @desc: json的轉換 */ public class JsonUtils { /** * Convert object, list, ... to Json * 轉爲json格式輸出 * @param obj * @return */ public static String toJson(Object obj) { Gson gson = new Gson(); return gson.toJson(obj); } /** * Convert a json string to Object * 將json轉爲object對象 * @param json * @param clazz * @return */ public static <T> T jsonToObject(String json, Class<T> clazz) { Gson gson = new Gson(); return gson.fromJson(json, clazz); } /** * Convert a json string to List<?> * 將json轉爲list集合 * @param json * @return */ public static <T> List<T> jsonToList(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<T>>() { }.getType()); } /** * Convert a json string to ArrayList<?> * 將json轉爲ArrayList * @param json * @return */ public static <T> ArrayList<T> jsonToArrayList(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<ArrayList<T>>() { }.getType()); } /** * Convert a json string to Map<?, ?> * 將json轉爲map * @param json * @return */ public static <K, V> Map<K, V> jsonToMap(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<Map<K, V>>() { }.getType()); } /** * Convert a json string to Generic<T> * 將json轉爲泛型 * @param json * @param <T> * @return */ public static <T> T jsonToGeneric(String json, TypeToken<T> token) { Gson gson = new Gson(); return gson.fromJson(json, token.getType()); } }
6鍵盤工具類
/* * Copyright 2015-2016 北京博瑞彤芸文化傳播股份有限公司 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.coshenwancheng.utils; import android.app.Activity; import android.content.Context; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; /** * @description 鍵盤工具類 */ public class KeyboardUtil { /** * 隱藏鍵盤 */ public static void hideSoftInput(Activity acitivity) { InputMethodManager imm = (InputMethodManager) acitivity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(acitivity.getWindow().getDecorView().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } /** * 顯示鍵盤 */ public static void showSoftInput(EditText et) { et.requestFocus(); InputMethodManager imm = (InputMethodManager) et.getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(et, InputMethodManager.RESULT_UNCHANGED_SHOWN); } /** * 展示鍵盤並選中最後一個 */ public static void showSoftInputSelect(EditText et) { showSoftInputSelect(et, 300); } /** * 展示鍵盤並選中最後一個 */ public static void showSoftInputSelect(final EditText et, long delayMillis) { et.postDelayed(new Runnable() { @Override public void run() { showSoftInput(et); et.setSelection(et.getText().length()); } }, delayMillis); } }
7Log統一管理類
package com.example.coshenwancheng.utils; import android.util.Log; /** * Log統一管理類 * * * */ public class LogUtil { private LogUtil() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函數裏面初始化 private static final String TAG = "way"; // 下面四個是默認tag的函數 public static void i(String msg) { if (isDebug){ Log.i(TAG, msg); } } public static void d(String msg) { if (isDebug) { Log.d(TAG, msg); } } public static void e(String msg) { if (isDebug) { Log.e(TAG, msg); } } public static void v(String msg) { if (isDebug) { Log.v(TAG, msg); } } // 下面是傳入自定義tag的函數 public static void i(String tag, String msg) { if (isDebug) { Log.i(tag, msg); } } public static void d(String tag, String msg) { if (isDebug) { Log.i(tag, msg); } } public static void e(String tag, String msg) { if (isDebug) { Log.i(tag, msg); } } public static void v(String tag, String msg) { if (isDebug) { Log.i(tag, msg); } } }
8MD5相關操作
package com.example.coshenwancheng.utils; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @desc: MD5相關操作 */ public class MD5Utils { /** * Encode MD5 for a string * * @param s * @return */ public static String encodeMD5(String s) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); return toHexString(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } private static String toHexString(byte[] keyData) { if (keyData == null) { return null; } int expectedStringLen = keyData.length * 2; StringBuilder sb = new StringBuilder(expectedStringLen); for (int i = 0; i < keyData.length; i++) { String hexStr = Integer.toString(keyData[i] & 0x00FF, 16); if (hexStr.length() == 1) { hexStr = "0" + hexStr; } sb.append(hexStr); } return sb.toString(); } /** * Encode MD5 for a string * * @param s * @return */ public final static String encodeMD52(String s) { char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { byte[] btInput = s.getBytes(); MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(btInput); byte[] md = digest.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Encode md5 for a single file * * @param f * @return */ public static String encodeMD5(File f) { if (!f.isFile()) { return null; } MessageDigest digest = null; byte buffer[] = new byte[1024]; int len; try { digest = MessageDigest.getInstance("MD5"); FileInputStream in = new FileInputStream(f); while ((len = in.read(buffer, 0, 1024)) != -1) { digest.update(buffer, 0, len); } in.close(); } catch (Exception e) { e.printStackTrace(); return null; } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } }
9跟網絡相關的工具類
package com.example.coshenwancheng.utils; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * 跟網絡相關的工具類 */ public class NetUtils { private NetUtils() { /** cannot be instantiated **/ throw new UnsupportedOperationException("cannot be instantiated"); } /** * 判斷網絡是否連接 * * @param context * @return */ public static boolean isConnected(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (null != connectivity) { NetworkInfo info = connectivity.getActiveNetworkInfo(); if (null != info && info.isConnected()) { if (info.getState() == NetworkInfo.State.CONNECTED) { return true; } } } return false; } /** * 判斷是否是wifi連接 */ public static boolean isWifi(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; } /** * 打開網絡設置界面 */ public static void openSetting(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); } }
10數字格式化操作類
package com.example.coshenwancheng.utils; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; /** * @desc: 數字格式化操作類 */ public class NumberUtils { /** * 保留一位小數 * * @param number * @return */ public static String formatOneDecimal(float number) { DecimalFormat oneDec = new DecimalFormat("##0.0"); return oneDec.format(number); } /** * 保留兩位小數 * * @param number * @return */ public static String formatTwoDecimal(float number) { DecimalFormat twoDec = new DecimalFormat("##0.00"); return twoDec.format(number); } /** * 保留兩位小數百分比 * * @param number * @return */ public static String formatTwoDecimalPercent(float number) { return formatTwoDecimal(number) + "%"; } /** * 四捨五入 * * @param number * @param scale scale of the result returned. * @return */ public static double roundingNumber(float number, int scale) { return roundingNumber(number, scale, RoundingMode.HALF_UP); } /** * 四捨五入 * * @param number * @param scale scale of the result returned. * @param roundingMode rounding mode to be used to round the result. * @return */ public static double roundingNumber(float number, int scale, RoundingMode roundingMode) { BigDecimal b = new BigDecimal(number); return b.setScale(scale, roundingMode).doubleValue(); } }