总结Android开发中常用的工具类

我们在日常开发中,都会有一些常用的辅助工具类,完成一些非业务方面的功能,今天抽空整理出13个工具类,这些工具类基本在我们开发项目中都会用到。本人也是第一次写博客先从简单的开始就算试试水了,废话不多说了,接下来我们直接看代码,写的不好的地方希望大家多多留言。

1、日志管理类

import android.util.Log;

/**
 * Created by guojingbu on 2017/12/16.
 */

public class LogUtils {

    /**
    *
    *是否需要打印bug,可以在application的onCreate函数里面初始化
    */
    public static boolean isDebug = true;
    /**
     * 过滤log标记
     */
    private static final String TAG = "APPDemo";

    public static void i(String msg)
    {
        if (isDebug)
            Log.i(TAG, msg);
    }

    public static void d(String msg)
    {
        if (isDebug)
            Log.d(TAG, msg);
    }

    public static void e(String msg)
    {
        if (isDebug)
            Log.e(TAG, msg);
    }

    public static void v(String msg)
    {
        if (isDebug)
            Log.v(TAG, msg);
    }

    public static void i(String tag, String msg)
    {
        if (isDebug)
            Log.i(tag, msg);
    }

    public static void d(String tag, String msg)
    {
        if (isDebug)
            Log.d(tag, msg);
    }

    public static void e(String tag, String msg)
    {
        if (isDebug)
            Log.e(tag, msg);
    }

    public static void v(String tag, String msg)
    {
        if (isDebug)
            Log.v(tag, msg);
    }
    public static void print(String msg){
        if(isDebug){
            System.out.println(msg);    
        }

    }
}

我们以前打log一直用的就是这种管理方式,现在能由于各种问题给调试带来不便,需要做到上传日志到我们的管理平台,程序一旦有问题我们只需要查看管理平台的日志就好了,这样可以提高我们的解决问题的效率。当然了上面这个是一个简单的工具类还没有实现上传日志到管理平台的功能。

2、Toast统一管理类

mport android.content.Context;
import android.widget.Toast;

/**
 * Created by guojingbu on 2017/12/16.
 */

public class ToastUtils {

    private ToastUtils()
    {

    }

    public static boolean isShow = true;

    public static void showShort(Context context, String message)
    {
        if (isShow){
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }
    }

    public static void showShort(Context context, int message)
    {
        if (isShow)
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    public static void showLong(Context context, String message)
    {
        if (isShow) {
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }
    }

    public static void showLong(Context context, int message)
    {
        if (isShow) {
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }
    }

}

3、SharedPreferences封装类SPUtils

import android.content.Context;
import android.content.SharedPreferences;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by guojingbu on 2017/12/16.
 */

public class SPUtils {

    private  SPUtils(){

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

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

            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 defaultObject
         * @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;
        }

