Android---工具类
来源:互联网 发布:mt7620a 修改源码 编辑:程序博客网 时间:2024/06/06 01:45
1、日志工具类
import android.util.Log; /** * Log统一管理类 * */ public class L { private L() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 private static final String TAG = "way"; // 下面四个是默认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); } }
2、Toast统一管理类
import android.content.Context; import android.widget.Toast; /** * Toast统一管理类 * */ public class T { private T() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } public static boolean isShow = true; /** * 短时间显示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(); } }
3、SharedPreferences封装类SPUtils
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import android.content.Context; import android.content.SharedPreferences; public class 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(); } } }
4、单位转换类 DensityUtils
import android.content.Context; import android.util.TypedValue; /** * 常用单位转换的辅助类 * * * */ public class DensityUtils { private DensityUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * dp转px * * @param context * @param val * @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 val * @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 fontScale * @param pxVal * @return */ public static float px2sp(Context context, float pxVal) { return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); } }
5、SD卡相关辅助类 SDCardUtils
import java.io.File; import android.os.Environment; import android.os.StatFs; /** * SD卡相关的辅助类 */ public class SDCardUtils { private SDCardUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * 判断SDCard是否可用 * * @return */ public static boolean isSDCardEnable() { return Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED); } /** * 获取SD卡路径 * * @return */ public static String getSDCardPath() { return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator; } /** * 获取SD卡的剩余容量 单位byte * * @return */ public static long getSDCardAllSize() { if (isSDCardEnable()) { StatFs stat = new StatFs(getSDCardPath()); // 获取空闲的数据块的数量 long availableBlocks = (long) stat.getAvailableBlocks() - 4; // 获取单个数据块的大小(byte) long freeBlocks = stat.getAvailableBlocks(); return freeBlocks * availableBlocks; } return 0; } /** * 获取指定路径所在空间的剩余可用容量字节数,单位byte * * @param filePath * @return 容量字节 SDCard可用空间,内部存储可用空间 */ public static long getFreeBytes(String filePath) { // 如果是sd卡的下的路径,则获取sd卡可用容量 if (filePath.startsWith(getSDCardPath())) { filePath = getSDCardPath(); } else {// 如果是内部存储的路径,则获取内存存储的可用容量 filePath = Environment.getDataDirectory().getAbsolutePath(); } StatFs stat = new StatFs(filePath); long availableBlocks = (long) stat.getAvailableBlocks() - 4; return stat.getBlockSize() * availableBlocks; } /** * 获取系统存储路径 * * @return */ public static String getRootDirectoryPath() { return Environment.getRootDirectory().getAbsolutePath(); } }
6、屏幕相关辅助类 ScreenUtils
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; /** * 获得屏幕相关的辅助类 */ public class ScreenUtils { private ScreenUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * 获得屏幕高度 * * @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; } }
7、App相关辅助类
import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; /** * 跟App相关的辅助类 * * * */ public class AppUtils { private AppUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * 获取应用程序名称 */ public static String getAppName(Context context) { try { PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0); int labelRes = packageInfo.applicationInfo.labelRes; return context.getResources().getString(labelRes); } catch (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 (NameNotFoundException e) { e.printStackTrace(); } return null; } }
8、软键盘相关辅助类KeyBoardUtils
import android.content.Context; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; /** * 打开或关闭软键盘 * * @author zhy * */ public class KeyBoardUtils { /** * 打卡软键盘 * * @param mEditText * 输入框 * @param mContext * 上下文 */ public static void openKeybord(EditText mEditText, Context mContext) { InputMethodManager imm = (InputMethodManager) mContext .getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); } /** * 关闭软键盘 * * @param mEditText * 输入框 * @param mContext * 上下文 */ public static void closeKeybord(EditText mEditText, Context mContext) { InputMethodManager imm = (InputMethodManager) mContext .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); } }
9、MD5工具类
public final static String MD5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { byte[] btInput = s.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } }
10、异常捕捉类
/** * UncaughtException处理类,当程序发生Uncaught异常的时候,由该类来接管程序,并记录发送错误报告. 需要在Application中注册,为了要在程序启动器就监控整个程序。 */public class CrashHandler implements UncaughtExceptionHandler { /** TAG */ public static final String TAG = "CrashHandler"; /** 系统默认的UncaughtException处理类 */ private Thread.UncaughtExceptionHandler mDefaultHandler; /** CrashHandler实例 */ private static CrashHandler mCrashHandler; /** 程序的Context对象 */ private Context mContext; /** 用来存储设备信息和异常信息 */ private Map<String, String> infos = new HashMap<String, String>(); /** 用于格式化日期,作为日志文件名的一部分 */ private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); /** * 私有构造函数 */ private CrashHandler() { } /** * 获取CrashHandler实例 ,单例模式 * * @return * @since V1.0 */ public static CrashHandler getInstance() { if (mCrashHandler == null) mCrashHandler = new CrashHandler(); return mCrashHandler; } /** * 初始化 * * @param context * @since V1.0 */ public void init(Context context) { mContext = context; // 获取系统默认的UncaughtException处理器 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); // 设置该CrashHandler为程序的默认处理器 Thread.setDefaultUncaughtExceptionHandler(this); } /** * 当UncaughtException发生时会转入该函数来处理 */ @Override public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { // 如果用户没有处理则让系统默认的异常处理器来处理 mDefaultHandler.uncaughtException(thread, ex); } else { try { Thread.sleep(3000); } catch (InterruptedException e) { CLog.e(TAG, "uncaughtException() InterruptedException:" + e); } // 退出程序 android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1); } } /** * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. * * @param ex * @return true:如果处理了该异常信息;否则返回false. * @since V1.0 */ private boolean handleException(Throwable ex) { if (ex == null) { return false; } // 收集设备参数信息 collectDeviceInfo(mContext); // 使用Toast来显示异常信息 new Thread() { @Override public void run() { Looper.prepare(); Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT).show(); Looper.loop(); } }.start(); // 保存日志文件 saveCatchInfo2File(ex); return true; } /** * 收集设备参数信息 * * @param ctx * @since V1.0 */ public void collectDeviceInfo(Context ctx) { try { PackageManager pm = ctx.getPackageManager(); PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES); if (pi != null) { String versionName = pi.versionName == null ? "null" : pi.versionName; String versionCode = pi.versionCode + ""; infos.put("versionName", versionName); infos.put("versionCode", versionCode); } } catch (NameNotFoundException e) { CLog.e(TAG, "collectDeviceInfo() an error occured when collect package info NameNotFoundException:", e); } Field[] fields = Build.class.getDeclaredFields(); for (Field field : fields) { try { field.setAccessible(true); infos.put(field.getName(), field.get(null).toString()); CLog.d(TAG, field.getName() + " : " + field.get(null)); } catch (Exception e) { CLog.e(TAG, "collectDeviceInfo() an error occured when collect crash info Exception:", e); } } } /** * 保存错误信息到文件中 * * @param ex * @return 返回文件名称,便于将文件传送到服务器 */ private String saveCatchInfo2File(Throwable ex) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : infos.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); sb.append(key + "=" + value + "\n"); } Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } printWriter.close(); String result = writer.toString(); sb.append(result); try { long timestamp = System.currentTimeMillis(); String time = formatter.format(new Date()); String fileName = "crash-" + time + "-" + timestamp + ".log"; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String path = FilePathUtil.getiVMSDirPath() + "/crash/"; File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } FileOutputStream fos = new FileOutputStream(path + fileName); fos.write(sb.toString().getBytes()); // 发送给开发人员 sendCrashLog2PM(path + fileName); fos.close(); } return fileName; } catch (Exception e) { CLog.e(TAG, "saveCatchInfo2File() an error occured while writing file... Exception:", e); } return null; } /** * 将捕获的导致崩溃的错误信息发送给开发人员 目前只将log日志保存在sdcard 和输出到LogCat中,并未发送给后台。 * * @param fileName * @since V1.0 */ private void sendCrashLog2PM(String fileName) { if (!new File(fileName).exists()) { CLog.e(TAG, "sendCrashLog2PM() 日志文件不存在"); return; } FileInputStream fis = null; BufferedReader reader = null; String s = null; try { fis = new FileInputStream(fileName); reader = new BufferedReader(new InputStreamReader(fis, "GBK")); while (true) { s = reader.readLine(); if (s == null) break; // 由于目前尚未确定以何种方式发送,所以先打出log日志。 CLog.e(TAG, s); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭流 try { reader.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } }}
Android快速开发系列 10个常用工具类 - Hongyang - 博客频道 - CSDN.NET
Android 常见工具类封装 - cryAllen - 博客园
Android常用工具类 - fangzhibin4712的专栏 - 博客频道 - CSDN.NET
android-common/src/cn/trinea/android/common/util at master · Trinea/android-common
Android intent跳转工具类 - lovoo的博客 - 博客频道 - CSDN.NET
http://blog.csdn.net/lovoo/article/details/51379268
0 0
- 【Android工具】时间工具类
- [Android工具类]Android File工具类
- Android Bitmap 工具类
- Android:HttpClient工具类
- android图片下载工具类
- android日志工具类
- android ---- ImageUtil工具类
- Android Bitmap 工具类
- android 图片工具类
- Android 工具类
- android缓存工具类
- android截图工具类
- Android工具类
- Android工具类-SharedPrefsUtil
- Android 日志工具类
- Android ShareProference工具类
- android工具类归纳
- android 工具类
- 计算文件夹下文件行总数的一个小demo
- 减少mysql主从数据同步延迟问题的详解
- Sequel Pro连接本地mamp的mysql
- 九、退化维度 本节讨论一种称为退化维度的技术。该技术减少维度的数量,简化维度数据仓库模式。简单的模式比复杂的更容易理解,也有更好的查询性能。当一个维度没有数据仓库需要的任何数据时就可
- 如何给TextView 中通过drawable放图片 修改图片大小
- Android---工具类
- 分布式集群
- 【Get深一度】Win10 Setup will now quit. 系统管理员失去安装和移除软件的权利(求助帖)
- 通达OA,js控制复选框checkbox,获取复选框的值
- 51Nod-1154-回文串划分
- 表单的值
- Redis笔记
- 万能幻灯片插件
- ORA-20000: index "FCSASUSER"."IDX_DN_TREE_ID" or partition of such index is in unusable state