在Android开发中,总有一个不可缺少的包,那就是工具包,就像拧螺丝没有扳手仅仅依靠自己的双手,只是有心报国无力回天。
参考1:http://www.jianshu.com/p/e04177f08fc8?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=qq
参考2:https://github.com/Blankj/AndroidUtilCode/tree/master/utilcode/src/main/java/com/blankj/utilcode/util
1.尺寸工具类:获取屏幕宽高,密度,dp、px互转,px、sp互转
public class ScreenUtils {
/**
* 获取屏幕宽度
*
* @param context
* @return
*/
public static int getScreenWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}
/**
* 获取屏幕高度
*
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
/**
* 获取屏幕密度
*
* @param context
* @return
*/
public static float getScreenDensity(Context context) {
return context.getResources().getDisplayMetrics().density;
}
/**
* dp转px
*
* @param context
* @param dpValue
* @return
*/
public static int dp2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 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);
}
/**
* sp转px
*
* @param context
* @param spVal
* @return
*/
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* px转sp
*
* @param context
* @param pxVal
* @return
*/
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}
2.SharedPreferences存取操作类:可以传任意类型自动能存取数据,也举例了String和Boolean的。
public class SharedPrefUtils {
public static final String SHAREPRENFERENCE_NAME = "sharefile";
private static SharedPreferences sp;
/**
* 保存数据到共享参数中
* @param context
* @param key 键
* @param object 值
*/
public static void setParams(Context context, String key, Object object){
SharedPreferences sharedPreferences = context.getSharedPreferences(SHAREPRENFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if(object instanceof String){
editor.putString(key, (String) object);
}else if(object instanceof Integer){
editor.putInt(key, (Integer) object);
}else if(object instanceof Boolean){
editor.putBoolean(key, (Boolean) object);
}else if(object instanceof Float){
editor.putFloat(key, (Float) object);
}else if(object instanceof Long){
editor.putLong(key, (Long) object);
}
editor.commit();
}
/**
* 获取共享参数,根据默认数据类型获取相对应key的值
* @param context
* @param key 键
* @param defaultObject 默认值
* @return
*/
public static Object getParams(Context context, String key, Object defaultObject){
SharedPreferences sharedPreferences = context.getSharedPreferences(SHAREPRENFERENCE_NAME, Context.MODE_PRIVATE);
if(defaultObject instanceof String){
return sharedPreferences.getString(key, (String) defaultObject);
}else if(defaultObject instanceof Integer){
return sharedPreferences.getInt(key, (Integer) defaultObject);
}else if(defaultObject instanceof Boolean){
return sharedPreferences.getBoolean(key, (Boolean) defaultObject);
}else if(defaultObject instanceof Float){
return sharedPreferences.getFloat(key, (Float) defaultObject);
}else if(defaultObject instanceof Long){
return sharedPreferences.getLong(key, (Long) defaultObject);
}
return null;
}
//保存string
public static void putString(Context context, String key, String values) {
sp = context.getSharedPreferences(SHAREPRENFERENCE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
sp.edit().putString(key, values).commit();
}
//获取string
public static String getString(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(SHAREPRENFERENCE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
return sp.getString(key, "");
}
//保存boolean
public static void putBoolean(Context context, String key, boolean value) {
if (sp == null) {
sp = context.getSharedPreferences(SHAREPRENFERENCE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
}
sp.edit().putBoolean(key, value).commit();
}
//获取boolean
public static boolean getBoolean(Context context, String key, boolean defult) {
if (sp == null) {
sp = context.getSharedPreferences(SHAREPRENFERENCE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
}
return sp.getBoolean(key, defult);
}
}
3.字符串操作工具类:获取时间;时间戳转日期;保留指定位小数点;字符串判空等
private static String patternCoder = "(?
4.Bitmap处理工具类:包括bitmap保存本地;bytebuffer转bitmap;对bitmap高效高斯模糊;bitmap二次采样;bitmap图片压缩。
public class BitmapUtils {
/**
* 将bitmap保存为文件
* @param bitmap
* @param file
* @return
*/
public static boolean bitmapToFile(Bitmap bitmap, File file) {
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 将byteBuffer转为Bitmap
* @param byteBuffer
* @param width
* @param height
* @return
*/
public static Bitmap byteBufferToBitmap(ByteBuffer byteBuffer, int width, int height) {
IntBuffer intBuffer = byteBuffer.asIntBuffer();
final int[] ret = new int[byteBuffer.limit() / 4];
IntBuffer retBuffer = IntBuffer.wrap(ret);
retBuffer.put(intBuffer);
for (int i = 0; i < ret.length; i++) {
int src = ret[i];
int dest = (src & 0xFF) << 24 | (src & 0xFF000000) >> 8 | (src & 0xFF0000) >> 8 | (src & 0xFF00) >> 8;
ret[i] = dest;
}
Bitmap bitmap = Bitmap.createBitmap(ret, width, height, Bitmap.Config.ARGB_8888);
return bitmap;
}
/**
* 高效率Bitmap高斯模糊
* 还需在build.gradle加入 defaultConfig {
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
* @param context
* @param ivBlurBg
* @param bitmap
* param scaleRatio bitmap分辨率缩小比例,计算速度更快,范围 1-10
*
*/
public static void bitmapBlur(Context context, ImageView ivBlurBg, Bitmap bitmap, int scaleRatio){
int x = (int) ivBlurBg.getX();
int y = (int) ivBlurBg.getY();
int bitmapX = bitmap.getWidth();
int bitmapY = bitmap.getHeight();
Bitmap bitmapNew = Bitmap.createBitmap(bitmap,x,y,bitmapX-x,bitmapY-y);
if(bitmap != null){
Bitmap overlay = Bitmap.createScaledBitmap(bitmapNew, bitmapNew.getWidth() / scaleRatio, bitmapNew.getHeight() / scaleRatio, false);
overlay = handleGlassblur(context,overlay,15);
ivBlurBg.setImageBitmap(overlay);
}
bitmap.recycle();
}
public static Bitmap handleGlassblur(Context context, Bitmap originBitmap, int radius){
RenderScript renderScript = RenderScript.create(context);
Allocation input = Allocation.createFromBitmap(renderScript,originBitmap);
Allocation output = Allocation.createTyped(renderScript,input.getType());
ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
scriptIntrinsicBlur.setRadius(radius);
scriptIntrinsicBlur.setInput(input);
scriptIntrinsicBlur.forEach(output);
output.copyTo(originBitmap);
return originBitmap;
}
/**
* 根据指定的宽、高,对图片进行二次采样
* @param bytes
* @return
*/
public static Bitmap ScaleBitmap(byte[] bytes,int width,int height){
//获取图片的解码参数设置
BitmapFactory.Options options = new BitmapFactory.Options();
//设置为true仅仅解码图片的边缘
options.inJustDecodeBounds = true;
//对图片进行解码,如果指定了inJustDecodeBounds=true,decodeByteArray将返回为空
BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
int outWidth = options.outWidth;
int outHeight = options.outHeight;
int sampleSizeX = width/outWidth;
int sampleSizeY = height/outHeight;
int simpleSize = sampleSizeX < sampleSizeY ? sampleSizeX : sampleSizeY;
//设置inJustDecodeBounds为false重新将图片读进内存中
options.inJustDecodeBounds = false;
//实际要进行缩放的比例
options.inSampleSize = simpleSize;
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}
/**
* 图片质量压缩
* @param bitmap 需要质量压缩的图片
* @param size 指定最大要压缩成的大小,单位为k
* @return
*/
public static Bitmap compressBitmap(Bitmap bitmap, int size){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//将压缩后的数据放入bos中
bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
int quality = 100;
while(bos.toByteArray().length / 1024 > size){
//循环判断如果压缩后的图片大于100k,则清空bos,质量压缩比减小10%
bos.reset();
quality -= 10;
bitmap.compress(Bitmap.CompressFormat.JPEG,quality,bos);
}
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
//通过字节输入流转为bitmap
return BitmapFactory.decodeStream(bis,null,null);
}
5.万能接口回调类,一个类能回调任何数据类型,从此不需要再创建其他单一回调接口。
public abstract class CallBackimpl implements IcallBack{
@Override
public void callBack(List datas) {
}
@Override
public void callBack(List list, boolean charge) {
}
@Override
public void callBack(String str) {
}
@Override
public void callBack(String str, int code) {
}
@Override
public void callBack(byte[] bytes) {
}
@Override
public void callBack(Bitmap bitmap) {
}
@Override
public void confirmHandle() {
}
@Override
public void callBack(int progress) {
}
@Override
public void callBack(float num) {
}
@Override
public void callBack(int page,int subpage) {
}
@Override
public void callBack(boolean boo) {
}
@Override
public void callBack(JSONObject obj) {
}
@Override
public void callBack(String... args) {
}
@Override
public void onFail() {
}
}
6.动态获取危险权限
public class PmUtil {
//要开通的危险权限的列表
public static final String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
public static final String[] PERMISSIONS_MY_CTID = {
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
//列表中的权限是否全部开通
public static boolean havePm(List pmList, Activity activity) {
for (String pm : pmList) {
int permissionState = ActivityCompat.checkSelfPermission(activity, pm);
if (permissionState != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
//请求开通权限
public static void requestPm(List pmList, int requestCode, Activity activity) {
List needPm = checkPm(pmList, activity);
if (needPm.size() > 0) {
String[] pmsArray = needPm.toArray(new String[needPm.size()]);
ActivityCompat.requestPermissions(activity, pmsArray, requestCode);
}
}
//获取没有开通的权限列表
public static List checkPm(List pmList, Activity activity) {
List needPm = new ArrayList();
for (String pm : pmList) {
int permissionState = ActivityCompat.checkSelfPermission(activity, pm);
if (permissionState != PackageManager.PERMISSION_GRANTED) {
needPm.add(pm);
}
}
return needPm;
}
}