Android开发常用工具类

博主会长期更新Android开发中常用的工具类,有一些会转载其他博主的内容,会在对应位置标明,有什么好的建议和意见欢迎反馈,走起!

前提说明:有一些用到全局context,需要在Application中初始化,每个工具类都有详细的注释。如:

public class MyApplication extends Application {

    private static MyApplication sApp;
    private Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        sApp = this;
        mContext = getApplicationContext();

        initLogUtil();
        initSPUtil();
        initToastUtil();
        initDisplayUtil();

    }

    /**
     * 获取MyApplication实例
     */
    public static MyApplication getInstance() {
        return sApp;
    }

    /**
     * 初始化Log工具类
     */
    private void initLogUtil() {
        //DEBUG模式
        LogUtil.LEVEL = LogUtil.DEBUG;
    }

    /**
     * 初始化SharedPreferences工具类
     */
    private void initSPUtil() {
        SPUtil.sContext = mContext;
        SPUtil.sName = "share_data";
    }

    /**
     * 初始化Toast工具类
     */
    private void initToastUtil() {
        ToastUtil.sContext = mContext;
    }

    /**
     * 初始化DisplayUtil
     */
    private void initDisplayUtil() {
        DisplayUtil.sContext = mContext;
        DisplayUtil.sScreenWidth = DisplayUtil.getScreenWidth();
        DisplayUtil.sScreenHeight = DisplayUtil.getScreenWidth();
    }

}
一:ActivityUtil Activity堆栈管理

/**
 * Created by licrynoob on 2016/7/12 <br>
 * Copyright (C) 2016 <br>
 * Email:licrynoob@gmail.com <p>
 * Activity堆栈工具类
 */
public class ActivityUtil {

    /**
     * 单一实例
     */
    private static ActivityUtil sActivityUtil;
    /**
     * Activity堆栈 Stack:线程安全
     */
    private Stack<Activity> mActivityStack = new Stack<>();

    /**
     * 私有构造器 无法外部创建
     */
    private ActivityUtil() {
    }

    /**
     * 获取单一实例 双重锁
     *
     * @return
     */
    public static ActivityUtil getInstance() {
        if (sActivityUtil == null) {
            synchronized (ActivityUtil.class) {
                if (sActivityUtil == null) {
                    sActivityUtil = new ActivityUtil();
                }
            }
        }
        return sActivityUtil;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        mActivityStack.add(activity);
    }

    /**
     * 移除堆栈中的Activity
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        if (activity != null && mActivityStack.contains(activity)) {
            mActivityStack.remove(activity);
        }
    }

    /**
     * 获取当前Activity (堆栈中最后一个添加的)
     *
     * @return
     */
    public Activity getCurrentActivity() {
        return mActivityStack.lastElement();
    }

    public Activity getActivity(Class<?> cls) {
        if (mActivityStack != null)
            for (Activity activity : mActivityStack) {
                if (activity.getClass().equals(cls)) {
                    return activity;
                }
            }
        return null;
    }

    /**
     * 结束当前Activity (堆栈中最后一个添加的)
     */
    public void finishCurrentActivity() {
        Activity activity = mActivityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     *
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null && mActivityStack.contains(activity)) {
            mActivityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : mActivityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
                break;
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = mActivityStack.size(); i < size; i++) {
            if (mActivityStack.get(i) != null) {
                finishActivity(mActivityStack.get(i));
            }
        }
        mActivityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public void exitApp() {
        try {
            finishAllActivity();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

}
二:DisplayUtil 显示屏幕工具类

/**
 * Created by licrynoob on 2016/7/14 <br>
 * Copyright (C) 2016 <br>
 * Email:licrynoob@gmail.com <p>
 * 显示屏幕工具类
 * 需初始化sContext
 * 可初始化sScreenWidth & sScreenHeight
 */
public class DisplayUtil {

    public static Context sContext = null;

    /**
     * 屏幕宽度
     */
    public static int sScreenWidth = 0;
    /**
     * 屏幕高度
     */
    public static int sScreenHeight = 0;

    /**
     * 获取屏幕尺寸与密度
     *
     * @return
     */
    public static DisplayMetrics getDisplayMetrics() {
        Resources resources;
        if (sContext == null) {
            resources = Resources.getSystem();
        } else {
            resources = sContext.getResources();
        }
        return resources.getDisplayMetrics();
    }

    /**
     * TypedValue官方源码中的算法 任意单位转换为PX单位
     *
     * @param unit           TypedValue.COMPLEX_UNIT_DIP
     * @param value          对应单位的值
     * @param displayMetrics 密度
     * @return px值
     */
    public static float applyDimension(int unit, float value, DisplayMetrics displayMetrics) {
        switch (unit) {
            case TypedValue.COMPLEX_UNIT_PX:
                return value;
            case TypedValue.COMPLEX_UNIT_DIP:
                return value * displayMetrics.density;
            case TypedValue.COMPLEX_UNIT_SP:
                return value * displayMetrics.scaledDensity;
            case TypedValue.COMPLEX_UNIT_PT:
                return value * displayMetrics.xdpi * (1.0f / 72);
            case TypedValue.COMPLEX_UNIT_IN:
                return value * displayMetrics.xdpi;
            case TypedValue.COMPLEX_UNIT_MM:
                return value * displayMetrics.xdpi * (1.0f / 25.4f);
        }
        return 0;
    }

    /**
     * px 转 dp
     *
     * @param pxValue px
     * @return dp
     */
    public static float pxToDp(float pxValue) {
        DisplayMetrics displayMetrics = getDisplayMetrics();
        return pxValue / displayMetrics.density;
    }

    /**
     * dp 转 px
     *
     * @param dpValue dp
     * @return px
     */
    public static float dpToPx(float dpValue) {
        DisplayMetrics displayMetrics = getDisplayMetrics();
        return applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, displayMetrics);
    }

    /**
     * px 转 sp
     *
     * @param pxValue px
     * @return sp
     */
    public static float pxToSp(float pxValue) {
        DisplayMetrics displayMetrics = getDisplayMetrics();
        return pxValue / displayMetrics.scaledDensity;
    }

    /**
     * sp 转 px
     *
     * @param spValue sp
     * @return px
     */
    public static float spToPx(float spValue) {
        DisplayMetrics displayMetrics = getDisplayMetrics();
        return applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, displayMetrics);
    }

