转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自【张鸿洋的博客】
打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于快速开发~~
在此感谢群里给我发项目中工具类的兄弟/姐妹~
1、日志工具类L.java
 
- package com.zhy.utils;  
 
-   
 
- import android.util.Log;  
 
-   
 
- public class L  
 
- {  
 
-   
 
-     private L()  
 
-     {  
 
-         
 
-         throw new UnsupportedOperationException("cannot be instantiated");  
 
-     }  
 
-   
 
-     public static boolean isDebug = true;
 
-     private static final String TAG = "way";  
 
-   
 
-     
 
-     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.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);  
 
-     }  
 
- }  
 
 
 
网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到SDCard上的,不过我是从来没记录过,所以引入个最简单的,大家可以进行评价是否需要扩充~~
2、Toast统一管理类 
 
- package com.zhy.utils;  
 
-   
 
- import android.content.Context;  
 
- import android.widget.Toast;  
 
-   
 
- public class T  
 
- {  
 
-   
 
-     private T()  
 
-     {  
 
-         
 
-         throw new UnsupportedOperationException("cannot be instantiated");  
 
-     }  
 
-   
 
-     public static boolean isShow = true;  
 
-   
 
-     
 
-     public static void showShort(Context context, CharSequence 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, CharSequence 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();  
 
-     }  
 
-   
 
-     
 
-     public static void show(Context context, CharSequence message, int duration)  
 
-     {  
 
-         if (isShow)  
 
-             Toast.makeText(context, message, duration).show();  
 
-     }  
 
-   
 
-     
 
-     public static void show(Context context, int message, int duration)  
 
-     {  
 
-         if (isShow)  
 
-             Toast.makeText(context, message, duration).show();  
 
-     }  
 
-   
 
- }  
 
 
 
也是非常简单的一个封装,能省则省了~~
3、SharedPreferences封装类SPUtils
 
- package com.zhy.utils;  
 
-   
 
- 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";  
 
-   
 
-     
 
-     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);  
 
-     }  
 
-   
 
-     
 
-     public static Object get(Context context, String key, Object defaultObject)  
 
-     {  
 
-         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
 
-                 Context.MODE_PRIVATE);  
 
-   
 
-         if (defaultObject instanceof String)  
 
-         {  
 
-             return sp.getString(key, (String) defaultObject);  
 
-         } else if (defaultObject instanceof Integer)  
 
-         {  
 
-             return sp.getInt(key, (Integer) defaultObject);  
 
-         } else if (defaultObject instanceof Boolean)  
 
-         {  
 
-             return sp.getBoolean(key, (Boolean) defaultObject);  
 
-         } else if (defaultObject instanceof Float)  
 
-         {  
 
-             return sp.getFloat(key, (Float) defaultObject);  
 
-         } else if (defaultObject instanceof Long)  
 
-         {  
 
-             return sp.getLong(key, (Long) defaultObject);  
 
-         }  
 
-   
 
-         return null;  
 
-     }  
 
-   
 
-     
 
-     public static 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);  
 
-     }  
 
-   
 
-     
 
-     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);  
 
-     }  
 
-   
 
-     
 
-     public static boolean contains(Context context, String key)  
 
-     {  
 
-         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
 
-                 Context.MODE_PRIVATE);  
 
-         return sp.contains(key);  
 
-     }  
 
-   
 
-     
 
-     public static Map<String, ?> getAll(Context context)  
 
-     {  
 
-         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
 
-                 Context.MODE_PRIVATE);  
 
-         return sp.getAll();  
 
-     }  
 
-   
 
-     
 
-     private static class SharedPreferencesCompat  
 
-     {  
 
-         private static final Method sApplyMethod = findApplyMethod();  
 
-   
 
-         
 
-         @SuppressWarnings({ "unchecked", "rawtypes" })  
 
-         private static Method findApplyMethod()  
 
-         {  
 
-             try  
 
-             {  
 
-                 Class clz = SharedPreferences.Editor.class;  
 
-                 return clz.getMethod("apply");  
 
-             } catch (NoSuchMethodException e)  
 
-             {  
 
-             }  
 
-   
 
-             return null;  
 
-         }  
 
-   
 
-         
 
-         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();  
 
-         }  
 
-     }  
 
