Android 常用工具类

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;
	}
}




  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
常用Android Studio工具类有以下几个: 1. AndroidUniqueID: 这是一个用于获取Android设备唯一标识符的工具类,可以通过GitHub链接(https://github.com/appdevzhang/AndroidUniqueID)找到详细使用方法。 2. Lazy android: 这是一个方便快捷的Android工具类,通过GitHub链接(https://github.com/l123456789jy/Lazy android)可以了解它的具体功能和用法。 3. Utils-Everywhere: 这是一个Android各种工具类的集合,通过GitHub链接(https://github.com/SenhLinsh/Utils-Everywhere)可以查看所有可用的工具类和使用方法。 这些工具类都是为了方便开发者在Android Studio中进行开发而设计的,可以提高开发效率和代码质量。同时,还可以使用Lint工具来进行静态代码检查,找出代码结构和质量问题,并提供解决方案。通过Android Studio自带的Lint功能,可以进行一些常见的代码优化,去除多余的资源等。 可以通过这个(https://blog.csdn.net/ouyang_peng/article/details/80374867)链接来了解更多关于Lint工具的配置和使用方法。 除了Lint工具,还有其他的静态代码检查框架,如FindBugs、PMD和Checkstyle等,它们可以检查Java源文件或class文件的代码质量和代码风格。但在Android开发中,我们通常会选择使用Lint框架,因为它提供了强大的功能、扩展性和与Android StudioAndroid Gradle插件的原生支持。此外,Lint框架还提供了许多有用的Android相关检查规则,而且有Google官方的支持,在Android开发工具的升级中也会得到完善。 你可以通过这个链接(https://blog.csdn.net/MeituanTech/article/details/79922364)了解更多关于Lint框架的使用和优势。 总结来说,Android Studio常用工具类包括AndroidUniqueID、Lazy android和Utils-Everywhere等,而Lint工具则可以帮助我们进行静态代码检查和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值