        /**
         * 移除某个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();
            }
        }

    /**
     * 存入一个对象
     * 
     * @param context
     * @param object
     * @param key
     * @return
     */
    public static boolean setObjectToShare(Context context, Object object, String key) {
        // TODO Auto-generated method stub
        SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(context);
        if (object == null) {
            Editor editor = share.edit().remove(key);
            return editor.commit();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        // 将对象放到OutputStream中
        // 将对象转换成byte数组,并将其进行base64编码
        String objectStr = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
        try {
            baos.close();
            oos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SharedPreferences.Editor editor = share.edit();
        // 将编码后的字符串写到base64.xml文件中
        editor.putString(key, objectStr);
        return editor.commit();
    }
    /**
     * 获取一个对象
     * @param context
     * @param key
     * @return
     */
    public static Object getObjectFromShare(Context context, String key) {
        SharedPreferences sharePre = PreferenceManager.getDefaultSharedPreferences(context);
        try {
            String wordBase64 = sharePre.getString(key, "");
            // 将base64格式字符串还原成byte数组
            if (wordBase64 == null || wordBase64.equals("")) { // 不可少,否则在下面会报java.io.StreamCorruptedException
                return null;
            }
            byte[] objBytes = Base64.decode(wordBase64.getBytes(), Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            // 将byte数组转换成product对象
            Object obj = ois.readObject();
            bais.close();
            ois.close();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    }

这个工具类是我看到鸿洋大神2014年发表的博客中的一个工具类方法个人认为这封装的挺好的所给大家分享一下。
4、通用的工具

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.yesway.virtualkeys.view.dialog.SafeCertificationDialog;
import com.yesway.virtualkeys.view.dialog.StandardAlertDialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;

/**
 * 通用工具类
 * @author guojingbu
 *
 */
public class CommonUtils {

    /**
     * 手机号中间号码替换为*
     * @param phone
     * @return
     */
    public static String getEncryptedPhoneNumber(String phone) {
        if (TextUtils.isEmpty(phone)) {
            return "";
        }
        char[] tmpPhone = phone.toCharArray();
        for (int i = 0; i < tmpPhone.length; i++) {
            if (i >= 3 && i <= 6) {
                tmpPhone[i] = '*';
            }
        }
        return new String(tmpPhone);
    }

    /**
     * MD5加密
     * @param s
     * @return
     * @throws NoSuchAlgorithmException
     */
    private final static String MD5(String s) throws NoSuchAlgorithmException {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        byte[] btInput = s.getBytes();
        // 获得MD5摘要算法的 MessageDigest 对象
        MessageDigest mdInst = MessageDigest.getInstance("MD5");
        // 使用指定的字节更新摘要
        mdInst.update(btInput);
        // 获得密文
        byte[] md = mdInst.digest();
        // 把密文转换成十六进制的字符串形式
        int length = md.length;
        char str[] = new char[length * 2];
        int k = 0;
        for (int i = 0; i < length; i++) {
            byte byte0 = md[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }

    /**
     * null 字符串处理
     * @param s
     * @return
     */
    public static String safeString(String s) {
        if (s == null) {
            return "";
        }
        return s;
    }

    /**
     * 字符串Base64编码
     * @param s
     * @return
     */
    public static byte[] encode(String s) {
        byte[] data;
        try {
            data = s.getBytes("utf-8");
            byte[] result = Base64.encode(data, Base64.DEFAULT);
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 校验手机号
     * @param phoneNumber
     * @return
     */
    public static boolean isValidPhoneNumber(String phoneNumber) {
        if (phoneNumber == null) {
            return false;
        }
        String regExp = "^(1)\\d{10}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(phoneNumber);
        return m.find();
    }

}

这个工具类主要是一些通用的工具类方法,比如校验电话号码是否合法、字符串BASE64编码、字符串的MD5加密等等。

5、int转化为byte的工具类


/**
 * Created by guojingbu on 2017/12/16.
 */

public class Int2Byte {

    /**
     * 以大端模式将int转成byte[]
     */
    public static byte[] intToBytesBig(int value) {
        byte[] src = new byte[4];
        src[0] = (byte) ((value >> 24) & 0xFF);
        src[1] = (byte) ((value >> 16) & 0xFF);
        src[2] = (byte) ((value >> 8) & 0xFF);
        src[3] = (byte) (value & 0xFF);
        return src;
    }

    /**
     * 以小端模式将int转成byte[]
     *
     * @param value
     * @return
     */
    public static byte[] intToBytesLittle(int value) {
        byte[] src = new byte[4];
        src[3] = (byte) ((value >> 24) & 0xFF);
        src[2] = (byte) ((value >> 16) & 0xFF);
        src[1] = (byte) ((value >> 8) & 0xFF);
        src[0] = (byte) (value & 0xFF);
        return src;
    }

    /**
     * 以大端模式将byte[]转成int
     */
    public static int bytesToIntBig(byte[] src, int offset) {
        int value;
        value = (int) (((src[offset] & 0xFF) << 24)
                | ((src[offset + 1] & 0xFF) << 16)
                | ((src[offset + 2] & 0xFF) << 8)
                | (src[offset + 3] & 0xFF));
        return value;
    }

    /**
     * 以小端模式将byte[]转成int
     */
    public static int bytesToIntLittle(byte[] src, int offset) {
        int value;
        value = (int) ((src[offset] & 0xFF)
                | ((src[offset + 1] & 0xFF) << 8)
                | ((src[offset + 2] & 0xFF) << 16)
                | ((src[offset + 3] & 0xFF) << 24));
        return value;
    }
}

这个工具类主要是在解析二进制协议的时候比较常用,一般的开发中也是比较少用的。

6、下载文件工具类

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.os.Environment;
import android.util.Log;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

public class LoadUtils {
    private static final String TAG = "DownLoadUtils";
    private OkHttpClient mOkHttpClient;
    private static LoadUtils instance;

    private LoadUtils() {
        mOkHttpClient = new OkHttpClient();
    }

    public static LoadUtils getInstance() {
        if (instance == null) {
            instance = new LoadUtils();
        }
        return instance;
    }

    public void donwnloadFile(String url, final DownloadCallback callback) {
        Request request = new Request.Builder().url(url).addHeader("Accept-Encoding", "identity").build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @SuppressWarnings("resource")
            @Override
            public void onResponse(Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                String SDPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                try {
                    is = response.body().byteStream();
                    long current = 0;
                    long total = response.body().contentLength();
                    Log.i("guojingbu", "duixiang:total = " + response.body());
                    LogUtil.i("guojingbu", "数据大小:total = " + total);
                    File file = new File(SDPath, "test.txt");
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        current += len;
                        fos.write(buf, 0, len);
                        callback.onprogress(total, current);
                    }
                    fos.flush();
                    callback.onSuccess(file);
                    LogUtil.i("guojingbu", "文件下载成功");
                } catch (Exception e) {
                    callback.onFailure(e);
                    LogUtil.i("guojingbu", "文件下载失败");
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                callback.onFailure(e);
                LogUtil.i("guojingbu", "onFailure");
            }
        });
    }

    public interface DownloadCallback {

        void onSuccess(File file);

        void onFailure(Exception e);

        void onprogress(long total, long current);
    }

    public static String readInputStream(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int length = 0;
            byte[] buffer = new byte[1024];
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            is.close();
            baos.close();
            // 或者用这种方法
            byte[] result = baos.toByteArray();
            // return new String(result);
            return new String(result, "GBK");
        } catch (Exception e) {
            e.printStackTrace();
            return "获取失败";
        }
    }
}
这个工具类主要是基于OKHTTP封装的一个下载带更新进度的一个工具类,值得注意的是request必须设置addHeader("Accept-Encoding", "identity")这个头才能获取到文件的大小,否则获取的都是0。

7、network工具类

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


public class NetworkUtils {
    public static final String NET_TYPE_WIFI = "WIFI";
    public static final String NET_TYPE_MOBILE = "MOBILE";
    public static final String NET_TYPE_NO_NETWORK = "no_network";

    private Context mContext = null;

    public NetworkUtils(Context pContext) {
        this.mContext = pContext;
    }

    public static final String IP_DEFAULT = "0.0.0.0";

    public static boolean isConnectInternet(final Context pContext) {
        final ConnectivityManager conManager = (ConnectivityManager) pContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = conManager.getActiveNetworkInfo();

        if (networkInfo != null) {
            return networkInfo.isAvailable();
        }

        return false;
    }

    public static boolean isConnectWifi(final Context pContext) {
        ConnectivityManager mConnectivity = (ConnectivityManager) pContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = mConnectivity.getActiveNetworkInfo();
        //判断网络连接类型,只有在3G或wifi里进行一些数据更新。
        int netType = -1;
        if (info != null) {
            netType = info.getType();
        }
        if (netType == ConnectivityManager.TYPE_WIFI) {
            return info.isConnected();
        } else {
            return false;
        }
    }

    public static String getNetTypeName(final int pNetType) {
        switch (pNetType) {
            case 0:
                return "unknown";
            case 1:
                return "GPRS";
            case 2:
                return "EDGE";
            case 3:
                return "UMTS";
            case 4:
                return "CDMA: Either IS95A or IS95B";
            case 5:
                return "EVDO revision 0";
            case 6:
                return "EVDO revision A";
            case 7:
                return "1xRTT";
            case 8:
                return "HSDPA";
            case 9:
                return "HSUPA";
            case 10:
                return "HSPA";
            case 11:
                return "iDen";
            case 12:
                return "EVDO revision B";
            case 13:
                return "LTE";
            case 14:
                return "eHRPD";
            case 15:
                return "HSPA+";
            default:
                return "unknown";
        }
    }

    public static String getIPAddress() {
        try {
            final Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();

            while (networkInterfaceEnumeration.hasMoreElements()) {
                final NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();

                final Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses();

                while (inetAddressEnumeration.hasMoreElements()) {
                    final InetAddress inetAddress = inetAddressEnumeration.nextElement();

                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }

            return NetworkUtils.IP_DEFAULT;
        } catch (final SocketException e) {
            return NetworkUtils.IP_DEFAULT;
        }
    }

    public String getConnTypeName() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return NET_TYPE_NO_NETWORK;
        } else {
            return networkInfo.getTypeName();
        }
    }
}

8、屏幕相关的工具类

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

/**
 * Created by guojingbu on 2017/12/16.
 */

public class ScreenUtils {

    private ScreenUtils() {

    }

    /**
     * 获得屏幕高度
     *
     * @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;

    }

    /**
     * 用于获取状态栏的高度。 使用Resource对象获取(推荐这种方式)
     *
     * @return 返回状态栏高度的像素值。
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}

9、单位转换工具类 DensityUtils

import android.content.Context;
import android.util.TypedValue;
/**
 *  常用单位转换的辅助类
 * Created by guojingbu on 2017/12/16.
 */
    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 (int) 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 (int) 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);
        }
    }

10、时间工具类DateUtils

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by guojingbu on 2017/12/16.
 */

public class DateUtils {

    /** The Constant timestampDateFormatter. */
    public static final SimpleDateFormat timestampDateFormatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());

    /** The Constant birthdayFormatter. */
    public static final SimpleDateFormat birthdayFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    /**
     * Gets the timestamp.
     *
     * @return the timestamp
     */
    public static String getTimestamp() {
        return timestampDateFormatter.format(new Date());
    }

    /**
     * Checks if is night.
     *
     * @return true, if is night
     */
    public static boolean isNight() {
        return Calendar.getInstance().get(Calendar.HOUR_OF_DAY) > 17;
    }

    /**
     * Gets the hour and minute.
     *
     * @param timeStirng the time stirng
     * @return the hour and minute
     */
    public static String getHourAndMinute(String timeStirng) {
        if (timeStirng != null) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return new SimpleDateFormat("HH:mm").format(dateFormat.parse(timeStirng));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public static String getYearAndDate(String timeStirng) {
        if (timeStirng != null) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return new SimpleDateFormat("yyyy-MM-dd").format(dateFormat.parse(timeStirng));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    /**
     * Gets the date and week.
     *
     * @param date the date
     * @return the date and week
     */
    public static String getDateAndWeek(Date date) {
        if (date == null) {
            return "";
        }
        return new SimpleDateFormat("yyyy年MM月dd日 EEEE", Locale.CHINA).format(date);
    }

    /**
     * Gets the date and week.
     *
     * @param timeStirng the time stirng
     * @return the date and week
     */
    public static String getDateAndWeek(String timeStirng) {
        if (timeStirng != null) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return new SimpleDateFormat("yyyy年MM月dd日 EEEE", Locale.CHINA).format(dateFormat.parse(timeStirng));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public static String getDateNow(){
        SimpleDateFormat    sDateFormat    =   new    SimpleDateFormat("yyyy-MM-dd");
        String    date    =    sDateFormat.format(new java.util.Date());
        return date;
    }

    public static String dateAndWeek() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return new SimpleDateFormat("MM/dd EEEE", Locale.CHINA).format(new java.util.Date());
    }

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

11、MD5校验工具类MD5Chek

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * The Class MD5Check.
 */
public class MD5Check {

    /**
     * Bytes to hex.
     *
     * @param bytes the bytes
     * @return the string
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer md5str = new StringBuffer();
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];
            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString().toUpperCase();
    }

    /**
     * Bytes to m d5.
     *
     * @param input the input
     * @return the string
     */
    public static String bytesToMD5(byte[] input) {
        String md5str = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buff = md.digest(input);
            md5str = bytesToHex(buff);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5str;
    }

    /**
     * Str to m d5.
     *
     * @param str the str
     * @return the string
     */
    public static String strToMD5(String str) {
        byte[] input = str.getBytes();
        return bytesToMD5(input);
    }

    /**
     * File to m d5.
     *
     * @param file the file
     * @return the string
     */
    public static String fileToMD5(File file) {
        if (file == null) {
            return null;
        }
        if (file.exists() == false) {
            return null;
        }
        if (file.isFile() == false) {
            return null;
        }
        FileInputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            fis = new FileInputStream(file);
            byte[] buff = new byte[1024];
            int len = 0;
            while (true) {
                len = fis.read(buff, 0, buff.length);
                if (len == -1) {
                    break;
                }
                md.update(buff, 0, len);
            }
            fis.close();
            return bytesToHex(md.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString().toUpperCase();
    }

}

12、文件操作工具类FileUtils

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import android.content.Context;
import android.os.Environment;

import com.yesway.yeswaysdk.YeswaySDK;

/**
 * 
 * 文件操作
 * 
 * @author yesway
 * 
 */
public class FileUtils {

    public static final String ROOT_DIR = "Android/data/";
    public static final String DOWNLOAD_DIR = "download";
    public static final String CACHE_DIR = "cache";
    public static final String ICON_DIR = "icon";

    /** 判断SD卡是否挂载 */
    public static boolean isSDCardAvailable() {
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            return true;
        } else {
            return false;
        }
    }

    /** 获取下载目录 */
    public static String getDownloadDir() {
        return getDir(DOWNLOAD_DIR);
    }

    /** 获取缓存目录 */
    public static String getCacheDir() {
        return getDir(CACHE_DIR);
    }

    /** 获取icon目录 */
    public static String getIconDir() {
        return getDir(ICON_DIR);
    }

    /**
     * 
     * 获取应用目录,当SD卡存在时,获取SD卡上的目录, 当SD卡不存在时,获取应用的cache目录
     * 
     * @param name
     * @return
     */
    public static String getDir(String name) {
        StringBuilder sb = new StringBuilder();
        if (isSDCardAvailable()) {
            sb.append(getExternalStoragePath());
        } else {
            sb.append(getCachePath(YeswaySDK.getContext()));
        }
        sb.append(name);
        sb.append(File.separator);
        String path = sb.toString();
        if (createDirs(path)) {
            return path;
        } else {
            return null;
        }
    }

    /**
     * 
     * 获取SD下的应用目录
     * 
     * @return
     */
    public static String getExternalStoragePath() {
        StringBuilder sb = new StringBuilder();
        sb.append(Environment.getExternalStorageDirectory().getAbsolutePath());
        sb.append(File.separator);
        sb.append(ROOT_DIR);
        sb.append(File.separator);
        return sb.toString();
    }

    /**
     * 
     * 获取应用的cache目录
     * 
     * @param context
     * @return
     */
    public static String getCachePath(Context context) {
        File f = context.getCacheDir();
        if (null == f) {
            return null;
        } else {
            return f.getAbsolutePath() + "/";
        }
    }

    /**
     * 
     * 创建文件夹
     * 
     * @param dirPath
     * @return
     */
    public static boolean createDirs(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists() || !file.isDirectory()) {
            return file.mkdirs();
        }
        return true;
    }

    /**
     * 
     * 复制文件,可以选择是否删除源文件
     * 
     * @param srcPath
     * @param destPath
     * @param deleteSrc
     * @return
     */
    public static boolean copyFile(String srcPath, String destPath,
            boolean deleteSrc) {
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);
        return copyFile(srcFile, destFile, deleteSrc);
    }

    /**
     * 
     * 复制文件,可以选择是否删除源文件
     * 
     * @param srcFile
     * @param destFile
     * @param deleteSrc
     * @return
     */
    @SuppressWarnings("resource")
    public static boolean copyFile(File srcFile, File destFile,
            boolean deleteSrc) {
        if (!srcFile.exists() || !srcFile.isFile()) {
            return false;
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            int i = -1;
            while ((i = in.read(buffer)) > 0) {
                out.write(buffer, 0, i);
                out.flush();
            }
            if (deleteSrc) {
                srcFile.delete();
            }
        } catch (Exception e) {

            return false;
        } finally {
        }
        return true;
    }

    /**
     * 
     * 判断文件是否可写
     * 
     * @param path
     * @return
     */
    public static boolean isWriteable(String path) {
        try {
            if (StringUtils.isEmpty(path)) {
                return false;
            }
            File f = new File(path);
            return f.exists() && f.canWrite();
        } catch (Exception e) {

            return false;
        }
    }

    /**
     * 修改文件的权限,例如"777"等
     * 
     * @param path
     * @param mode
     */
    public static void chmod(String path, String mode) {
        try {
            String command = "chmod " + mode + " " + path;
            Runtime runtime = Runtime.getRuntime();
            runtime.exec(command);
        } catch (Exception e) {

        }
    }

    /**
     * 把数据写入文件
     * 
     * @param is
     *            数据流
     * @param path
     *            文件路径
     * @param recreate
     *            如果文件存在,是否需要删除重建
     * @return 是否写入成功
     */
    @SuppressWarnings("resource")
    public static boolean writeFile(InputStream is, String path,
            boolean recreate) {
        boolean res = false;
        File f = new File(path);
        FileOutputStream fos = null;
        try {
            if (recreate && f.exists()) {
                f.delete();
            }
            if (!f.exists() && null != is) {
                File parentFile = new File(f.getParent());
                parentFile.mkdirs();
                int count = -1;
                byte[] buffer = new byte[1024];
                fos = new FileOutputStream(f);
                while ((count = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, count);
                }
                res = true;
            }
        } catch (Exception e) {

        } finally {
        }
        return res;
    }

    /**
     * 把字符串数据写入文件
     * 
     * @param content
     *            需要写入的字符串
     * @param path
     *            文件路径名称
     * @param append
     *            是否以添加的模式写入
     * @return 是否写入成功
     */
    @SuppressWarnings("resource")
    public static boolean writeFile(byte[] content, String path, boolean append) {
        boolean res = false;
        File f = new File(path);
        RandomAccessFile raf = null;
        try {
            if (f.exists()) {
                if (!append) {
                    f.delete();
                    f.createNewFile();
                }
            } else {
                f.createNewFile();
            }
            if (f.canWrite()) {
                raf = new RandomAccessFile(f, "rw");
                raf.seek(raf.length());
                raf.write(content);
                res = true;
            }
        } catch (Exception e) {

        } finally {

        }
        return res;
    }

    /**
     * 把字符串数据写入文件
     * 
     * @param content
     *            需要写入的字符串
     * @param path
     *            文件路径名称
     * @param append
     *            是否以添加的模式写入
     * @return 是否写入成功
     */
    public static boolean writeFile(String content, String path, boolean append) {
        return writeFile(content.getBytes(), path, append);
    }

    /**
     * 把键值对写入文件
     * 
     * @param filePath
     *            文件路径
     * @param key
     *            键
     * @param value
     *            值
     * @param comment
     *            该键值对的注释
     */
    public static void writeProperties(String filePath, String key,
            String value, String comment) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(filePath)) {
            return;
        }
        FileInputStream fis = null;
        FileOutputStream fos = null;
        File f = new File(filePath);
        try {
            if (!f.exists() || !f.isFile()) {
                f.createNewFile();
            }
            fis = new FileInputStream(f);
            Properties p = new Properties();
            p.load(fis);// 先读取文件,再把键值对追加到后面
            p.setProperty(key, value);
            fos = new FileOutputStream(f);
            p.store(fos, comment);
        } catch (Exception e) {

        } finally {
            close(fis);
            close(fos);
        }
    }

    /**
     * 
     * 关闭流
     * 
     * @param io
     * @return
     */
    public static boolean close(Closeable io) {
        if (io != null) {
            try {
                io.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 
     * 根据值读取
     * 
     * @param filePath
     * @param key
     * @param defaultValue
     * @return
     */
    public static String readProperties(String filePath, String key,
            String defaultValue) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(filePath)) {
            return null;
        }
        String value = null;
        FileInputStream fis = null;
        File f = new File(filePath);
        try {
            if (!f.exists() || !f.isFile()) {
                f.createNewFile();
            }
            fis = new FileInputStream(f);
            Properties p = new Properties();
            p.load(fis);
            value = p.getProperty(key, defaultValue);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return value;
    }

    /**
     * 
     * 把字符串键值对的map写入文件
     * 
     * @param filePath
     * @param map
     * @param append
     * @param comment
     */
    public static void writeMap(String filePath, Map<String, String> map,
            boolean append, String comment) {
        if (map == null || map.size() == 0 || StringUtils.isEmpty(filePath)) {
            return;
        }
        FileInputStream fis = null;
        FileOutputStream fos = null;
        File f = new File(filePath);
        try {
            if (!f.exists() || !f.isFile()) {
                f.createNewFile();
            }
            Properties p = new Properties();
            if (append) {
                fis = new FileInputStream(f);
                p.load(fis);// 先读取文件,再把键值对追加到后面
            }
            p.putAll(map);
            fos = new FileOutputStream(f);
            p.store(fos, comment);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(fis);
            close(fos);
        }
    }

    /**
     * 
     * 把字符串键值对的文件读入map
     * 
     * @param filePath
     * @param defaultValue
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map<String, String> readMap(String filePath,
            String defaultValue) {
        if (StringUtils.isEmpty(filePath)) {
            return null;
        }
        Map<String, String> map = null;
        FileInputStream fis = null;
        File f = new File(filePath);
        try {
            if (!f.exists() || !f.isFile()) {
                f.createNewFile();
            }
            fis = new FileInputStream(f);
            Properties p = new Properties();
            p.load(fis);
            // 因为properties继承了map,所以直接通过p来构造一个map
            map = new HashMap<String, String>((Map) p);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(fis);
        }
        return map;
    }

    /**
     * 
     * 改名
     * 
     * @param src
     * @param des
     * @param delete
     * @return
     */
    public static boolean copy(String src, String des, boolean delete) {
        File file = new File(src);
        if (!file.exists()) {
            return false;
        }
        File desFile = new File(des);
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(file);
            out = new FileOutputStream(desFile);
            byte[] buffer = new byte[1024];
            int count = -1;
            while ((count = in.read(buffer)) != -1) {
                out.write(buffer, 0, count);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            close(in);
            close(out);
        }
        if (delete) {
            file.delete();
        }
        return true;
    }

    /**判断文件是否存在*/
    public static boolean FileExists(String path){
          File file = new File(path);
          //判断文件夹是否存在,如果不存在则创建文件夹
          if (file.exists()) {
           return true;
          }
        return false;

    }
}

13、字符串工具类StringUtils

import android.text.TextUtils;

import org.apache.http.protocol.HTTP;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * String类相关操作
 * 
 * @author wangbo
 */
public class StringUtils {

    /**
     * 将字符串用分隔符分割为字符串列表
     * 
     * @param string
     *            字符串
     * @param delimiter
     *            分隔符
     * @return 分割后的字符串数组.
     */
    public static List<String> splitToStringList(String string, String delimiter) {
        List<String> stringList = new ArrayList<String>();
        if (!TextUtils.isEmpty(string)) {
            int length = string.length();
            int pos = 0;

            do {
                int end = string.indexOf(delimiter, pos);
                if (end == -1) {
                    end = length;
                }
                stringList.add(string.substring(pos, end));
                pos = end + 1;
            } while (pos < length);
        }
        return stringList;
    }

    /**
     * InputSteam 转换到 String,会把输入流关闭
     * 
     * @param inputStream
     *            输入流
     * @return String 如果有异常则返回null
     */
    public static String stringFromInputStream(InputStream inputStream) {
        try {
            byte[] readBuffer = new byte[ConstantUtils.CACHE_SIZE];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while (true) {
                int readLen = inputStream.read(readBuffer, 0, ConstantUtils.CACHE_SIZE);
                if (readLen <= 0) {
                    break;
                }

                byteArrayOutputStream.write(readBuffer, 0, readLen);
            }

            return byteArrayOutputStream.toString(HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 判断是否为空串
     * 
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str == null || str.equals("")) {
            return true;
        } else {
            return false;
        }
    }

以上就是我总结的工具类,大家在看或者用的时候发现有什么问题的时候,如果大家有可以的建议,欢迎大家留言提出我们可以不断的改进这些类。

猜你喜欢

转载自blog.csdn.net/guojingbu/article/details/78822209