-   
 
- }  
 
 
对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;
 
注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit
首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;
所以我们使用apply进行替代,apply异步的进行写入;
但是apply相当于commit来说是new API呢,为了更好的兼容,我们做了适配;
SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考~~
 
4、单位转换类 DensityUtils
 
- package com.zhy.utils;  
 
-   
 
- import android.content.Context;  
 
- import android.util.TypedValue;  
 
-   
 
- public class DensityUtils  
 
- {  
 
-     private DensityUtils()  
 
-     {  
 
-         
 
-         throw new UnsupportedOperationException("cannot be instantiated");  
 
-     }  
 
-   
 
-     
 
-     public static int dp2px(Context context, float dpVal)  
 
-     {  
 
-         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,  
 
-                 dpVal, context.getResources().getDisplayMetrics());  
 
-     }  
 
-   
 
-     
 
-     public static int sp2px(Context context, float spVal)  
 
-     {  
 
-         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,  
 
-                 spVal, context.getResources().getDisplayMetrics());  
 
-     }  
 
-   
 
-     
 
-     public static float px2dp(Context context, float pxVal)  
 
-     {  
 
-         final float scale = context.getResources().getDisplayMetrics().density;  
 
-         return (pxVal / scale);  
 
-     }  
 
-   
 
-     
 
-     public static float px2sp(Context context, float pxVal)  
 
-     {  
 
-         return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);  
 
-     }  
 
-   
 
- }  
 
 
5、SD卡相关辅助类 SDCardUtils
- package com.zhy.utils;  
 
-   
 
- import java.io.File;  
 
-   
 
- import android.os.Environment;  
 
- import android.os.StatFs;  
 
-   
 
- public class SDCardUtils  
 
- {  
 
-     private SDCardUtils()  
 
-     {  
 
-         
 
-         throw new UnsupportedOperationException("cannot be instantiated");  
 
-     }  
 
-   
 
-     
 
-     public static boolean isSDCardEnable()  
 
-     {  
 
-         return Environment.getExternalStorageState().equals(  
 
-                 Environment.MEDIA_MOUNTED);  
 
-   
 
-     }  
 
-   
 
-     
 
-     public static String getSDCardPath()  
 
-     {  
 
-         return Environment.getExternalStorageDirectory().getAbsolutePath()  
 
-                 + File.separator;  
 
-     }  
 
-   
 
-     
 
-     public static long getSDCardAllSize()  
 
-     {  
 
-         if (isSDCardEnable())  
 
-         {  
 
-             StatFs stat = new StatFs(getSDCardPath());  
 
-             
 
-             long availableBlocks = (long) stat.getAvailableBlocks() - 4;  
 
-             
 
-             long freeBlocks = stat.getAvailableBlocks();  
 
-             return freeBlocks * availableBlocks;  
 
-         }  
 
-         return 0;  
 
-     }  
 
-   
 
-     
 
-     public static long getFreeBytes(String filePath)  
 
-     {  
 
-         
 
-         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;  
 
-     }  
 
-   
 
-     
 
-     public static String getRootDirectoryPath()  
 
-     {  
 
-         return Environment.getRootDirectory().getAbsolutePath();  
 
-     }  
 
-   
 
-   
 
- }  
 
 
 
6、屏幕相关辅助类 ScreenUtils
 
7、App相关辅助类
 
 
- package com.zhy.utils;  
 
-   
 
- import android.content.Context;  
 
- import android.content.pm.PackageInfo;  
 
- import android.content.pm.PackageManager;  
 
- import android.content.pm.PackageManager.NameNotFoundException;  
 
-   
 
- public class AppUtils  
 
- {  
 
-   
 
-     private AppUtils()  
 
-     {  
 
-         
 
-         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;  
 
-     }  
 
-   
 
-     
 
-     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
 
 
- package com.zhy.utils;  
 
-   
 
- import android.content.Context;  
 
- import android.view.inputmethod.InputMethodManager;  
 
- import android.widget.EditText;  
 
-   
 
- public class KeyBoardUtils  
 
- {  
 
-     
 
-     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);  
 
-     }  
 
-   
 
-     
 
-     public static void closeKeybord(EditText mEditText, Context mContext)  
 
