android开发之常用工具类

下面是本人在项目开发中收集总结的一些常用工具类,希望能帮助到各位,话不多说,直接上代码

1、Decimal数据精确计算及小数保留工具类

public class ArithDecimal {

    // 默认除法运算精度
    private static final int DEF_DIV_SCALE = 10;

    // 这个类不能实例化
    private ArithDecimal() {

    }

    /**
     * 提供精确的加法运算
     * @param v1 被加数
     * @param v2  加数
     * @return 两个参数的和
     */
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }

    /**
     * 提供精确的减法运算 v1-v2
     * @param v1     被减数
     * @param v2     减数
     * @return 两个参数的差
     */
    public static double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 提供精确的乘法运算
     * @param v1       被乘数
     * @param v2       乘数
     * @return 两个参数的积
     */
    public static double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }

    /**
     * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入
     * @param v1      被除数
     * @param v2        除数
     * @return 两个参数的商
     */
    public static double div(double v1, double v2) {
        return div(v1, v2, DEF_DIV_SCALE);
    }

    /**
     * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。v1/v2
     * @param v1         被除数
     * @param v2       除数
     * @param scale      表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        if(v2 == 0.0){
            return 0.0;
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 提供精确的小数位四舍五入处理。
     * @param v         需要四舍五入的数字
     * @param scale      小数点后保留几位
     * @return 四舍五入后的结果
     */
    public static double round(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 格式化小数点后面的多余的0
     * @param object
     * @return
     */
    public static String formatDotZero(Object object) {
        DecimalFormat decimalFormat = new DecimalFormat("#########.#########");
        return decimalFormat.format(object);
    }

    public static String formatDouNum(Object object, Integer FDotNum) {
        BigDecimal b = new BigDecimal(object.toString());
        return b.setScale(FDotNum, BigDecimal.ROUND_HALF_UP).toString();
    }

    /**
     * 不进行四舍五入 删除多余的数
     * @param v
     * @param scale
     * @returnd
     */
    public static double round_down(double v,int scale){
        if(scale<0){
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one,scale,BigDecimal.ROUND_DOWN).doubleValue();
    }

    /**
     * 将double类型小数点后面的都去掉,并返回字符串类型
     * @param v
     * @return
     */
    public static String getCount(double v){
        String str = String.valueOf(v);
        String newStr = "--";
        if(str.contains(".")){
            newStr = str.substring(0,str.indexOf("."));
        }else{
            newStr = str;
        }
        return newStr;
    }

    /**
     * 保留2位小数
     * @param d1
     * @return
     */
    public static String retainTwo(double d1){
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(d1);
    }

2、判断当前网络是否连接工具类

public class ConnectionUtils {
    /**
     * 获取当前网络类型
     * @return 0:没有网络   1:WIFI网络   2:WAP网络    3:NET网络
     */
    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;

    /**
     * 检测网络是否可用
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }

    public static int getNetworkType(Context context) {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if (!TextUtils.isEmpty(extraInfo)) {
                if (extraInfo.toLowerCase().equals("cmnet")) {
                    netType = NETTYPE_CMNET;
                } else {
                    netType = NETTYPE_CMWAP;
                }
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }

    public static void setNetType(Context context) {
        AppState.netState = getNetworkType(context);
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }
}

3、日期获取及转化工具类

public class DateUtils {
    private static String TAG = "DateUtils";
    public static String[] weekName = {"日", "一", "二", "三", "四", "五", "六"};
    public final static String CALENDAR_DATA_TIME = "MM/dd-HH:mm";
    public final static String CALENDAR_TIME = "HH:mm";
    public final static String CALENDAR_YEAR_DATA = "yyyy/MM/dd";
    public final static String CALENDAR_DATA = "MM/dd";
    public final static String CALENDAR_YEAR_MONTH = "yyyy/MM";

    private static SimpleDateFormat dateFormat1 = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm");

    private static SimpleDateFormat dateFormat2 = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    private static SimpleDateFormat dateFormat3 = new SimpleDateFormat(
            "yyyy/MM/dd HH:mm:ss");

    //输入年月得到月份天数
    public static int getMonthDays(int year, int month) {
        if (month > 12 || month < 1) {
            LogUtils.v(TAG, "date error");
            return 0;
        }
        int[] arr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int days = 0;

        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            arr[1] = 29; // 闰年2月29天
        }
        days = arr[month - 1];

        return days;
    }

    public static int getYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }

    public static int getMonth() {
        return Calendar.getInstance().get(Calendar.MONTH) + 1;
    }

    public static int getDate() {
        return Calendar.getInstance().get(Calendar.DATE) ;
    }

    public static int getCurrentMonthDay() {
        return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    }

    public static int getWeekDay() {
        return Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
    }

    public static int getHour() {
        return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    }

    public static int getMinute() {
        return Calendar.getInstance().get(Calendar.MINUTE);
    }

    /**
     * 通过日期获得星期几
     *
     * @param year
     * @param month
     * @param date
     * @return
     */
    public static String getWeekOfDate(int year, int month, int date) {
        Calendar time = Calendar.getInstance();
        time.clear();
        time.set(Calendar.YEAR, year); //year 为 int
        time.set(Calendar.MONTH, month - 1);//注意,Calendar对象默认一月为0
        time.set(Calendar.DATE, date);//注意,Calendar对象默认一月为0
        Calendar cal = Calendar.getInstance();
        Date dates = cal.getTime();
        return getWeekOfDate(dates);
    }


    public static String getWeekOfDate(Date dt) {
        // String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五",
        // "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return weekName[w];
    }

    /**
     * 取不同格式的当前时间
     * @return yyyyMMdd
     */
    public static String getStrDate() {
        SimpleDateFormat da = new SimpleDateFormat("yyyyMMdd");
        return da.format(new Date());
    }

    public static String getTime() {
        SimpleDateFormat da = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return da.format(new Date());
    }

    public static String getOrderTime() {
        SimpleDateFormat da = new SimpleDateFormat("HH:mm:ss");
        return da.format(new Date());
    }

    public static String getOrderDate(){
        SimpleDateFormat da = new SimpleDateFormat("yyyy-MM-dd");
        return da.format(new Date());
    }

    public static int getWeekOfDateintForYMDInt(int year, int month, int date) {
        Calendar time = Calendar.getInstance();
        time.clear();
        time.set(Calendar.YEAR, year); //year 为 int
        time.set(Calendar.MONTH, month - 1);//注意,Calendar对象默认一月为0
        time.set(Calendar.DATE, date);//注意,Calendar对象默认一月为0
        Date dates = time.getTime();
        return getWeekOfDateint(dates);
    }


    public static int getWeekOfDateint(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return w;
    }

    //日期String格式转换成long类型格式
    public static long getLongDate(String date){
        //将字符串类型转化成Date类型
        //String date="2009-08-04 14:37:47";
        if(date.equals("")){
            return 0;
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d2=null;
        long t3 = 0;
        try {
            d2=sdf.parse(date);//将String to Date类型
            t3=d2.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return t3;
    }
    //Date转String
    public static String parseDateToString(Date date){
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return df.format(date);
    }

    //long类型转换成date格式
    public static String getDateDate(long date){
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //前面的date如果是秒数,就要先乘1000得到毫秒数,再转为java.util.Date类型
        java.util.Date dt = new Date(date);
        String sDateTime = sdf.format(dt);  //得到精确到秒的表示
        return sDateTime;
    }

    //long转Calendar
    public static Calendar parseLongToCalendar(long date){
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date dt = new Date(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dt);
        return calendar;
    }

    /**
     * 将calendar的时间转换为 yyyy-MM-dd HH:mm:ss格式的string时间
     * @param calendar
     * @return
     */
    public static String parseCalendarToString(Calendar calendar) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 将calendar的时间转换为 pattern 指定格式的string时间
     *
     * @param calendar
     * @return
     */
    public static String parseCalendarToString(Calendar calendar, String pattern) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 将calendar的时间转换为string时间
     *
     * @CALENDAR_DATA MM/dd
     * @CALENDAR_YEAR_DATA yyyy/MM/dd
     * @CALENDAR_TIME HH:mm
     * @CALENDAR_DATA_TIME MM/dd-HH:mm
     * @CALENDAR_YEAR_MONTH yyyy/MM
     */
    public static String parseCalendarToStringByType(String type,Calendar calendar) {
        if (type == null || type.equals(""))
            return null;
        if (calendar == null)
            return null;

        SimpleDateFormat dateFormat = new SimpleDateFormat(type);
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 取当前时间
     * @return yyyyMMdd
     */
    public static String getCurrDate() {
        SimpleDateFormat da = new SimpleDateFormat("yyyyMMdd");
        return da.format(new Date());
    }

    /**
     * 将String字符串的时间转换为Calendar
     *
     * @param dateTime
     * @return Calendar的时间
     */
    public static Calendar parseStringToCalendar(String dateTime) {
        Calendar calendar = null;
        try {
            // "^(\\d{4})-([0-1]\\d)-([0-3]\\d)\\s([0-5]\\d):([0-5]\\d):([0-5]\\d)$";
            // String regex2 = "^\\d{4}(\\-|\\/|\\.)\\d{1,2}\\1\\d{1,2}$";
            String regex1 = "^[1-9]\\d{3}\\-(0?[1-9]|1[0-2])\\-(0?[1-9]|[12]\\d|3[01])\\s*(0?[0-9]|1\\d|2[0-3])(\\:(0?[0-9]|[1-5]\\d)){2}$";
            String regex2 = "^[1-9]\\d{3}\\-(0?[1-9]|1[0-2])\\-(0?[1-9]|[12]\\d|3[01])\\s*(0?[0-9]|1\\d|2[0-3])(\\:(0?[0-9]|[1-5]\\d)){1}$";
            String regex3 = "^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9])\\s*([01][0-9]|[2][0-3])$";
            String regex4 = "^[1-9]\\d{3}\\-(0?[1-9]|1[0-2])\\-(0?[1-9]|[12]\\d|3[01])$";
            String regex5 = "^[1-9]\\d{3}\\/(0?[1-9]|1[0-2])\\/(0?[1-9]|[12]\\d|3[01])\\s*(0?[0-9]|1\\d|2[0-3])(\\:(0?[0-9]|[1-5]\\d)){2}$";
            String regex6 = "^[1-9]\\d{3}\\/(0?[1-9]|1[0-2])\\/(0?[1-9]|[12]\\d|3[01])\\s*(0?[0-9]|1\\d|2[0-3])(\\:(0?[0-9]|[1-5]\\d)){1}$";
            String regex7 = "^[1-2][0-9][0-9][0-9]/([1][0-2]|0?[1-9])/([12][0-9]|3[01]|0?[1-9])\\s*([01][0-9]|[2][0-3])$";
            String regex8 = "^[1-9]\\d{3}\\/(0?[1-9]|1[0-2])\\/(0?[1-9]|[12]\\d|3[01])$";

            // yyyy-MM-dd HH:mm:ss格式的正则匹配
            if (dateTime.trim().matches(regex1)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");
                Date date = dateFormat.parse(dateTime);
                calendar = Calendar.getInstance();
                calendar.setTime(date);
            }
            if (dateTime.trim().matches(regex2)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm");
                Date date = dateFormat.parse(dateTime);
                calendar = Calendar.getInstance();
                calendar.setTime(date);
            }
            if (dateTime.trim().matches(regex3)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyy-MM-dd HH");
                Date date = dateFormat.parse(dateTime);
                calendar = Calendar.getInstance();
                calendar.setTime(date);
            }
            if (dateTime.trim().matches(regex4)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = dateFormat.parse(dateTime);
                calendar = Calendar.getInstance();
                calendar.setTime(date);
            }
            if (dateTime.trim().matches(regex5)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyy/MM/dd HH:mm:ss");
                Date date = dateFormat.parse(dateTime);
                calendar = Calendar.getInstance();
                calendar.setTime(date);
            }
            if (dateTime.trim().matches(regex6)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyy/MM/dd HH:mm");
                Date date = dateFormat.parse(dateTime);
                calendar = Calendar.getInstance();
                calendar.setTime(date);
            }
            if (dateTime.trim().matches(regex7)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyy/MM/dd HH");
                Date date = dateFormat.parse(dateTime);
                calendar = Calendar.getInstance();
                calendar.setTime(date);
            }
            if (dateTime.trim().matches(regex8)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                Date date = dateFormat.parse(dateTime);
                calendar = Calendar.getInstance();
                calendar.setTime(date);
            }

            return calendar;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 将String字符串的时间转换为Calendar
     *
     * @param dateTime
     * @return Calendar的时间
     */
    public static Calendar parseStringToCalendarForChart(String dateTime) {

        Calendar calendar = null;

        try {

            if (!Utils.isEmpty(dateTime)) {
                String[] arr = dateTime.split(":");

                if (dateTime.trim().length() <= 16 && arr.length <= 2) {
                    //SimpleDateFormat dateFormat = new SimpleDateFormat(
                    //      "yyyy-MM-dd HH:mm");
                    Date date = dateFormat1.parse(dateTime);
                    calendar = Calendar.getInstance();
                    calendar.setTime(date);
                } else {
                    if (dateTime.indexOf('-') != -1) {
                        //SimpleDateFormat dateFormat = new SimpleDateFormat(
                        //      "yyyy-MM-dd HH:mm:ss");
                        Date date = dateFormat2.parse(dateTime);
                        calendar = Calendar.getInstance();
                        calendar.setTime(date);
                    } else if (dateTime.indexOf('/') != -1) {
                        //SimpleDateFormat dateFormat = new SimpleDateFormat(
                        //      "yyyy/MM/dd HH:mm:ss");
                        Date date = dateFormat3.parse(dateTime);
                        calendar = Calendar.getInstance();
                        calendar.setTime(date);
                    }
                }
            }
            return calendar;
        } catch (Exception e) {
            return null;
        }
    }
}

4、屏幕像素密度工具类

public class DensityUtil {
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int getWindowHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getHeight();
    }

    public static int getWindowWeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

}

5、正在加载中对话框工具类

public class LoadingDialogUtils {
    ProgressDialog dialog;

    public LoadingDialogUtils(Context context) {
        dialog = new ProgressDialog(context);
    }

    public void showLoadingDialog(String msg1, String msg2) {
        if (dialog.isShowing()) return;
        dialog.setMessage(msg2);
        dialog.setTitle(msg1);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        dialog.setCancelable(true);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(true);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.show();
        LogUtils.v(this.toString(), "show Dialog");
    }

    public void disMissDialog() {
        LogUtils.v(this.toString(), "cancel dialog");
        if(dialog.isShowing()){
            dialog.cancel();
        }
    }
}

6、log打印工具类

public class LogUtils {
    private static final String TAG = "LogUtils";
    // 发布时改false
    private static final boolean LOGGER = true;

    public static void v(String tag, Object msg) {
        if (LOGGER) {
            Log.v(TAG, tag + "-->" + msg);
        }
    }

    public static void d(String tag, Object msg) {
        if (LOGGER) {
            Log.d(TAG, tag + "-->" + msg);
        }
    }

    public static void i(String tag, Object msg) {
        if (LOGGER) {
            Log.i(TAG, tag + "-->" + msg);
        }
    }

    public static void i(Object msg) {
        if (LOGGER) {
            Log.i("test", tag + "-->" + msg);
        }
    }

    public static void w(String tag, Object msg) {
        if (LOGGER) {
            Log.v(TAG, tag + "-->" + msg);
        }
    }

    public static void e(String tag, Object msg) {
        if (LOGGER) {
            Log.e(TAG, tag + "-->" + msg);
        }
    }

    public static void e(String tag, Object msg, Throwable tr) {
        if (LOGGER) {
            Log.e(TAG, tag + "-->" + msg);
        }
    }

    public static void e( Object msg) {
        if (LOGGER) {
            Log.e(TAG, tag + "-->" + msg);
        }
    }

    /**
     * log打印数据量较大的时候使用
     * @param tag
     * @param res
     */
    public static void bigData(String tag,String res){
        if(LOGGER){
            if (res.length() > 3000) {
                Log.v(TAG, tag+"-->length == " + res.length());
                int chunkCount = res.length() / 3000;     // integer division
                for (int i = 0; i <= chunkCount; i++) {
                    int max = 3000 * (i + 1);
                    if (max >= res.length()) {
                        Log.v(TAG, "chunk " + i + " of " + chunkCount + "-->" + res.substring(3000 * i));
                    } else {
                        Log.v(TAG, "chunk " + i + " of " + chunkCount + "-->" + res.substring(3000 * i, max));
                    }
                }
            } else {
                Log.v(TAG, tag + "-->" + res.toString());
            }
        }
    }
}

7、sharedPreferences工具类

public class SPrefUtils {
    /**
     * 保存在手机里面的文件名
     */
    public static final String FILE_NAME = "share_data";

    /**
     * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
     *
     * @param context
     * @param key
     * @param object
     */
    public static void put(Context context, String key, Object object) {
        if(context==null || key==null || object==null){
            return;
        }

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.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);
        } else {
            editor.putString(key, object.toString());
        }

        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
     *
     * @param context
     * @param key
     * @param
     * @return
     */
    public static Object get(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    public static String get(Context context, String key) {
        if(context==null || key==null){
            return null;
        }
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getString(key, null);
    }

    public static Boolean getBoolean(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getBoolean(key, false);
    }

    /**
     * 移除某个key值已经对应的值
     *
     * @param context
     * @param key
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有数据
     *
     * @param context
     */
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查询某个key是否已经存在
     *
     * @param context
     * @param key
     * @return
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * 返回所有的键值对
     *
     * @param context
     * @return
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     *
     * @author zhy
     */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }

            return null;
        }

        /**
         * 如果找到则使用apply执行,否则使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }
}

8、Toast工具类

public final class ToastUtil {
    // App生命周期中唯一Context,CrashApplication继承Application
    private static Context mContext = BaseApp.getInstance();

    // 全局的toast实例
    private static Toast mToast;

    // 短时间显示toast
    public static void showShort(String text) {
        if (mContext == null) {
            mContext = BaseApp.getInstance();
        }

        if (mToast == null) {
            mToast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
        }

        mToast.setText(text);
        mToast.setDuration(Toast.LENGTH_SHORT);
        mToast.show();
    }

    public static void showShort(int resId) {
        if (mContext == null) {
            mContext = BaseApp.getInstance();
        }

        if (mToast == null) {
            mToast = Toast.makeText(mContext, resId, Toast.LENGTH_SHORT);
        }

        mToast.setText(resId);
        mToast.setDuration(Toast.LENGTH_SHORT);
        mToast.show();
    }

    // 长时间显示toast
    public static void showLong(String text) {
        if (mContext == null) {
            mContext = BaseApp.getInstance();
        }

        if (mToast == null) {
            mToast = Toast.makeText(mContext, text, Toast.LENGTH_LONG);
        }

        mToast.setText(text);
        mToast.setDuration(Toast.LENGTH_LONG);
        mToast.show();
    }

    public static void showLong(int resId) {
        if (mContext == null) {
            mContext = BaseApp.getInstance();
        }

        if (mToast == null) {
            mToast = Toast.makeText(mContext, resId, Toast.LENGTH_LONG);
        }

        mToast.setText(resId);
        mToast.setDuration(Toast.LENGTH_LONG);
        mToast.show();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值