1、DensityUtils
/** * 常用单位转换的辅助类 */ public class DensityUtils { private DensityUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * dp转px * * @param context * @param dpVal * @return */ public static int dp2px(Context context, float dpVal) { return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources().getDisplayMetrics())); } /** * sp转px * * @param context * @param spVal * @return */ public static int sp2px(Context context, float spVal) { return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources().getDisplayMetrics())); } /** * px转dp * * @param context * @param pxVal * @return */ public static float px2dp(Context context, float pxVal) { final float scale = context.getResources().getDisplayMetrics().density; return (pxVal / scale); } /** * px转sp * * @param context * @param pxVal * @return */ public static float px2sp(Context context, float pxVal) { return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); } }
2、LogUtil
/** * 日志工具类。统一管理日志信息的显示/隐藏 * * @author Tobin */ public class LogUtil { /** 日志输出时的TAG */ private static String mTag = "LogUtil"; /** * 是否已经显示佛祖 */ private static boolean isShowBuddha = false; /** * 是否允许输出log * mDebuggable < 1: 不允许 * mDebuggable >= 1: 根据等级允许 * */ private static int mDebuggable = 10; /** 日志输出级别V */ public static final int LEVEL_VERBOSE = 1; /** 日志输出级别D */ public static final int LEVEL_DEBUG = 2; /** 日志输出级别I */ public static final int LEVEL_INFO = 3; /** 日志输出级别W */ public static final int LEVEL_WARN = 4; /** 日志输出级别E */ public static final int LEVEL_ERROR = 5; private LogUtil() throws InstantiationException { throw new InstantiationException("This class is not created for instantiation"); } /** * 佛祖显灵 */ public static void showBuddha() { if (isShowBuddha) { return; } isShowBuddha = true; Log.i(mTag, " _ooOoo_"); Log.i(mTag, " o8888888o"); Log.i(mTag, " 88\" . \"88"); Log.i(mTag, " (| -_- |)"); Log.i(mTag, " O\\ = /O"); Log.i(mTag, " ____/`---'\\____"); Log.i(mTag, " . ' \\| |// `."); Log.i(mTag, " / \\\\||| : |||// \\"); Log.i(mTag, " / _||||| -:- |||||- \\"); Log.i(mTag, " | | \\\\\\ - /// | |"); Log.i(mTag, " | \\_| ''\\---/'' | |"); Log.i(mTag, " \\ .-\\__ `-` ___/-. /"); Log.i(mTag, " ___`. .' /--.--\\ `. . __"); Log.i(mTag, " .\"\" '< `.___\\_<|>_/___.' >'\"\"."); Log.i(mTag, " | | : `- \\`.;`\\ _ /`;.`/ - ` : | |"); Log.i(mTag, " \\ \\ `-. \\_ __\\ /__ _/ .-` / /"); Log.i(mTag, " ======`-.____`-.___\\_____/___.-`____.-'======"); Log.i(mTag, " `=---='"); Log.i(mTag, " ............................................."); Log.i(mTag, " 信佛祖,无bug"); Log.i(mTag, " del bug ..."); } /** * 以级别为v 的形式输出LOG * */ public static void v(String msg) { if (mDebuggable >= LEVEL_VERBOSE) { Log.v(mTag, msg); } } /** 以级别为 d 的形式输出LOG */ public static void d(String msg) { if (mDebuggable >= LEVEL_DEBUG) { Log.d(mTag, msg); } } /** 以级别为 d 的形式输出LOG */ public static void d(String tag,String msg) { if (mDebuggable >= LEVEL_DEBUG) { Log.d(tag, msg); } } /** 以级别为 i 的形式输出LOG */ public static void i(String msg) { if (mDebuggable >= LEVEL_INFO) { Log.i(mTag, msg); } } /** 以级别为 i 的形式输出LOG */ public static void i(String tag,String msg) { if (mDebuggable >= LEVEL_INFO) { Log.i(tag, msg); } } /** * 以级别为 w 的形式输出LOG * */ public static void w(String msg) { if (mDebuggable >= LEVEL_WARN) { Log.w(mTag, msg); } } /** * 以级别为 w 的形式输出LOG * */ public static void w(String tag,String msg) { if (mDebuggable >= LEVEL_WARN) { Log.w(tag, msg); } } /** * 以级别为 w 的形式输出Throwable * */ public static void w(Throwable tr) { if (mDebuggable >= LEVEL_WARN) { Log.w(mTag, "", tr); } } /** * 以级别为 w 的形式输出LOG信息和Throwable * */ public static void w(String msg, Throwable tr) { if (mDebuggable >= LEVEL_WARN && null != msg) { Log.w(mTag, msg, tr); } } /** * 以级别为 e 的形式输出LOG * * */ public static void e(String msg) { if (mDebuggable >= LEVEL_ERROR) { Log.e(mTag, msg); } } /** * 以级别为 e 的形式输出LOG * * */ public static void e(String tag,String msg) { if (mDebuggable >= LEVEL_ERROR) { Log.e(tag, msg); } } /** * 以级别为 e 的形式输出Throwable * */ public static void e(Throwable tr) { if (mDebuggable >= LEVEL_ERROR) { Log.e(mTag, "", tr); } } /** 以级别为 e 的形式输出LOG信息和Throwable */ public static void e(String msg, Throwable tr) { if (mDebuggable >= LEVEL_ERROR && null != msg) { Log.e(mTag, msg, tr); } } }
3、ScreenUtils
/** * 获得屏幕相关的辅助类 * */ public class ScreenUtils { private ScreenUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * 获得屏幕高度 * * @param context * @return */ 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; } /** * 获得屏幕宽度 * * @param context * @return */ 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; } /** * 获得状态栏的高度 * * @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; } /** * 获取当前屏幕截图,包含状态栏 * * @param activity * @return */ 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; } /** * 获取当前屏幕截图,不包含状态栏 * * @param activity * @return */ 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; } }
4、JsonUtil 基于fastjson-1.x.xx.android.jar,下载地址:https://github.com/alibaba/fastjson/releases
/** * FastJson序列化工具包 * * @author Sun * @since 2012-1-19 * @author Tobin * @modify 2015-5-27 */ public class JsonUtil { private static final String CHARSET = "UTF-8"; /** * 将网络请求下来的数据用fastjson处理空的情况,并将时间戳转化为标准时间格式 * @param result * @return */ public static String dealResponseResult(String result) { result = JSONObject.toJSONString(result, SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteEnumUsingToString, SerializerFeature.WriteSlashAsSpecial, SerializerFeature.WriteTabAsSpecial); return result; } /** * 将json转换成为java对象T * * @param json * @param classOfT * @return */ public static <T> T Json2T(String json, Class<T> classOfT) { if (null == json || "".equals(json.trim())) return null; try { return JSON.parseObject(json, classOfT); } catch (Throwable e) { e.printStackTrace(); Log.e("JsonUtil.Json2T", "msg:" + json + "\nclazz:" + classOfT.getName()); return null; } } /** * 将json转换成为java对象列表List<T> * * @param json * @param classOfT * @return */ public static <T> List<T> Json2List(String json, Class<T> classOfT) { if (null == json || "".equals(json.trim())) { return null; } try { return JSON.parseArray(json, classOfT); } catch (Exception e) { Log.e("JsonUtil.Json2T", "msg:" + json + "\r\nclazz:" + classOfT.getName()); return null; } } /** * 把JSON数据转换成较为复杂的java对象列表List<Map<String, Object>> * * @param jsonData * JSON数据 * @return * @throws Exception */ public static List<Map<String, Object>> json2MapList(String jsonData) throws Exception { return JSON.parseObject(jsonData, new TypeReference<List<Map<String, Object>>>() {}); } /** * 将非集合类java对象转换成为json object * * @param o * @return */ public static JSONObject Object2JsonObject(Object o) { try { return (JSONObject) JSON.toJSON(o); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将集合类java对象装换成为json array * * @param collection * @return */ public static JSONArray Collection2JsonArray(Collection collection) { try { return (JSONArray) JSON.toJSON(collection); } catch (Exception e) { e.printStackTrace(); return null; } } /** * json String 转 JSONObject * * @param json * @return */ public static JSONObject json2JsonObject(String json) { try { return JSON.parseObject(json); } catch (Throwable e) { e.printStackTrace(); return null; } } /** * 将json转换成为jsonArray对象 * * @param str * @return */ public static JSONArray Json2JsonArray(String str) { if (null == str || "".equals(str.trim())) { return null; } try { return JSON.parseArray(str); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将对象Object转换成json格式数据 * * @param o * @return */ public static String Object2Json(Object o) { try { return JSON.toJSONString(o); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将对象Object转换成更加方便观察的json格式数据,但会增加存储空间 * * @param o * @return */ public static String Object2JsonPrettyFormat(Object o) { try { return JSON.toJSONString(o, true); } catch (Exception e) { e.printStackTrace(); return null; } } /** * byte[] 转 JSONObject * * @param bytes * @return */ public static JSONObject bytes2JsonObject(byte[] bytes) { try { return JSON.parseObject(new String(bytes, CHARSET)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * byte[] 转 java对象 * * @param bytes * @return */ public static <T> T bytes2T(byte[] bytes, Class<T> classOfT) { try { return JSON.parseObject(new String(bytes, CHARSET), classOfT); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将对象转换成json格式数据,使用全序列化方案 * * @param o * @return */ public static String Object2JsonSerial(Object o) { try { return JSON.toJSONString(o, SerializerFeature.WriteClassName); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将列表转换成为json,使用全序列化方案 * * @param l * @return */ public static String list2JsonSerial(List l) { if (null == l) { return null; } try { return JSON.toJSONString(l, SerializerFeature.WriteClassName); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将全序列化json转换成为java对象 * * @param json * @return */ public static Object JsonSerial2Object(String json) { try { return JSON.parse(json); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将全序列化json转换成为list对象 * * @param json * @return */ public static List JsonSerial2List(String json) { try { return JSON.parseArray(json); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将全序列化json转换为jsonArray对象 * * @param json * @return */ public static JSONArray JsonSerial2JsonArray(String json) { try { return JSON.parseArray(json); } catch (Exception e) { e.printStackTrace(); return null; } } }
5、HttpUtils
/** * @author Tobin * * 简单的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() { 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() { 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) { e.printStackTrace(); } try { if (baos != null) baos.close(); } catch (IOException e) { e.printStackTrace(); } 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; } }
时间: 2024-10-03 14:15:43