-     {  
 
-         InputMethodManager imm = (InputMethodManager) mContext  
 
-                 .getSystemService(Context.INPUT_METHOD_SERVICE);  
 
-   
 
-         imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);  
 
-     }  
 
- }  
 
 
9、网络相关辅助类 NetUtils
 
 
- package com.zhy.utils;  
 
-   
 
- import android.app.Activity;  
 
- import android.content.ComponentName;  
 
- import android.content.Context;  
 
- import android.content.Intent;  
 
- import android.net.ConnectivityManager;  
 
- import android.net.NetworkInfo;  
 
-   
 
- public class NetUtils  
 
- {  
 
-     private NetUtils()  
 
-     {  
 
-         
 
-         throw new UnsupportedOperationException("cannot be instantiated");  
 
-     }  
 
-   
 
-     
 
-     public static boolean isConnected(Context context)  
 
-     {  
 
-   
 
-         ConnectivityManager connectivity = (ConnectivityManager) context  
 
-                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
 
-   
 
-         if (null != connectivity)  
 
-         {  
 
-   
 
-             NetworkInfo info = connectivity.getActiveNetworkInfo();  
 
-             if (null != info && info.isConnected())  
 
-             {  
 
-                 if (info.getState() == NetworkInfo.State.CONNECTED)  
 
-                 {  
 
-                     return true;  
 
-                 }  
 
-             }  
 
-         }  
 
-         return false;  
 
-     }  
 
-   
 
-     
 
-     public static boolean isWifi(Context context)  
 
-     {  
 
-         ConnectivityManager cm = (ConnectivityManager) context  
 
-                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
 
-   
 
-         if (cm == null)  
 
-             return false;  
 
-         return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;  
 
-   
 
-     }  
 
-   
 
-     
 
-     public static void openSetting(Activity activity)  
 
-     {  
 
-         Intent intent = new Intent("/");  
 
-         ComponentName cm = new ComponentName("com.android.settings",  
 
-                 "com.android.settings.WirelessSettings");  
 
-         intent.setComponent(cm);  
 
-         intent.setAction("android.intent.action.VIEW");  
 
-         activity.startActivityForResult(intent, 0);  
 
-     }  
 
-   
 
- }  
 
 
 
 
10、Http相关辅助类 HttpUtils
- package com.zhy.utils;  
 
-   
 
- import java.io.BufferedReader;  
 
- import java.io.ByteArrayOutputStream;  
 
- import java.io.IOException;  
 
- import java.io.InputStream;  
 
- import java.io.InputStreamReader;  
 
- import java.io.PrintWriter;  
 
- import java.net.HttpURLConnection;  
 
- import java.net.URL;  
 
-   
 
- public class HttpUtils  
 
- {  
 
-   
 
-     private static final int TIMEOUT_IN_MILLIONS = 5000;  
 
-   
 
-     public interface CallBack  
 
-     {  
 
-         void onRequestComplete(String result);  
 
-     }  
 
-   
 
-   
 
-     
 
-     public static void doGetAsyn(final String urlStr, final CallBack callBack)  
 
-     {  
 
-         new Thread()  
 
-         {  
 
-             public void run()  
 
-             {  
 
-                 try  
 
-                 {  
 
-                     String result = doGet(urlStr);  
 
-                     if (callBack != null)  
 
-                     {  
 
-                         callBack.onRequestComplete(result);  
 
-                     }  
 
-                 } catch (Exception e)  
 
-                 {  
 
-                     e.printStackTrace();  
 
-                 }  
 
-   
 
-             };  
 
-         }.start();  
 
-     }  
 
-   
 
-     
 
-     public static void doPostAsyn(final String urlStr, final String params,  
 
-             final CallBack callBack) throws Exception  
 
-     {  
 
-         new Thread()  
 
-         {  
 
-             public void run()  
 
-             {  
 
-                 try  
 
-                 {  
 
-                     String result = doPost(urlStr, params);  
 
-                     if (callBack != null)  
 
-                     {  
 
-                         callBack.onRequestComplete(result);  
 
-                     }  
 
-                 } catch (Exception e)  
 
-                 {  
 
-                     e.printStackTrace();  
 
-                 }  
 
-   
 
-             };  
 
-         }.start();  
 
-   
 
-     }  
 
-   
 
-     
 
-     public static String doGet(String urlStr)   
 
-     {  
 
-         URL url = null;  
 
-         HttpURLConnection conn = null;  
 
-         InputStream is = null;  
 
-         ByteArrayOutputStream baos = null;  
 
-         try  
 
-         {  
 
-             url = new URL(urlStr);  
 
-             conn = (HttpURLConnection) url.openConnection();  
 
-             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);  
 
-             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);  
 
-             conn.setRequestMethod("GET");  
 
-             conn.setRequestProperty("accept", "*/*");  
 
-             conn.setRequestProperty("connection", "Keep-Alive");  
 
-             if (conn.getResponseCode() == 200)  
 
-             {  
 
-                 is = conn.getInputStream();  
 
-                 baos = new ByteArrayOutputStream();  
 
-                 int len = -1;  
 
-                 byte[] buf = new byte[128];  
 
-   
 
-                 while ((len = is.read(buf)) != -1)  
 
-                 {  
 
-                     baos.write(buf, 0, len);  
 
-                 }  
 
-                 baos.flush();  
 
-                 return baos.toString();  
 
-             } else  
 
-             {  
 
-                 throw new RuntimeException(" responseCode is not 200 ... ");  
 
-             }  
 
-   
 
-         } catch (Exception e)  
 
