Android開發中常用的工具類整理
package net.wujingchao.android.utilityimport android.util.Log;
public final class L {
private final static int LEVEL = 5;
private final static String DEFAULT_TAG = "L";
private L() { throw new UnsupportedOperationException("L cannot instantiated!"); }
public static void v(String tag,String msg) { if(LEVEL >= 5)Log.v(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); }
public static void d(String tag,String msg) { if(LEVEL >= 4)Log.d(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); }
public static void i(String tag,String msg) { if(LEVEL >= 3)Log.i(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); }
public static void w(String tag,String msg) { if(LEVEL >= 2)Log.w(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); }
public static void e(String tag,String msg) { if(LEVEL >= 1)Log.e(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); } }</pre>
Toast
package net.wujingchao.android.utilityimport android.content.Context; import android.widget.Toast;
public class T {
private final static boolean isShow = true;
private T(){ throw new UnsupportedOperationException("T cannot be instantiated"); }
public static void showShort(Context context,CharSequence text) { if(isShow)Toast.makeText(context,text,Toast.LENGTH_SHORT).show(); }
public static void showLong(Context context,CharSequence text) { if(isShow)Toast.makeText(context,text,Toast.LENGTH_LONG).show(); } }</pre>
網絡
package net.wujingchao.android.utilityimport android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager;
public class NetworkUtil { private NetworkUtil() { throw new UnsupportedOperationException("NetworkUtil cannot be instantiated"); }
/* 判斷網絡是否連接 / 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 connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) return false; return connectivity.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}
/* 打開網絡設置界面 */ public static void openSetting(Activity activity) { Intent intent = new Intent("/"); ComponentName componentName = new ComponentName("com.android.settings","com.android.settings.WirelessSettings"); intent.setComponent(componentName); intent.setAction("android.intent.action.VIEW"); activity.startActivityForResult(intent, 0); }
/* 使用SSL不信任的證書 */ public static void useUntrustedCertificate() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } }</pre>
像素單位轉換
package net.wujingchao.android.utilityimport android.content.Context; import android.util.TypedValue;
public class DensityUtil {
private DensityUtil() { throw new UnsupportedOperationException("DensityUtil cannot be instantiated"); }
public int dip2px(Context context,int dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int)(dipValue*scale + 0.5f); }
public int px2dip(Context context,float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int)(pxValue/scale + 0.5f); }
public static float px2sp(Context context, float pxValue){ return (pxValue / context.getResources().getDisplayMetrics().scaledDensity); }
public static int sp2px(Context context, int spValue){ return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics()); } }</pre>
屏幕
package net.wujingchao.android.utilityimport android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Rect; import android.util.DisplayMetrics; import android.view.View; import android.view.WindowManager;
public class ScreenUtil {
private ScreenUtil() { throw new UnsupportedOperationException("ScreenUtil cannot be instantiated"); }
public static int getScreenWidth(Context context) { WindowManager wm = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); return outMetrics.widthPixels; }
public static int getScreenHeight(Context context) { WindowManager wm = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); return outMetrics.heightPixels; }
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; }
/* 獲取當前屏幕截圖,包含狀態欄 */ public static Bitmap snapShotWithStatusBar(Activity activity){ View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bmp = view.getDrawingCache(); int width = getScreenWidth(activity); int height = getScreenHeight(activity); Bitmap bp = null; bp = Bitmap.createBitmap(bmp, 0, 0, width, height); view.destroyDrawingCache(); return bp; }
/* 獲取當前屏幕截圖,不包含狀態欄 / public static Bitmap snapShotWithoutStatusBar(Activity activity){ View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bmp = view.getDrawingCache(); Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; int width = getScreenWidth(activity); int height = getScreenHeight(activity); Bitmap bp = null; bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return bp; } }</pre>
App相關
package net.wujingchao.android.utilityimport android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager;
public class AppUtil {
private AppUtil() { throw new UnsupportedOperationException("AppUtil cannot instantiated"); }
/* 獲取app版本名 */ public static String getAppVersionName(Context context){ PackageManager pm = context.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(context.getPackageName(),0); return pi.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return ""; }
/* 獲取應用程序版本名稱信息 */ public static String getVersionName(Context context) { try{ PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0); return packageInfo.versionName; }catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; }
/* 獲取app版本號 */ public static int getAppVersionCode(Context context){ PackageManager pm = context.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(context.getPackageName(),0); return pi.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return 0; } }</pre>
鍵盤
package net.wujingchao.android.utilityimport android.content.Context; import android.view.inputmethod.InputMethodManager; import android.widget.EditText;
public class KeyBoardUtil{
private KeyBoardUtil(){ throw new UnsupportedOperationException("KeyBoardUtil cannot be instantiated"); }
/ 打卡軟鍵盤 / public static void openKeybord(EditText mEditText, Context mContext){ InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY); } / 關閉軟鍵盤 / public static void closeKeybord(EditText mEditText, Context mContext) { InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); } }</pre>
文件上傳下載
package net.wujingchao.android.utilityimport android.content.Context; import android.os.Environment;
import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.UUID;
import com.mixiaofan.App;
public class DownloadUtil {
private static final int TIME_OUT = 30*1000; //超時時間 private static final String CHARSET = "utf-8"; //設置編碼 private DownloadUtil() {
throw new UnsupportedOperationException("DownloadUtil cannot be instantiated"); }
/ @param file 上傳文件 @param RequestURL 上傳文件URL @return 服務器返回的信息,如果出錯則返回為null / public static String uploadFile(File file,String RequestURL) { String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機生成 String PREFIX = "--" , LINE_END = "\r\n"; String PREFIX = "--" , LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; //內容類型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); //允許輸入流 conn.setDoOutput(true); //允許輸出流 conn.setUseCaches(false); //不允許使用緩存 conn.setRequestMethod("POST"); //請求方式 conn.setRequestProperty("Charset", CHARSET); conn.setRequestProperty("Cookie", "PHPSESSID=" + App.getSessionId()); //設置編碼 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if(file!=null) { / 當文件不為空,把文件包裝并且上傳 / OutputStream outputSteam=conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputSteam); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); / 這里重點注意: name里面的值為服務器端需要key 只有這個key 才可以得到對應的文件 filename是文件的名字,包含后綴名的 比如:abc.png / sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len; while((len=is.read(bytes))!=-1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes(); dos.write(end_data); dos.flush(); / 獲取響應碼 200=成功 當響應成功,獲取響應的流 / ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream resultStream = conn.getInputStream(); len = -1; byte [] buffer = new byte[10248]; while((len = resultStream.read(buffer)) != -1) { bos.write(buffer,0,len); } resultStream.close(); bos.flush(); bos.close(); String info = new String(bos.toByteArray()); int res = conn.getResponseCode(); if(res==200){ return info; }else { return null; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public static byte[] download(String urlStr) { HttpURLConnection conn = null; InputStream is = null; byte[] result = null; ByteArrayOutputStream bos = null; try { URL url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(TIME_OUT); conn.setReadTimeout(TIME_OUT); conn.setDoInput(true); conn.setUseCaches(false);//不使用緩存 if(conn.getResponseCode() == 200) { is = conn.getInputStream(); byte [] buffer = new byte[1024*8]; int len; bos = new ByteArrayOutputStream(); while((len = is.read(buffer)) != -1) { bos.write(buffer,0,len); } bos.flush(); result = bos.toByteArray(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(bos != null){ bos.close(); } if (is != null) { is.close(); } if (conn != null)conn.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return result; }
/* 獲取緩存文件 */ public static File getDiskCacheFile(Context context,String filename,boolean isExternal) { if(isExternal && (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) { return new File(context.getExternalCacheDir(),filename); }else { return new File(context.getCacheDir(),filename); } }
/* 獲取緩存文件目錄 */ public static File getDiskCacheDirectory(Context context) { if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return context.getExternalCacheDir(); }else { return context.getCacheDir(); } } }</pre>
加密
package net.wujingchao.android.utilityimport java.security.MessageDigest; import java.security.NoSuchAlgorithmException;
public class CipherUtil {
private CipherUtil() {
}
//字節數組轉化為16進制字符串 public static String byteArrayToHex(byte[] byteArray) { char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' }; char[] resultCharArray =new char[byteArray.length * 2]; int index = 0; for (byte b : byteArray) { resultCharArray[index++] = hexDigits[b>>> 4 & 0xf]; resultCharArray[index++] = hexDigits[b & 0xf]; } return new String(resultCharArray); }
//字節數組md5算法 public static byte[] md5 (byte [] bytes) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(bytes); return messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } }</pre>
時間
package net.wujingchao.android.utility import java.text.SimpleDateFormat; import java.util.Date;public class DateUtil {
//轉換中文對應的時段 public static String convertNowHour2CN(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("HH"); String hourString = sdf.format(date); int hour = Integer.parseInt(hourString); if(hour < 6) { return "凌晨"; }else if(hour >= 6 && hour < 12) { return "早上"; }else if(hour == 12) { return "中午"; }else if(hour > 12 && hour <=18) { return "下午"; }else if(hour >=19) { return "晚上"; } return ""; }
//剩余秒數轉換 public static String convertSecond2Day(int time) { int day = time/86400; int hour = (time - 86400day)/3600; int min = (time - 86400day - 3600hour)/60; int sec = (time - 86400day - 3600hour - 60min); StringBuilder sb = new StringBuilder(); sb.append(day); sb.append("天"); sb.append(hour); sb.append("時"); sb.append(min); sb.append("分"); sb.append(sec); sb.append("秒"); return sb.toString(); }
}</pre>