Android 工具类大全
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311
1、日志工具类L.java
1 package com.zhy.utils; 2 3 import android.util.Log; 4 5 /** 6 * Log统一管理类 7 * 8 * 9 * 10 */ 11 public class L 12 { 13 14 private L() 15 { 16 /* cannot be instantiated */ 17 throw new UnsupportedOperationException("cannot be instantiated"); 18 } 19 20 public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 21 private static final String TAG = "way"; 22 23 // 下面四个是默认tag的函数 24 public static void i(String msg) 25 { 26 if (isDebug) 27 Log.i(TAG, msg); 28 } 29 30 public static void d(String msg) 31 { 32 if (isDebug) 33 Log.d(TAG, msg); 34 } 35 36 public static void e(String msg) 37 { 38 if (isDebug) 39 Log.e(TAG, msg); 40 } 41 42 public static void v(String msg) 43 { 44 if (isDebug) 45 Log.v(TAG, msg); 46 } 47 48 // 下面是传入自定义tag的函数 49 public static void i(String tag, String msg) 50 { 51 if (isDebug) 52 Log.i(tag, msg); 53 } 54 55 public static void d(String tag, String msg) 56 { 57 if (isDebug) 58 Log.i(tag, msg); 59 } 60 61 public static void e(String tag, String msg) 62 { 63 if (isDebug) 64 Log.i(tag, msg); 65 } 66 67 public static void v(String tag, String msg) 68 { 69 if (isDebug) 70 Log.i(tag, msg); 71 } 72 }
网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到SDCard上的,不过我是从来没记录过,所以引入个最简单的,大家可以进行评价是否需要扩充~~
2、Toast统一管理类
1 package com.zhy.utils; 2 3 import android.content.Context; 4 import android.widget.Toast; 5 6 /** 7 * Toast统一管理类 8 * 9 */ 10 public class T 11 { 12 13 private T() 14 { 15 /* cannot be instantiated */ 16 throw new UnsupportedOperationException("cannot be instantiated"); 17 } 18 19 public static boolean isShow = true; 20 21 /** 22 * 短时间显示Toast 23 * 24 * @param context 25 * @param message 26 */ 27 public static void showShort(Context context, CharSequence message) 28 { 29 if (isShow) 30 Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); 31 } 32 33 /** 34 * 短时间显示Toast 35 * 36 * @param context 37 * @param message 38 */ 39 public static void showShort(Context context, int message) 40 { 41 if (isShow) 42 Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); 43 } 44 45 /** 46 * 长时间显示Toast 47 * 48 * @param context 49 * @param message 50 */ 51 public static void showLong(Context context, CharSequence message) 52 { 53 if (isShow) 54 Toast.makeText(context, message, Toast.LENGTH_LONG).show(); 55 } 56 57 /** 58 * 长时间显示Toast 59 * 60 * @param context 61 * @param message 62 */ 63 public static void showLong(Context context, int message) 64 { 65 if (isShow) 66 Toast.makeText(context, message, Toast.LENGTH_LONG).show(); 67 } 68 69 /** 70 * 自定义显示Toast时间 71 * 72 * @param context 73 * @param message 74 * @param duration 75 */ 76 public static void show(Context context, CharSequence message, int duration) 77 { 78 if (isShow) 79 Toast.makeText(context, message, duration).show(); 80 } 81 82 /** 83 * 自定义显示Toast时间 84 * 85 * @param context 86 * @param message 87 * @param duration 88 */ 89 public static void show(Context context, int message, int duration) 90 { 91 if (isShow) 92 Toast.makeText(context, message, duration).show(); 93 } 94 95 }
也是非常简单的一个封装,能省则省了~~
3、SharedPreferences封装类SPUtils
1 package com.zhy.utils; 2 3 import java.lang.reflect.InvocationTargetException; 4 import java.lang.reflect.Method; 5 import java.util.Map; 6 7 import android.content.Context; 8 import android.content.SharedPreferences; 9 10 public class SPUtils 11 { 12 /** 13 * 保存在手机里面的文件名 14 */ 15 public static final String FILE_NAME = "share_data"; 16 17 /** 18 * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 19 * 20 * @param context 21 * @param key 22 * @param object 23 */ 24 public static void put(Context context, String key, Object object) 25 { 26 27 SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 28 Context.MODE_PRIVATE); 29 SharedPreferences.Editor editor = sp.edit(); 30 31 if (object instanceof String) 32 { 33 editor.putString(key, (String) object); 34 } else if (object instanceof Integer) 35 { 36 editor.putInt(key, (Integer) object); 37 } else if (object instanceof Boolean) 38 { 39 editor.putBoolean(key, (Boolean) object); 40 } else if (object instanceof Float) 41 { 42 editor.putFloat(key, (Float) object); 43 } else if (object instanceof Long) 44 { 45 editor.putLong(key, (Long) object); 46 } else 47 { 48 editor.putString(key, object.toString()); 49 } 50 51 SharedPreferencesCompat.apply(editor); 52 } 53 54 /** 55 * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 56 * 57 * @param context 58 * @param key 59 * @param defaultObject 60 * @return 61 */ 62 public static Object get(Context context, String key, Object defaultObject) 63 { 64 SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 65 Context.MODE_PRIVATE); 66 67 if (defaultObject instanceof String) 68 { 69 return sp.getString(key, (String) defaultObject); 70 } else if (defaultObject instanceof Integer) 71 { 72 return sp.getInt(key, (Integer) defaultObject); 73 } else if (defaultObject instanceof Boolean) 74 { 75 return sp.getBoolean(key, (Boolean) defaultObject); 76 } else if (defaultObject instanceof Float) 77 { 78 return sp.getFloat(key, (Float) defaultObject); 79 } else if (defaultObject instanceof Long) 80 { 81 return sp.getLong(key, (Long) defaultObject); 82 } 83 84 return null; 85 } 86 87 /** 88 * 移除某个key值已经对应的值 89 * @param context 90 * @param key 91 */ 92 public static void remove(Context context, String key) 93 { 94 SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 95 Context.MODE_PRIVATE); 96 SharedPreferences.Editor editor = sp.edit(); 97 editor.remove(key); 98 SharedPreferencesCompat.apply(editor); 99 } 100 101 /** 102 * 清除所有数据 103 * @param context 104 */ 105 public static void clear(Context context) 106 { 107 SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 108 Context.MODE_PRIVATE); 109 SharedPreferences.Editor editor = sp.edit(); 110 editor.clear(); 111 SharedPreferencesCompat.apply(editor); 112 } 113 114 /** 115 * 查询某个key是否已经存在 116 * @param context 117 * @param key 118 * @return 119 */ 120 public static boolean contains(Context context, String key) 121 { 122 SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 123 Context.MODE_PRIVATE); 124 return sp.contains(key); 125 } 126 127 /** 128 * 返回所有的键值对 129 * 130 * @param context 131 * @return 132 */ 133 public static Map<String, ?> getAll(Context context) 134 { 135 SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 136 Context.MODE_PRIVATE); 137 return sp.getAll(); 138 } 139 140 /** 141 * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 142 * 143 * @author zhy 144 * 145 */ 146 private static class SharedPreferencesCompat 147 { 148 private static final Method sApplyMethod = findApplyMethod(); 149 150 /** 151 * 反射查找apply的方法 152 * 153 * @return 154 */ 155 @SuppressWarnings({ "unchecked", "rawtypes" }) 156 private static Method findApplyMethod() 157 { 158 try 159 { 160 Class clz = SharedPreferences.Editor.class; 161 return clz.getMethod("apply"); 162 } catch (NoSuchMethodException e) 163 { 164 } 165 166 return null; 167 } 168 169 /** 170 * 如果找到则使用apply执行,否则使用commit 171 * 172 * @param editor 173 */ 174 public static void apply(SharedPreferences.Editor editor) 175 { 176 try 177 { 178 if (sApplyMethod != null) 179 { 180 sApplyMethod.invoke(editor); 181 return; 182 } 183 } catch (IllegalArgumentException e) 184 { 185 } catch (IllegalAccessException e) 186 { 187 } catch (InvocationTargetException e) 188 { 189 } 190 editor.commit(); 191 } 192 } 193 194 }
对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;
注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit
首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;
所以我们使用apply进行替代,apply异步的进行写入;
但是apply相当于commit来说是new API呢,为了更好的兼容,我们做了适配;
SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考~~
1 package com.zhy.utils; 2 3 import android.content.Context; 4 import android.util.TypedValue; 5 6 /** 7 * 常用单位转换的辅助类 8 * 9 * 10 * 11 */ 12 public class DensityUtils 13 { 14 private DensityUtils() 15 { 16 /* cannot be instantiated */ 17 throw new UnsupportedOperationException("cannot be instantiated"); 18 } 19 20 /** 21 * dp转px 22 * 23 * @param context 24 * @param val 25 * @return 26 */ 27 public static int dp2px(Context context, float dpVal) 28 { 29 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30 dpVal, context.getResources().getDisplayMetrics()); 31 } 32 33 /** 34 * sp转px 35 * 36 * @param context 37 * @param val 38 * @return 39 */ 40 public static int sp2px(Context context, float spVal) 41 { 42 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 43 spVal, context.getResources().getDisplayMetrics()); 44 } 45 46 /** 47 * px转dp 48 * 49 * @param context 50 * @param pxVal 51 * @return 52 */ 53 public static float px2dp(Context context, float pxVal) 54 { 55 final float scale = context.getResources().getDisplayMetrics().density; 56 return (pxVal / scale); 57 } 58 59 /** 60 * px转sp 61 * 62 * @param fontScale 63 * @param pxVal 64 * @return 65 */ 66 public static float px2sp(Context context, float pxVal) 67 { 68 return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); 69 } 70 71 }
5、SD卡相关辅助类 SDCardUtils
1 package com.zhy.utils; 2 3 import java.io.File; 4 5 import android.os.Environment; 6 import android.os.StatFs; 7 8 /** 9 * SD卡相关的辅助类 10 * 11 * 12 * 13 */ 14 public class SDCardUtils 15 { 16 private SDCardUtils() 17 { 18 /* cannot be instantiated */ 19 throw new UnsupportedOperationException("cannot be instantiated"); 20 } 21 22 /** 23 * 判断SDCard是否可用 24 * 25 * @return 26 */ 27 public static boolean isSDCardEnable() 28 { 29 return Environment.getExternalStorageState().equals( 30 Environment.MEDIA_MOUNTED); 31 32 } 33 34 /** 35 * 获取SD卡路径 36 * 37 * @return 38 */ 39 public static String getSDCardPath() 40 { 41 return Environment.getExternalStorageDirectory().getAbsolutePath() 42 + File.separator; 43 } 44 45 /** 46 * 获取SD卡的剩余容量 单位byte 47 * 48 * @return 49 */ 50 public static long getSDCardAllSize() 51 { 52 if (isSDCardEnable()) 53 { 54 StatFs stat = new StatFs(getSDCardPath()); 55 // 获取空闲的数据块的数量 56 long availableBlocks = (long) stat.getAvailableBlocks() - 4; 57 // 获取单个数据块的大小(byte) 58 long freeBlocks = stat.getAvailableBlocks(); 59 return freeBlocks * availableBlocks; 60 } 61 return 0; 62 } 63 64 /** 65 * 获取指定路径所在空间的剩余可用容量字节数,单位byte 66 * 67 * @param filePath 68 * @return 容量字节 SDCard可用空间,内部存储可用空间 69 */ 70 public static long getFreeBytes(String filePath) 71 { 72 // 如果是sd卡的下的路径,则获取sd卡可用容量 73 if (filePath.startsWith(getSDCardPath())) 74 { 75 filePath = getSDCardPath(); 76 } else 77 {// 如果是内部存储的路径,则获取内存存储的可用容量 78 filePath = Environment.getDataDirectory().getAbsolutePath(); 79 } 80 StatFs stat = new StatFs(filePath); 81 long availableBlocks = (long) stat.getAvailableBlocks() - 4; 82 return stat.getBlockSize() * availableBlocks; 83 } 84 85 /** 86 * 获取系统存储路径 87 * 88 * @return 89 */ 90 public static String getRootDirectoryPath() 91 { 92 return Environment.getRootDirectory().getAbsolutePath(); 93 } 94 95 96 }
6、屏幕相关辅助类 ScreenUtils
1 package com.zhy.utils; 2 3 import android.app.Activity; 4 import android.content.Context; 5 import android.graphics.Bitmap; 6 import android.graphics.Rect; 7 import android.util.DisplayMetrics; 8 import android.view.View; 9 import android.view.WindowManager; 10 11 /** 12 * 获得屏幕相关的辅助类 13 * 14 * 15 * 16 */ 17 public class ScreenUtils 18 { 19 private ScreenUtils() 20 { 21 /* cannot be instantiated */ 22 throw new UnsupportedOperationException("cannot be instantiated"); 23 } 24 25 /** 26 * 获得屏幕高度 27 * 28 * @param context 29 * @return 30 */ 31 public static int getScreenWidth(Context context) 32 { 33 WindowManager wm = (WindowManager) context 34 .getSystemService(Context.WINDOW_SERVICE); 35 DisplayMetrics outMetrics = new DisplayMetrics(); 36 wm.getDefaultDisplay().getMetrics(outMetrics); 37 return outMetrics.widthPixels; 38 } 39 40 /** 41 * 获得屏幕宽度 42 * 43 * @param context 44 * @return 45 */ 46 public static int getScreenHeight(Context context) 47 { 48 WindowManager wm = (WindowManager) context 49 .getSystemService(Context.WINDOW_SERVICE); 50 DisplayMetrics outMetrics = new DisplayMetrics(); 51 wm.getDefaultDisplay().getMetrics(outMetrics); 52 return outMetrics.heightPixels; 53 } 54 55 /** 56 * 获得状态栏的高度 57 * 58 * @param context 59 * @return 60 */ 61 public static int getStatusHeight(Context context) 62 { 63 64 int statusHeight = -1; 65 try 66 { 67 Class<?> clazz = Class.forName("com.android.internal.R$dimen"); 68 Object object = clazz.newInstance(); 69 int height = Integer.parseInt(clazz.getField("status_bar_height") 70 .get(object).toString()); 71 statusHeight = context.getResources().getDimensionPixelSize(height); 72 } catch (Exception e) 73 { 74 e.printStackTrace(); 75 } 76 return statusHeight; 77 } 78 79 /** 80 * 获取当前屏幕截图,包含状态栏 81 * 82 * @param activity 83 * @return 84 */ 85 public static Bitmap snapShotWithStatusBar(Activity activity) 86 { 87 View view = activity.getWindow().getDecorView(); 88 view.setDrawingCacheEnabled(true); 89 view.buildDrawingCache(); 90 Bitmap bmp = view.getDrawingCache(); 91 int width = getScreenWidth(activity); 92 int height = getScreenHeight(activity); 93 Bitmap bp = null; 94 bp = Bitmap.createBitmap(bmp, 0, 0, width, height); 95 view.destroyDrawingCache(); 96 return bp; 97 98 } 99 100 /** 101 * 获取当前屏幕截图,不包含状态栏 102 * 103 * @param activity 104 * @return 105 */ 106 public static Bitmap snapShotWithoutStatusBar(Activity activity) 107 { 108 View view = activity.getWindow().getDecorView(); 109 view.setDrawingCacheEnabled(true); 110 view.buildDrawingCache(); 111 Bitmap bmp = view.getDrawingCache(); 112 Rect frame = new Rect(); 113 activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); 114 int statusBarHeight = frame.top; 115 116 int width = getScreenWidth(activity); 117 int height = getScreenHeight(activity); 118 Bitmap bp = null; 119 bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height 120 - statusBarHeight); 121 view.destroyDrawingCache(); 122 return bp; 123 124 } 125 126 }
7、App相关辅助类
1 package com.zhy.utils; 2 3 import android.content.Context; 4 import android.content.pm.PackageInfo; 5 import android.content.pm.PackageManager; 6 import android.content.pm.PackageManager.NameNotFoundException; 7 8 /** 9 * 跟App相关的辅助类 10 * 11 * 12 * 13 */ 14 public class AppUtils 15 { 16 17 private AppUtils() 18 { 19 /* cannot be instantiated */ 20 throw new UnsupportedOperationException("cannot be instantiated"); 21 22 } 23 24 /** 25 * 获取应用程序名称 26 */ 27 public static String getAppName(Context context) 28 { 29 try 30 { 31 PackageManager packageManager = context.getPackageManager(); 32 PackageInfo packageInfo = packageManager.getPackageInfo( 33 context.getPackageName(), 0); 34 int labelRes = packageInfo.applicationInfo.labelRes; 35 return context.getResources().getString(labelRes); 36 } catch (NameNotFoundException e) 37 { 38 e.printStackTrace(); 39 } 40 return null; 41 } 42 43 /** 44 * [获取应用程序版本名称信息] 45 * 46 * @param context 47 * @return 当前应用的版本名称 48 */ 49 public static String getVersionName(Context context) 50 { 51 try 52 { 53 PackageManager packageManager = context.getPackageManager(); 54 PackageInfo packageInfo = packageManager.getPackageInfo( 55 context.getPackageName(), 0); 56 return packageInfo.versionName; 57 58 } catch (NameNotFoundException e) 59 { 60 e.printStackTrace(); 61 } 62 return null; 63 } 64 65 }
8、软键盘相关辅助类KeyBoardUtils
1 package com.zhy.utils; 2 3 import android.content.Context; 4 import android.view.inputmethod.InputMethodManager; 5 import android.widget.EditText; 6 7 /** 8 * 打开或关闭软键盘 9 * 10 * @author zhy 11 * 12 */ 13 public class KeyBoardUtils 14 { 15 /** 16 * 打卡软键盘 17 * 18 * @param mEditText 19 * 输入框 20 * @param mContext 21 * 上下文 22 */ 23 public static void openKeybord(EditText mEditText, Context mContext) 24 { 25 InputMethodManager imm = (InputMethodManager) mContext 26 .getSystemService(Context.INPUT_METHOD_SERVICE); 27 imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN); 28 imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 29 InputMethodManager.HIDE_IMPLICIT_ONLY); 30 } 31 32 /** 33 * 关闭软键盘 34 * 35 * @param mEditText 36 * 输入框 37 * @param mContext 38 * 上下文 39 */ 40 public static void closeKeybord(EditText mEditText, Context mContext) 41 { 42 InputMethodManager imm = (InputMethodManager) mContext 43 .getSystemService(Context.INPUT_METHOD_SERVICE); 44 45 imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); 46 } 47 }
9、网络相关辅助类 NetUtils
1 package com.zhy.utils; 2 3 import android.app.Activity; 4 import android.content.ComponentName; 5 import android.content.Context; 6 import android.content.Intent; 7 import android.net.ConnectivityManager; 8 import android.net.NetworkInfo; 9 10 /** 11 * 跟网络相关的工具类 12 * 13 * 14 * 15 */ 16 public class NetUtils 17 { 18 private NetUtils() 19 { 20 /* cannot be instantiated */ 21 throw new UnsupportedOperationException("cannot be instantiated"); 22 } 23 24 /** 25 * 判断网络是否连接 26 * 27 * @param context 28 * @return 29 */ 30 public static boolean isConnected(Context context) 31 { 32 33 ConnectivityManager connectivity = (ConnectivityManager) context 34 .getSystemService(Context.CONNECTIVITY_SERVICE); 35 36 if (null != connectivity) 37 { 38 39 NetworkInfo info = connectivity.getActiveNetworkInfo(); 40 if (null != info && info.isConnected()) 41 { 42 if (info.getState() == NetworkInfo.State.CONNECTED) 43 { 44 return true; 45 } 46 } 47 } 48 return false; 49 } 50 51 /** 52 * 判断是否是wifi连接 53 */ 54 public static boolean isWifi(Context context) 55 { 56 ConnectivityManager cm = (ConnectivityManager) context 57 .getSystemService(Context.CONNECTIVITY_SERVICE); 58 59 if (cm == null) 60 return false; 61 return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; 62 63 } 64 65 /** 66 * 打开网络设置界面 67 */ 68 public static void openSetting(Activity activity) 69 { 70 Intent intent = new Intent("/"); 71 ComponentName cm = new ComponentName("com.android.settings", 72 "com.android.settings.WirelessSettings"); 73 intent.setComponent(cm); 74 intent.setAction("android.intent.action.VIEW"); 75 activity.startActivityForResult(intent, 0); 76 } 77 78 }