-         {  
 
-             e.printStackTrace();  
 
-         } finally  
 
-         {  
 
-             try  
 
-             {  
 
-                 if (is != null)  
 
-                     is.close();  
 
-             } catch (IOException e)  
 
-             {  
 
-             }  
 
-             try  
 
-             {  
 
-                 if (baos != null)  
 
-                     baos.close();  
 
-             } catch (IOException e)  
 
-             {  
 
-             }  
 
-             conn.disconnect();  
 
-         }  
 
-           
 
-         return null ;  
 
-   
 
-     }  
 
-   
 
-     /**  
 
-      * 向指定 URL 发送POST方法的请求  
 
-      *   
 
-      * @param url  
 
-      *            发送请求的 URL  
 
-      * @param param  
 
-      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。  
 
-      * @return 所代表远程资源的响应结果  
 
-      * @throws Exception  
 
-      */  
 
-     public static String doPost(String url, String param)   
 
-     {  
 
-         PrintWriter out = null;  
 
-         BufferedReader in = null;  
 
-         String result = "";  
 
-         try  
 
-         {  
 
-             URL realUrl = new URL(url);  
 
-             
 
-             HttpURLConnection conn = (HttpURLConnection) realUrl  
 
-                     .openConnection();  
 
-             
 
-             conn.setRequestProperty("accept", "*/*");  
 
-             conn.setRequestProperty("connection", "Keep-Alive");  
 
-             conn.setRequestMethod("POST");  
 
-             conn.setRequestProperty("Content-Type",  
 
-                     "application/x-www-form-urlencoded");  
 
-             conn.setRequestProperty("charset", "utf-8");  
 
-             conn.setUseCaches(false);  
 
-             
 
-             conn.setDoOutput(true);  
 
-             conn.setDoInput(true);  
 
-             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);  
 
-             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);  
 
-   
 
-             if (param != null && !param.trim().equals(""))  
 
-             {  
 
-                 
 
-                 out = new PrintWriter(conn.getOutputStream());  
 
-                 
 
-                 out.print(param);  
 
-                 
 
-                 out.flush();  
 
-             }  
 
-             
 
-             in = new BufferedReader(  
 
-                     new InputStreamReader(conn.getInputStream()));  
 
-             String line;  
 
-             while ((line = in.readLine()) != null)  
 
-             {  
 
-                 result += line;  
 
-             }  
 
-         } catch (Exception e)  
 
-         {  
 
-             e.printStackTrace();  
 
-         }  
 
-         
 
-         finally  
 
-         {  
 
-             try  
 
-             {  
 
-                 if (out != null)  
 
-                 {  
 
-                     out.close();  
 
-                 }  
 
-                 if (in != null)  
 
-                 {  
 
-                     in.close();  
 
-                 }  
 
-             } catch (IOException ex)  
 
-             {  
 
-                 ex.printStackTrace();  
 
-             }  
 
-         }  
 
-         return result;  
 
-     }  
 
- }