Android开发中常用的工具类整理
日志
1 package net.wujingchao.android.utility 2 3 import android.util.Log; 4 5 public final class L { 6 7 private final static int LEVEL = 5; 8 9 private final static String DEFAULT_TAG = "L"; 10 11 private L() { 12 throw new UnsupportedOperationException("L cannot instantiated!"); 13 } 14 15 public static void v(String tag,String msg) { 16 if(LEVEL >= 5)Log.v(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); 17 } 18 19 public static void d(String tag,String msg) { 20 if(LEVEL >= 4)Log.d(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); 21 } 22 23 public static void i(String tag,String msg) { 24 if(LEVEL >= 3)Log.i(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); 25 } 26 27 public static void w(String tag,String msg) { 28 if(LEVEL >= 2)Log.w(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); 29 } 30 31 public static void e(String tag,String msg) { 32 if(LEVEL >= 1)Log.e(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg); 33 } 34 }
Toast
1 package net.wujingchao.android.utility 2 3 import android.content.Context; 4 import android.widget.Toast; 5 6 public class T { 7 8 private final static boolean isShow = true; 9 10 private T(){ 11 throw new UnsupportedOperationException("T cannot be instantiated"); 12 } 13 14 public static void showShort(Context context,CharSequence text) { 15 if(isShow)Toast.makeText(context,text,Toast.LENGTH_SHORT).show(); 16 } 17 18 public static void showLong(Context context,CharSequence text) { 19 if(isShow)Toast.makeText(context,text,Toast.LENGTH_LONG).show(); 20 } 21 }
网络
1 package net.wujingchao.android.utility 2 3 import android.app.Activity; 4 import android.content.ComponentName; 5 import android.content.Context; 6 import android.content.Intent; 7 import android.net.ConnectivityManager; 8 import android.net.NetworkInfo; 9 10 import javax.net.ssl.HttpsURLConnection; 11 import javax.net.ssl.SSLContext; 12 import javax.net.ssl.TrustManager; 13 import javax.net.ssl.X509TrustManager; 14 15 public class NetworkUtil { 16 17 private NetworkUtil() { 18 throw new UnsupportedOperationException("NetworkUtil cannot be instantiated"); 19 } 20 21 /** 22 * 判断网络是否连接 23 * 24 */ 25 public static boolean isConnected(Context context) { 26 ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 27 if (null != connectivity) { 28 NetworkInfo info = connectivity.getActiveNetworkInfo(); 29 if (null != info && info.isConnected()){ 30 if (info.getState() == NetworkInfo.State.CONNECTED) { 31 return true; 32 } 33 } 34 } 35 return false; 36 } 37 38 /** 39 * 判断是否是wifi连接 40 */ 41 public static boolean isWifi(Context context){ 42 ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 43 if (connectivity == null) return false; 44 return connectivity.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; 45 46 } 47 48 /** 49 * 打开网络设置界面 50 */ 51 public static void openSetting(Activity activity) { 52 Intent intent = new Intent("/"); 53 ComponentName componentName = new ComponentName("com.android.settings","com.android.settings.WirelessSettings"); 54 intent.setComponent(componentName); 55 intent.setAction("android.intent.action.VIEW"); 56 activity.startActivityForResult(intent, 0); 57 } 58 59 /** 60 * 使用SSL不信任的证书 61 */ 62 public static void useUntrustedCertificate() { 63 // Create a trust manager that does not validate certificate chains 64 TrustManager[] trustAllCerts = new TrustManager[]{ 65 new X509TrustManager() { 66 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 67 return null; 68 } 69 public void checkClientTrusted( 70 java.security.cert.X509Certificate[] certs, String authType) { 71 } 72 public void checkServerTrusted( 73 java.security.cert.X509Certificate[] certs, String authType) { 74 } 75 } 76 }; 77 // Install the all-trusting trust manager 78 try { 79 SSLContext sc = SSLContext.getInstance("SSL"); 80 sc.init(null, trustAllCerts, new java.security.SecureRandom()); 81 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 82 } catch (Exception e) { 83 e.printStackTrace(); 84 } 85 } 86 }
像素单位转换
1 package net.wujingchao.android.utility 2 3 import android.content.Context; 4 import android.util.TypedValue; 5 6 public class DensityUtil { 7 8 private DensityUtil() { 9 throw new UnsupportedOperationException("DensityUtil cannot be instantiated"); 10 } 11 12 public int dip2px(Context context,int dipValue) { 13 final float scale = context.getResources().getDisplayMetrics().density; 14 return (int)(dipValue*scale + 0.5f); 15 } 16 17 public int px2dip(Context context,float pxValue) { 18 final float scale = context.getResources().getDisplayMetrics().density; 19 return (int)(pxValue/scale + 0.5f); 20 } 21 22 public static float px2sp(Context context, float pxValue){ 23 return (pxValue / context.getResources().getDisplayMetrics().scaledDensity); 24 } 25 26 public static int sp2px(Context context, int spValue){ 27 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 28 spValue, context.getResources().getDisplayMetrics()); 29 } 30 }
屏幕
1 package net.wujingchao.android.utility 2 3 import android.app.Activity; 4 import android.content.Context; 5 import android.graphics.Bitmap; 6 import android.graphics.Rect; 7 import android.util.DisplayMetrics; 8 import android.view.View; 9 import android.view.WindowManager; 10 11 public class ScreenUtil { 12 13 private ScreenUtil() 14 { 15 throw new UnsupportedOperationException("ScreenUtil cannot be instantiated"); 16 } 17 18 public static int getScreenWidth(Context context) 19 { 20 WindowManager wm = (WindowManager) context 21 .getSystemService(Context.WINDOW_SERVICE); 22 DisplayMetrics outMetrics = new DisplayMetrics(); 23 wm.getDefaultDisplay().getMetrics(outMetrics); 24 return outMetrics.widthPixels; 25 } 26 27 public static int getScreenHeight(Context context) { 28 WindowManager wm = (WindowManager) context 29 .getSystemService(Context.WINDOW_SERVICE); 30 DisplayMetrics outMetrics = new DisplayMetrics(); 31 wm.getDefaultDisplay().getMetrics(outMetrics); 32 return outMetrics.heightPixels; 33 } 34 35 public static int getStatusHeight(Context context) { 36 int statusHeight = -1; 37 try { 38 Class<?> clazz = Class.forName("com.android.internal.R$dimen"); 39 Object object = clazz.newInstance(); 40 int height = Integer.parseInt(clazz.getField("status_bar_height") 41 .get(object).toString()); 42 statusHeight = context.getResources().getDimensionPixelSize(height); 43 } catch (Exception e) { 44 e.printStackTrace(); 45 } 46 return statusHeight; 47 } 48 49 /** 50 * 获取当前屏幕截图,包含状态栏 51 */ 52 public static Bitmap snapShotWithStatusBar(Activity activity){ 53 View view = activity.getWindow().getDecorView(); 54 view.setDrawingCacheEnabled(true); 55 view.buildDrawingCache(); 56 Bitmap bmp = view.getDrawingCache(); 57 int width = getScreenWidth(activity); 58 int height = getScreenHeight(activity); 59 Bitmap bp = null; 60 bp = Bitmap.createBitmap(bmp, 0, 0, width, height); 61 view.destroyDrawingCache(); 62 return bp; 63 } 64 65 /** 66 * 获取当前屏幕截图,不包含状态栏 67 * 68 */ 69 public static Bitmap snapShotWithoutStatusBar(Activity activity){ 70 View view = activity.getWindow().getDecorView(); 71 view.setDrawingCacheEnabled(true); 72 view.buildDrawingCache(); 73 Bitmap bmp = view.getDrawingCache(); 74 Rect frame = new Rect(); 75 activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); 76 int statusBarHeight = frame.top; 77 int width = getScreenWidth(activity); 78 int height = getScreenHeight(activity); 79 Bitmap bp = null; 80 bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height 81 - statusBarHeight); 82 view.destroyDrawingCache(); 83 return bp; 84 } 85 }
App相关
package net.wujingchao.android.utility import 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; } }
键盘
1 package net.wujingchao.android.utility 2 3 import android.content.Context; 4 import android.view.inputmethod.InputMethodManager; 5 import android.widget.EditText; 6 7 public class KeyBoardUtil{ 8 9 private KeyBoardUtil(){ 10 throw new UnsupportedOperationException("KeyBoardUtil cannot be instantiated"); 11 } 12 13 /** 14 * 打卡软键盘 15 */ 16 public static void openKeybord(EditText mEditText, Context mContext){ 17 InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); 18 imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN); 19 imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY); 20 } 21 /** 22 * 关闭软键盘 23 */ 24 public static void closeKeybord(EditText mEditText, Context mContext) { 25 InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); 26 imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); 27 } 28 }
文件上传下载
1 package net.wujingchao.android.utility 2 3 import android.content.Context; 4 import android.os.Environment; 5 6 import java.io.ByteArrayOutputStream; 7 import java.io.DataOutputStream; 8 import java.io.File; 9 import java.io.FileInputStream; 10 import java.io.FileNotFoundException; 11 import java.io.IOException; 12 import java.io.InputStream; 13 import java.io.OutputStream; 14 import java.net.HttpURLConnection; 15 import java.net.MalformedURLException; 16 import java.net.ProtocolException; 17 import java.net.URL; 18 import java.util.UUID; 19 20 import com.mixiaofan.App; 21 22 public class DownloadUtil { 23 24 private static final int TIME_OUT = 30*1000; //超时时间 25 26 private static final String CHARSET = "utf-8"; //设置编码 27 28 private DownloadUtil() { 29 throw new UnsupportedOperationException("DownloadUtil cannot be instantiated"); 30 } 31 32 /** 33 * @param file 上传文件 34 * @param RequestURL 上传文件URL 35 * @return 服务器返回的信息,如果出错则返回为null 36 */ 37 public static String uploadFile(File file,String RequestURL) { 38 String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n"; 39 String PREFIX = "--" , LINE_END = "\r\n"; 40 String CONTENT_TYPE = "multipart/form-data"; //内容类型 41 try { 42 URL url = new URL(RequestURL); 43 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 44 conn.setReadTimeout(TIME_OUT); 45 conn.setConnectTimeout(TIME_OUT); 46 conn.setDoInput(true); //允许输入流 47 conn.setDoOutput(true); //允许输出流 48 conn.setUseCaches(false); //不允许使用缓存 49 conn.setRequestMethod("POST"); //请求方式 50 conn.setRequestProperty("Charset", CHARSET); 51 conn.setRequestProperty("Cookie", "PHPSESSID=" + App.getSessionId()); 52 //设置编码 53 conn.setRequestProperty("connection", "keep-alive"); 54 conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); 55 if(file!=null) { 56 /** * 当文件不为空,把文件包装并且上传 */ 57 OutputStream outputSteam=conn.getOutputStream(); 58 DataOutputStream dos = new DataOutputStream(outputSteam); 59 StringBuffer sb = new StringBuffer(); 60 sb.append(PREFIX); 61 sb.append(BOUNDARY); sb.append(LINE_END); 62 /** 63 * 这里重点注意: 64 * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 65 * filename是文件的名字,包含后缀名的 比如:abc.png 66 */ 67 sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); 68 sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END); 69 sb.append(LINE_END); 70 dos.write(sb.toString().getBytes()); 71 InputStream is = new FileInputStream(file); 72 byte[] bytes = new byte[1024]; 73 int len; 74 while((len=is.read(bytes))!=-1) 75 { 76 dos.write(bytes, 0, len); 77 } 78 is.close(); 79 dos.write(LINE_END.getBytes()); 80 byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes(); 81 dos.write(end_data); 82 dos.flush(); 83 /** 84 * 获取响应码 200=成功 85 * 当响应成功,获取响应的流 86 */ 87 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 88 InputStream resultStream = conn.getInputStream(); 89 len = -1; 90 byte [] buffer = new byte[1024*8]; 91 while((len = resultStream.read(buffer)) != -1) { 92 bos.write(buffer,0,len); 93 } 94 resultStream.close(); 95 bos.flush(); 96 bos.close(); 97 String info = new String(bos.toByteArray()); 98 int res = conn.getResponseCode(); 99 if(res==200){ 100 return info; 101 }else { 102 return null; 103 } 104 } 105 } catch (MalformedURLException e) { 106 e.printStackTrace(); 107 } catch (ProtocolException e) { 108 e.printStackTrace(); 109 } catch (FileNotFoundException e) { 110 e.printStackTrace(); 111 } catch (IOException e) { 112 e.printStackTrace(); 113 } 114 return null; 115 } 116 117 public static byte[] download(String urlStr) { 118 HttpURLConnection conn = null; 119 InputStream is = null; 120 byte[] result = null; 121 ByteArrayOutputStream bos = null; 122 try { 123 URL url = new URL(urlStr); 124 conn = (HttpURLConnection) url.openConnection(); 125 conn.setRequestMethod("GET"); 126 conn.setConnectTimeout(TIME_OUT); 127 conn.setReadTimeout(TIME_OUT); 128 conn.setDoInput(true); 129 conn.setUseCaches(false);//不使用缓存 130 if(conn.getResponseCode() == 200) { 131 is = conn.getInputStream(); 132 byte [] buffer = new byte[1024*8]; 133 int len; 134 bos = new ByteArrayOutputStream(); 135 while((len = is.read(buffer)) != -1) { 136 bos.write(buffer,0,len); 137 } 138 bos.flush(); 139 result = bos.toByteArray(); 140 } 141 } catch (MalformedURLException e) { 142 e.printStackTrace(); 143 } catch (IOException e) { 144 e.printStackTrace(); 145 } finally { 146 try { 147 if(bos != null){ 148 bos.close(); 149 } 150 if (is != null) { 151 is.close(); 152 } 153 if (conn != null)conn.disconnect(); 154 } catch (IOException e) { 155 e.printStackTrace(); 156 } 157 } 158 return result; 159 } 160 161 /** 162 * 获取缓存文件 163 */ 164 public static File getDiskCacheFile(Context context,String filename,boolean isExternal) { 165 if(isExternal && (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) { 166 return new File(context.getExternalCacheDir(),filename); 167 }else { 168 return new File(context.getCacheDir(),filename); 169 } 170 } 171 172 /** 173 * 获取缓存文件目录 174 */ 175 public static File getDiskCacheDirectory(Context context) { 176 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 177 return context.getExternalCacheDir(); 178 }else { 179 return context.getCacheDir(); 180 } 181 } 182 }
加密
1 package net.wujingchao.android.utility 2 3 import java.security.MessageDigest; 4 import java.security.NoSuchAlgorithmException; 5 6 public class CipherUtil { 7 8 private CipherUtil() { 9 10 } 11 12 //字节数组转化为16进制字符串 13 public static String byteArrayToHex(byte[] byteArray) { 14 char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' }; 15 char[] resultCharArray =new char[byteArray.length * 2]; 16 int index = 0; 17 for (byte b : byteArray) { 18 resultCharArray[index++] = hexDigits[b>>> 4 & 0xf]; 19 resultCharArray[index++] = hexDigits[b & 0xf]; 20 } 21 return new String(resultCharArray); 22 } 23 24 //字节数组md5算法 25 public static byte[] md5 (byte [] bytes) { 26 try { 27 MessageDigest messageDigest = MessageDigest.getInstance("MD5"); 28 messageDigest.update(bytes); 29 return messageDigest.digest(); 30 } catch (NoSuchAlgorithmException e) { 31 e.printStackTrace(); 32 } 33 return null; 34 } 35 }
时间
1 package net.wujingchao.android.utility 2 import java.text.SimpleDateFormat; 3 import java.util.Date; 4 5 6 public class DateUtil { 7 8 //转换中文对应的时段 9 public static String convertNowHour2CN(Date date) { 10 SimpleDateFormat sdf = new SimpleDateFormat("HH"); 11 String hourString = sdf.format(date); 12 int hour = Integer.parseInt(hourString); 13 if(hour < 6) { 14 return "凌晨"; 15 }else if(hour >= 6 && hour < 12) { 16 return "早上"; 17 }else if(hour == 12) { 18 return "中午"; 19 }else if(hour > 12 && hour <=18) { 20 return "下午"; 21 }else if(hour >=19) { 22 return "晚上"; 23 } 24 return ""; 25 } 26 27 //剩余秒数转换 28 public static String convertSecond2Day(int time) { 29 int day = time/86400; 30 int hour = (time - 86400*day)/3600; 31 int min = (time - 86400*day - 3600*hour)/60; 32 int sec = (time - 86400*day - 3600*hour - 60*min); 33 StringBuilder sb = new StringBuilder(); 34 sb.append(day); 35 sb.append("天"); 36 sb.append(hour); 37 sb.append("时"); 38 sb.append(min); 39 sb.append("分"); 40 sb.append(sec); 41 sb.append("秒"); 42 return sb.toString(); 43 } 44 45 }