    /**
     * 获得屏幕宽度
     *
     * @return
     */
    public static int getScreenWidth() {
        WindowManager wm = (WindowManager) sContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @return
     */
    public static int getScreenHeight() {
        WindowManager wm = (WindowManager) sContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 获得状态栏的高度
     *
     * @return
     */
    public static int getStatusHeight() {
        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 = sContext.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 获取当前屏幕截图,包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap screenShotWithStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int width = getScreenWidth();
        int height = getScreenHeight();
        Bitmap bitmap;
        bitmap = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return bitmap;
    }

    /**
     * 获取当前屏幕截图,不包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap screenShotWithoutStatusBar(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();
        int height = getScreenHeight();
        Bitmap bitmap;
        bitmap = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return bitmap;
    }
    
}
三:ToastUtil 提示框工具类

/**
 * Created by licrynoob on 2016/7/12 <br>
 * Copyright (C) 2016 <br>
 * Email:licrynoob@gmail.com <p>
 * Toast工具类
 * 需初始化sContext
 */
public class ToastUtil {

    public static Context sContext = null;

    /**
     * 短时间显示Toast
     *
     * @param message
     */
    public static void showShort(CharSequence message) {
        Toast.makeText(sContext, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 短时间显示Toast
     *
     * @param message
     */
    public static void showShort(int message) {
        Toast.makeText(sContext, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 长时间显示Toast
     *
     * @param message
     */
    public static void showLong(CharSequence message) {
        Toast.makeText(sContext, message, Toast.LENGTH_LONG).show();
    }

    /**
     * 长时间显示Toast
     *
     * @param message
     */
    public static void showLong(int message) {
        Toast.makeText(sContext, message, Toast.LENGTH_LONG).show();
    }

    /**
     * 自定义显示Toast时间
     *
     * @param message
     * @param duration
     */
    public static void showDuration(CharSequence message, int duration) {
        Toast.makeText(sContext, message, duration).show();
    }

    /**
     * 自定义显示Toast时间
     *
     * @param message
     * @param duration
     */
    public static void showDuration(int message, int duration) {
        Toast.makeText(sContext, message, duration).show();
    }

}
四:LogUtil 日志工具类

/**
 * Created by licrynoob on 2016/7/12 <br>
 * Copyright (C) 2016 <br>
 * Email:licrynoob@gmail.com <p>
 * Log工具类 重载默认包括当前类名和方法名
 */
public class LogUtil {

    public static final int VERBOSE = 1;
    public static final int DEBUG = 2;
    public static final int INFO = 3;
    public static final int WARN = 4;
    public static final int ERROR = 5;
    public static final int NOTHING = 6;
    public static int LEVEL = -1;

    public static void v(String tag, String msg) {
        if (LEVEL <= VERBOSE) {
            Log.v(tag, msg);
        }
    }

    public static void v(String msg) {
        if (LEVEL <= VERBOSE) {
            Log.v("[类:" + getClassName() + " 方法:" + getMethodName() + "]", msg);
        }
    }


    public static void d(String tag, String msg) {
        if (LEVEL <= DEBUG) {
            Log.d(tag, msg);
        }
    }

    public static void d(String msg) {
        if (LEVEL <= DEBUG) {
            Log.d("[类:" + getClassName() + " 方法:" + getMethodName() + "]", msg);
        }
    }

    public static void i(String tag, String msg) {
        if (LEVEL <= INFO) {
            Log.i(tag, msg);
        }
    }

    public static void i(String msg) {
        if (LEVEL <= INFO) {
            Log.i("[类:" + getClassName() + " 方法:" + getMethodName() + "]", msg);
        }
    }

    public static void w(String tag, String msg) {
        if (LEVEL <= WARN) {
            Log.w(tag, msg);
        }
    }

    public static void w(String msg) {
        if (LEVEL <= WARN) {
            Log.w("[类:" + getClassName() + " 方法:" + getMethodName() + "]", msg);
        }
    }

    public static void e(String tag, String msg) {
        if (LEVEL <= ERROR) {
            Log.e(tag, msg);
        }
    }

    public static void e(String msg) {
        if (LEVEL <= ERROR) {
            Log.e("[类:" + getClassName() + " 方法:" + getMethodName() + "]", msg);
        }
    }

    /**
     * 获取当前类名
     *
     * @return
     */
    public static String getClassName() {
        return Thread.currentThread().getStackTrace()[1].getClassName();
    }

    /**
     * 获取当前方法名
     *
     * @return
     */
    public static String getMethodName() {
        return Thread.currentThread().getStackTrace()[1].getMethodName();
    }
    
}

五:基于Volley的ImageUtil 图片工具类

/**
 * Created by licrynoob on 2016/7/12 <br>
 * Copyright (C) 2016 <br>
 * Email:licrynoob@gmail.com <p>
 * 图片工具类
 */
public class ImageUtil implements ImageLoader.ImageCache {

    /**
     * LruCache
     */
    public static LruCache<String, Bitmap> sLruCache = null;
    /**
     * LruCache缓存大小 单位:B
     */
    public static int sLruCacheSize = 0;

    @Override
    public Bitmap getBitmap(String s) {
        return sLruCache.get(s);
    }

    @Override
    public void putBitmap(String s, Bitmap bitmap) {
        sLruCache.put(s, bitmap);
    }


    /**
     * 从路径获取压缩图片
     *
     * @param path
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

    /**
     * ResourceBitmap压缩
     *
     * @param res       资源文件
     * @param resId     资源Id
     * @param reqWidth  需求图片宽
     * @param reqHeight 需求图片高
     * @return 压缩后的Bitmap
     */
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    /**
     * FileDescriptorBitmap压缩 比decodeFile省内存
     *
     * @param fd        资源文件
     * @param reqWidth  需求图片宽
     * @param reqHeight 需求图片高
     * @return 压缩后的Bitmap
     */
    public static Bitmap decodeSampledBitmapFromFileDescriptor(FileDescriptor fd, int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fd, null, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFileDescriptor(fd, null, options);
    }

    /**
     * 获得裁剪图片的InSampleSize
     *
     * @param options   options
     * @param reqWith   需求的宽度
     * @param reqHeight 需求的高度
     * @return inSampleSize
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWith, int reqHeight) {
        //原来图片宽高
        final int oldWith = options.outWidth;
        final int oldHeight = options.outHeight;
        LogUtil.d("[oldWith]:" + oldWith + "[oldHeight]:" + oldHeight);
        int inSampleSize = 1;
        //默认不压缩
        if (reqWith == 0 || reqHeight == 0) {
            return inSampleSize;
        }
        if (oldWith > reqWith || oldHeight > reqHeight) {
            //宽比例
            final int withRatio = Math.round((float) oldWith / (float) reqWith);
            //高比例
            final int heightRatio = Math.round((float) oldHeight / (float) reqHeight);
            //选取小的比例,保证需求的图片宽和高都不小于原图片
            inSampleSize = withRatio < heightRatio ? withRatio : heightRatio;
        }
        return inSampleSize;
    }

    /**
     * Drawable 转 Bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * Bitmap 转 Drawable
     *
     * @param bitmap
     * @return
     */
    public static Drawable bitmapToDrawable(Bitmap bitmap) {
        BitmapDrawable mBitmapDrawable = null;
        try {
            if (bitmap == null) {
                return null;
            }
            mBitmapDrawable = new BitmapDrawable(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mBitmapDrawable;
    }

    /**
     * 保存bitmap
     *
     * @param bitmap
     * @param bitmapUri 图片Uri
     */
    public static void saveBitmap(Bitmap bitmap, String bitmapUri) {
        File f = new File(bitmapUri);
        if (f.exists()) {
            f.delete();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
其中初始化部分为:

 /**
     * 初始化Volley请求队列
     */
    private void initRequestQueue() {
        MyVariable.sRequestQueue = Volley.newRequestQueue(mContext);
    }

    /**
     * 初始化图片缓存
     */
    private void initImageUtil() {
        /*LruCache*/
        MyVariable.sMaxMemory = Runtime.getRuntime().maxMemory();
        // 设置LruCacheSize为程序最大可用内存的1/8
        ImageUtil.sLruCacheSize = (int) (MyVariable.sMaxMemory / 8);
        ImageUtil.sLruCache = new LruCache<String, Bitmap>(ImageUtil.sLruCacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount() / 1024;
            }
        };
        MyVariable.sImageLoader = new ImageLoader(MyVariable.sRequestQueue, new ImageUtil());
    }










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值