Android 常用工具类

4,363 阅读4分钟

AppUtil

package utils; 
 
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
 
/** 
 * app相关辅助类 
 */ 
public class AppUtil { 
    private AppUtil() { 
        /* cannot be instantiated*/ 
        throw new UnsupportedOperationException("cannot be instantiated");
    } 
 
    /** 
     * 获取应用程序名称 
     * 
     * @param context 
     * @return 
     */ 
    public static String getAppName(Context context) {
 
        PackageManager packageManager = context.getPackageManager();
        try { 
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } 
        return null; 
    } 
 
    /** 
     * 获取应用程序版本名称信息 
     * 
     * @param context 
     * @return 当前应用的版本名称 
     */ 
    public static String getVersionName(Context context) {
        try { 
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } 
        return null; 
    } 
 
    /** 
     * 获取应用程序的版本Code信息 
     * @param context 
     * @return 版本code 
     */ 
    public static int getVersionCode(Context context) {
        try { 
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } 
        return 0; 
    } 
}

FileUtil


package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * 文件操作工具类
 */
public class FileUtil {
    /**
     * 在指定的位置创建指定的文件
     *
     * @param filePath 完整的文件路径
     * @param mkdir 是否创建相关的文件夹
     * @throws Exception
     */
    public static void mkFile(String filePath, boolean mkdir) throws Exception {
        File file = new File(filePath);
        file.getParentFile().mkdirs();
        file.createNewFile();
        file = null;
    }

    /**
     * 在指定的位置创建文件夹
     *
     * @param dirPath 文件夹路径
     * @return 若创建成功,则返回True;反之,则返回False
     */
    public static boolean mkDir(String dirPath) {
        return new File(dirPath).mkdirs();
    }

    /**
     * 删除指定的文件
     *
     * @param filePath 文件路径
     *
     * @return 若删除成功,则返回True;反之,则返回False
     *
     */
    public static boolean delFile(String filePath) {
        return new File(filePath).delete();
    }

    /**
     * 删除指定的文件夹
     *
     * @param dirPath 文件夹路径
     * @param delFile 文件夹中是否包含文件
     * @return 若删除成功,则返回True;反之,则返回False
     *
     */
    public static boolean delDir(String dirPath, boolean delFile) {
        if (delFile) {
            File file = new File(dirPath);
            if (file.isFile()) {
                return file.delete();
            } else if (file.isDirectory()) {
                if (file.listFiles().length == 0) {
                    return file.delete();
                } else {
                    int zfiles = file.listFiles().length;
                    File[] delfile = file.listFiles();
                    for (int i = 0; i < zfiles; i++) {
                        if (delfile[i].isDirectory()) {
                            delDir(delfile[i].getAbsolutePath(), true);
                        }
                        delfile[i].delete();
                    }
                    return file.delete();
                }
            } else {
                return false;
            }
        } else {
            return new File(dirPath).delete();
        }
    }

    /**
     * 复制文件/文件夹 若要进行文件夹复制,请勿将目标文件夹置于源文件夹中
     * @param source 源文件(夹)
     * @param target 目标文件(夹)
     * @param isFolder 若进行文件夹复制,则为True;反之为False
     * @throws Exception
     */
    public static void copy(String source, String target, boolean isFolder)
            throws Exception {
        if (isFolder) {
            (new File(target)).mkdirs();
            File a = new File(source);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (source.endsWith(File.separator)) {
                    temp = new File(source + file[i]);
                } else {
                    temp = new File(source + File.separator + file[i]);
                }
                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(target + "/" + (temp.getName()).toString());
                    byte[] b = new byte[1024];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {
                    copy(source + "/" + file[i], target + "/" + file[i], true);
                }
            }
        } else {
            int byteread = 0;
            File oldfile = new File(source);
            if (oldfile.exists()) {
                InputStream inStream = new FileInputStream(source);
                File file = new File(target);
                file.getParentFile().mkdirs();
                file.createNewFile();
                FileOutputStream fs = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
            }
        }
    }

    /**
     * 移动指定的文件(夹)到目标文件(夹)
     * @param source 源文件(夹)
     * @param target 目标文件(夹)
     * @param isFolder 若为文件夹,则为True;反之为False
     * @return
     * @throws Exception
     */
    public static boolean move(String source, String target, boolean isFolder)
            throws Exception {
        copy(source, target, isFolder);
        if (isFolder) {
            return delDir(source, true);
        } else {
            return delFile(source);
        }
    }
}

LogUtil


package utils; 
 
import android.util.Log;
 
/** 
 * Log统一管理类 
 */ 
public class LogUtil { 
 
    private LogUtil() { 
        /* cannot be instantiated */ 
        throw new UnsupportedOperationException("cannot be instantiated");
    } 
 
    // 是否需要打印bug,可以在application的onCreate函数里面初始化 
    public static boolean isDebug = true;
    private static final String TAG = "LogUtil";
 
    // 下面四个是默认tag的函数 
    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);
    } 
 
    // 下面是传入自定义tag的函数 
    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.i(tag, msg);
    } 
 
    public static void e(String tag, String msg)
    { 
        if (isDebug)
            Log.i(tag, msg);
    } 
 
    public static void v(String tag, String msg)
    { 
        if (isDebug)
            Log.i(tag, msg);
    } 
}

SPUtil


package utils; 
 
import android.content.Context;
import android.content.SharedPreferences;
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
 
/** 
 * SharedPreferences统一管理类 
 */ 
public class SPUtil { 
    /** 
     * 保存在手机里面的文件名 
     */ 
    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 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();
        } 
    } 
}

ToastUtil


package utils; 
 
import android.content.Context;
import android.widget.Toast;
 
/** 
 * Toast统一管理类 
 */ 
public class ToastUtil { 
 
    public static boolean isShow = true;
 
    /*cannot be instantiated*/ 
    private ToastUtil(){ 
        throw new UnsupportedOperationException("cannot be instantiated");
    } 
 
    /** 
     * 短时间显示Toast 
     * 
     * @param context 
     * @param message 
     */ 
    public static void showShort(Context context, CharSequence message) {
        if (isShow)
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    } 
 
    /** 
     * 短时间显示Toast 
     * 
     * @param context 
     * @param message 
     */ 
    public static void showShort(Context context, int message) {
        if (isShow)
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    } 
 
    /** 
     * 长时间显示Toast 
     * 
     * @param context 
     * @param message 
     */ 
    public static void showLong(Context context, CharSequence message) {
        if (isShow)
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    } 
 
    /** 
     * 长时间显示Toast 
     * 
     * @param context 
     * @param message 
     */ 
    public static void showLong(Context context, int message) {
        if (isShow)
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    } 
 
    /** 
     * 自定义显示Toast时间 
     * 
     * @param context 
     * @param message 
     * @param duration 
     */ 
    public static void show(Context context, CharSequence message, int duration) {
        if (isShow)
            Toast.makeText(context, message, duration).show();
    } 
 
    /** 
     * 自定义显示Toast时间 
     * 
     * @param context 
     * @param message 
     * @param duration 
     */ 
    public static void show(Context context, int message, int duration) {
        if (isShow)
            Toast.makeText(context, message, duration).show();
    } 
 
}