android开发工具类总结(一)

一、日志工具类 Log.java

 1 public class L
 2 {
 3     private L()
 4     {
 5         /* 不可被实例化 */
 6         throw new UnsupportedOperationException("Cannot be instantiated!");
 7     }
 8     // 是否需要打印bug,可以在application的onCreate函数里面初始化
 9     public static boolean isDebug = true;
10     private static final String TAG = "DefaultTag";
11
12     // 下面四个是默认tag的函数
13     public static void i(String msg)
14     {
15         if (isDebug)
16             Log.i(TAG, msg);
17     }
18
19     public static void d(String msg)
20     {
21         if (isDebug)
22             Log.d(TAG, msg);
23     }
24
25     public static void e(String msg)
26     {
27         if (isDebug)
28             Log.e(TAG, msg);
29     }
30
31     public static void v(String msg)
32     {
33         if (isDebug)
34             Log.v(TAG, msg);
35     }
36
37     // 下面是传入自定义tag的函数
38     public static void i(String tag, String msg)
39     {
40         if (isDebug)
41             Log.i(tag, msg);
42     }
43
44     public static void d(String tag, String msg)
45     {
46         if (isDebug)
47             Log.i(tag, msg);
48     }
49
50     public static void e(String tag, String msg)
51     {
52         if (isDebug)
53             Log.i(tag, msg);
54     }
55
56     public static void v(String tag, String msg)
57     {
58         if (isDebug)
59             Log.i(tag, msg);
60     }
61 }  

二、Toast统一管理类 Tost.java

public class T
{  

    private T()
    {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }  

    public static boolean isShow = true;  

    /**
     * 短时间显示Toast
     */
    public static void showShort(Context context, CharSequence message)
    {
        if (isShow)
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }  

    /**
     * 短时间显示Toast
     * @param message 要显示的字符串资源的id
     */
    public static void showShort(Context context, int message)
    {
        if (isShow)
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }  

    /**
     * 长时间显示Toast
     */
    public static void showLong(Context context, CharSequence message)
    {
        if (isShow)
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }  

    /**
     * 长时间显示Toast
     */
    public static void showLong(Context context, int message)
    {
        if (isShow)
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }  

    /**
     * 自定义显示Toast时间
     */
    public static void show(Context context, CharSequence message, int duration)
    {
        if (isShow)
            Toast.makeText(context, message, duration).show();
    }  

    /**
     * 自定义显示Toast时间
     */
    public static void show(Context context, int message, int duration)
    {
        if (isShow)
            Toast.makeText(context, message, duration).show();
    }  

}  

三、SharedPreferences封装类 SPUtils.java 和 PreferencesUtils.java

1. SPUtils.java
  1 public class SPUtils
  2 {
  3     /**
  4      * 保存在手机里面的文件名
  5      */
  6     public static final String FILE_NAME = "share_data";
  7
  8     /**
  9      * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
 10      *
 11      * @param context
 12      * @param key
 13      * @param object
 14      */
 15     public static void put(Context context, String key, Object object)
 16     {
 17
 18         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
 19                 Context.MODE_PRIVATE);
 20         SharedPreferences.Editor editor = sp.edit();
 21
 22         if (object instanceof String)
 23         {
 24             editor.putString(key, (String) object);
 25         } else if (object instanceof Integer)
 26         {
 27             editor.putInt(key, (Integer) object);
 28         } else if (object instanceof Boolean)
 29         {
 30             editor.putBoolean(key, (Boolean) object);
 31         } else if (object instanceof Float)
 32         {
 33             editor.putFloat(key, (Float) object);
 34         } else if (object instanceof Long)
 35         {
 36             editor.putLong(key, (Long) object);
 37         } else
 38         {
 39             editor.putString(key, object.toString());
 40         }
 41
 42         SharedPreferencesCompat.apply(editor);
 43     }
 44
 45     /**
 46      * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
 47      *
 48      * @param context
 49      * @param key
 50      * @param defaultObject
 51      * @return
 52      */
 53     public static Object get(Context context, String key, Object defaultObject)
 54     {
 55         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
 56                 Context.MODE_PRIVATE);
 57
 58         if (defaultObject instanceof String)
 59         {
 60             return sp.getString(key, (String) defaultObject);
 61         } else if (defaultObject instanceof Integer)
 62         {
 63             return sp.getInt(key, (Integer) defaultObject);
 64         } else if (defaultObject instanceof Boolean)
 65         {
 66             return sp.getBoolean(key, (Boolean) defaultObject);
 67         } else if (defaultObject instanceof Float)
 68         {
 69             return sp.getFloat(key, (Float) defaultObject);
 70         } else if (defaultObject instanceof Long)
 71         {
 72             return sp.getLong(key, (Long) defaultObject);
 73         }
 74
 75         return null;
 76     }
 77
 78     /**
 79      * 移除某个key值已经对应的值
 80      * @param context
 81      * @param key
 82      */
 83     public static void remove(Context context, String key)
 84     {
 85         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
 86                 Context.MODE_PRIVATE);
 87         SharedPreferences.Editor editor = sp.edit();
 88         editor.remove(key);
 89         SharedPreferencesCompat.apply(editor);
 90     }
 91
 92     /**
 93      * 清除所有数据
 94      * @param context
 95      */
 96     public static void clear(Context context)
 97     {
 98         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
 99                 Context.MODE_PRIVATE);
100         SharedPreferences.Editor editor = sp.edit();
101         editor.clear();
102         SharedPreferencesCompat.apply(editor);
103     }
104
105     /**
106      * 查询某个key是否已经存在
107      * @param context
108      * @param key
109      * @return
110      */
111     public static boolean contains(Context context, String key)
112     {
113         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
114                 Context.MODE_PRIVATE);
115         return sp.contains(key);
116     }
117
118     /**
119      * 返回所有的键值对
120      *
121      * @param context
122      * @return
123      */
124     public static Map<String, ?> getAll(Context context)
125     {
126         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
127                 Context.MODE_PRIVATE);
128         return sp.getAll();
129     }
130
131     /**
132      * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
133      *
134      * @author zhy
135      *
136      */
137     private static class SharedPreferencesCompat
138     {
139         private static final Method sApplyMethod = findApplyMethod();
140
141         /**
142          * 反射查找apply的方法
143          *
144          * @return
145          */
146         @SuppressWarnings({ "unchecked", "rawtypes" })
147         private static Method findApplyMethod()
148         {
149             try
150             {
151                 Class clz = SharedPreferences.Editor.class;
152                 return clz.getMethod("apply");
153             } catch (NoSuchMethodException e)
154             {
155             }
156
157             return null;
158         }
159
160         /**
161          * 如果找到则使用apply执行,否则使用commit
162          *
163          * @param editor
164          */
165         public static void apply(SharedPreferences.Editor editor)
166         {
167             try
168             {
169                 if (sApplyMethod != null)
170                 {
171                     sApplyMethod.invoke(editor);
172                     return;
173                 }
174             } catch (IllegalArgumentException e)
175             {
176             } catch (IllegalAccessException e)
177             {
178             } catch (InvocationTargetException e)
179             {
180             }
181             editor.commit();
182         }
183     }
184
185 }  

对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;

  • 注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit.
  • 首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;
  • 所以我们使用apply进行替代,apply异步的进行写入;
  • 但是apply相当于commit来说是new API呢,为了更好的兼容,我们做了适配;
  • SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考
2. SPUtils.java
  1 public class PreferencesUtils {
  2
  3     public static String PREFERENCE_NAME = "TrineaAndroidCommon";
  4
  5     private PreferencesUtils() {
  6         throw new AssertionError();
  7     }
  8
  9     /**
 10      * put string preferences
 11      *
 12      * @param context
 13      * @param key The name of the preference to modify
 14      * @param value The new value for the preference
 15      * @return True if the new values were successfully written to persistent storage.
 16      */
 17     public static boolean putString(Context context, String key, String value) {
 18         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
 19         SharedPreferences.Editor editor = settings.edit();
 20         editor.putString(key, value);
 21         return editor.commit();
 22     }
 23
 24     /**
 25      * get string preferences
 26      *
 27      * @param context
 28      * @param key The name of the preference to retrieve
 29      * @return The preference value if it exists, or null. Throws ClassCastException if there is a preference with this
 30      *         name that is not a string
 31      * @see #getString(Context, String, String)
 32      */
 33     public static String getString(Context context, String key) {
 34         return getString(context, key, null);
 35     }
 36
 37     /**
 38      * get string preferences
 39      *
 40      * @param context
 41      * @param key The name of the preference to retrieve
 42      * @param defaultValue Value to return if this preference does not exist
 43      * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
 44      *         this name that is not a string
 45      */
 46     public static String getString(Context context, String key, String defaultValue) {
 47         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
 48         return settings.getString(key, defaultValue);
 49     }
 50
 51     /**
 52      * put int preferences
 53      *
 54      * @param context
 55      * @param key The name of the preference to modify
 56      * @param value The new value for the preference
 57      * @return True if the new values were successfully written to persistent storage.
 58      */
 59     public static boolean putInt(Context context, String key, int value) {
 60         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
 61         SharedPreferences.Editor editor = settings.edit();
 62         editor.putInt(key, value);
 63         return editor.commit();
 64     }
 65
 66     /**
 67      * get int preferences
 68      *
 69      * @param context
 70      * @param key The name of the preference to retrieve
 71      * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
 72      *         name that is not a int
 73      * @see #getInt(Context, String, int)
 74      */
 75     public static int getInt(Context context, String key) {
 76         return getInt(context, key, -1);
 77     }
 78
 79     /**
 80      * get int preferences
 81      *
 82      * @param context
 83      * @param key The name of the preference to retrieve
 84      * @param defaultValue Value to return if this preference does not exist
 85      * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
 86      *         this name that is not a int
 87      */
 88     public static int getInt(Context context, String key, int defaultValue) {
 89         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
 90         return settings.getInt(key, defaultValue);
 91     }
 92
 93     /**
 94      * put long preferences
 95      *
 96      * @param context
 97      * @param key The name of the preference to modify
 98      * @param value The new value for the preference
 99      * @return True if the new values were successfully written to persistent storage.
100      */
101     public static boolean putLong(Context context, String key, long value) {
102         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
103         SharedPreferences.Editor editor = settings.edit();
104         editor.putLong(key, value);
105         return editor.commit();
106     }
107
108     /**
109      * get long preferences
110      *
111      * @param context
112      * @param key The name of the preference to retrieve
113      * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
114      *         name that is not a long
115      * @see #getLong(Context, String, long)
116      */
117     public static long getLong(Context context, String key) {
118         return getLong(context, key, -1);
119     }
120
121     /**
122      * get long preferences
123      *
124      * @param context
125      * @param key The name of the preference to retrieve
126      * @param defaultValue Value to return if this preference does not exist
127      * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
128      *         this name that is not a long
129      */
130     public static long getLong(Context context, String key, long defaultValue) {
131         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
132         return settings.getLong(key, defaultValue);
133     }
134
135     /**
136      * put float preferences
137      *
138      * @param context
139      * @param key The name of the preference to modify
140      * @param value The new value for the preference
141      * @return True if the new values were successfully written to persistent storage.
142      */
143     public static boolean putFloat(Context context, String key, float value) {
144         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
145         SharedPreferences.Editor editor = settings.edit();
146         editor.putFloat(key, value);
147         return editor.commit();
148     }
149
150     /**
151      * get float preferences
152      *
153      * @param context
154      * @param key The name of the preference to retrieve
155      * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
156      *         name that is not a float
157      * @see #getFloat(Context, String, float)
158      */
159     public static float getFloat(Context context, String key) {
160         return getFloat(context, key, -1);
161     }
162
163     /**
164      * get float preferences
165      *
166      * @param context
167      * @param key The name of the preference to retrieve
168      * @param defaultValue Value to return if this preference does not exist
169      * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
170      *         this name that is not a float
171      */
172     public static float getFloat(Context context, String key, float defaultValue) {
173         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
174         return settings.getFloat(key, defaultValue);
175     }
176
177     /**
178      * put boolean preferences
179      *
180      * @param context
181      * @param key The name of the preference to modify
182      * @param value The new value for the preference
183      * @return True if the new values were successfully written to persistent storage.
184      */
185     public static boolean putBoolean(Context context, String key, boolean value) {
186         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
187         SharedPreferences.Editor editor = settings.edit();
188         editor.putBoolean(key, value);
189         return editor.commit();
190     }
191
192     /**
193      * get boolean preferences, default is false
194      *
195      * @param context
196      * @param key The name of the preference to retrieve
197      * @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this
198      *         name that is not a boolean
199      * @see #getBoolean(Context, String, boolean)
200      */
201     public static boolean getBoolean(Context context, String key) {
202         return getBoolean(context, key, false);
203     }
204
205     /**
206      * get boolean preferences
207      *
208      * @param context
209      * @param key The name of the preference to retrieve
210      * @param defaultValue Value to return if this preference does not exist
211      * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
212      *         this name that is not a boolean
213      */
214     public static boolean getBoolean(Context context, String key, boolean defaultValue) {
215         SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
216         return settings.getBoolean(key, defaultValue);
217     }
218 }

四、单位转换类 DensityUtils.java

 1 public class DensityUtils
 2 {
 3     private DensityUtils()
 4     {
 5         /* cannot be instantiated */
 6         throw new UnsupportedOperationException("cannot be instantiated");
 7     }
 8
 9     /**
10      * dp转px
11      *
12      * @param context
13      * @param val
14      * @return
15      */
16     public static int dp2px(Context context, float dpVal)
17     {
18         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
19                 dpVal, context.getResources().getDisplayMetrics());
20     }
21
22     /**
23      * sp转px
24      *
25      * @param context
26      * @param val
27      * @return
28      */
29     public static int sp2px(Context context, float spVal)
30     {
31         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
32                 spVal, context.getResources().getDisplayMetrics());
33     }
34
35     /**
36      * px转dp
37      *
38      * @param context
39      * @param pxVal
40      * @return
41      */
42     public static float px2dp(Context context, float pxVal)
43     {
44         final float scale = context.getResources().getDisplayMetrics().density;
45         return (pxVal / scale);
46     }
47
48     /**
49      * px转sp
50      *
51      * @param fontScale
52      * @param pxVal
53      * @return
54      */
55     public static float px2sp(Context context, float pxVal)
56     {
57         return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
58     }
59
60 }  
    • TypedValue: 
      Container for a dynamically typed data value. Primarily used with Resources for holding resource values.
    • applyDimension(int unit, float value, DisplayMetrics metrics): 
      Converts an unpacked complex data value holding a dimension to its final floating point value.

五、SD卡相关辅助类 SDCardUtils.java

 1 public class SDCardUtils
 2 {
 3     private SDCardUtils()
 4     {
 5         /* cannot be instantiated */
 6         throw new UnsupportedOperationException("cannot be instantiated");
 7     }
 8
 9     /**
10      * 判断SDCard是否可用
11      *
12      * @return
13      */
14     public static boolean isSDCardEnable()
15     {
16         return Environment.getExternalStorageState().equals(
17                 Environment.MEDIA_MOUNTED);
18
19     }
20
21     /**
22      * 获取SD卡路径
23      *
24      * @return
25      */
26     public static String getSDCardPath()
27     {
28         return Environment.getExternalStorageDirectory().getAbsolutePath()
29                 + File.separator;
30     }
31
32     /**
33      * 获取SD卡的剩余容量 单位byte
34      *
35      * @return
36      */
37     public static long getSDCardAllSize()
38     {
39         if (isSDCardEnable())
40         {
41             StatFs stat = new StatFs(getSDCardPath());
42             // 获取空闲的数据块的数量
43             long availableBlocks = (long) stat.getAvailableBlocks() - 4;
44             // 获取单个数据块的大小(byte)
45             long freeBlocks = stat.getAvailableBlocks();
46             return freeBlocks * availableBlocks;
47         }
48         return 0;
49     }
50
51     /**
52      * 获取指定路径所在空间的剩余可用容量字节数,单位byte
53      *
54      * @param filePath
55      * @return 容量字节 SDCard可用空间,内部存储可用空间
56      */
57     public static long getFreeBytes(String filePath)
58     {
59         // 如果是sd卡的下的路径,则获取sd卡可用容量
60         if (filePath.startsWith(getSDCardPath()))
61         {
62             filePath = getSDCardPath();
63         } else
64         {// 如果是内部存储的路径,则获取内存存储的可用容量
65             filePath = Environment.getDataDirectory().getAbsolutePath();
66         }
67         StatFs stat = new StatFs(filePath);
68         long availableBlocks = (long) stat.getAvailableBlocks() - 4;
69         return stat.getBlockSize() * availableBlocks;
70     }
71
72     /**
73      * 获取系统存储路径
74      *
75      * @return
76      */
77     public static String getRootDirectoryPath()
78     {
79         return Environment.getRootDirectory().getAbsolutePath();
80     }
81
82 }  

StatFs 是Android提供的一个类: 
Retrieve overall information about the space on a filesystem. This is a wrapper for Unix statvfs(). 
检索一个文件系统的整体信息空间。这是一个Unix statvfs() 包装器

六、屏幕相关辅助类 ScreenUtils.java

  1 public class ScreenUtils
  2 {
  3     private ScreenUtils()
  4     {
  5         /* cannot be instantiated */
  6         throw new UnsupportedOperationException("cannot be instantiated");
  7     }
  8
  9     /**
 10      * 获得屏幕高度
 11      *
 12      * @param context
 13      * @return
 14      */
 15     public static int getScreenWidth(Context context)
 16     {
 17         WindowManager wm = (WindowManager) context
 18                 .getSystemService(Context.WINDOW_SERVICE);
 19         DisplayMetrics outMetrics = new DisplayMetrics();
 20         wm.getDefaultDisplay().getMetrics(outMetrics);
 21         return outMetrics.widthPixels;
 22     }
 23
 24     /**
 25      * 获得屏幕宽度
 26      *
 27      * @param context
 28      * @return
 29      */
 30     public static int getScreenHeight(Context context)
 31     {
 32         WindowManager wm = (WindowManager) context
 33                 .getSystemService(Context.WINDOW_SERVICE);
 34         DisplayMetrics outMetrics = new DisplayMetrics();
 35         wm.getDefaultDisplay().getMetrics(outMetrics);
 36         return outMetrics.heightPixels;
 37     }
 38
 39     /**
 40      * 获得状态栏的高度
 41      *
 42      * @param context
 43      * @return
 44      */
 45     public static int getStatusHeight(Context context)
 46     {
 47
 48         int statusHeight = -1;
 49         try
 50         {
 51             Class<?> clazz = Class.forName("com.android.internal.R$dimen");
 52             Object object = clazz.newInstance();
 53             int height = Integer.parseInt(clazz.getField("status_bar_height")
 54                     .get(object).toString());
 55             statusHeight = context.getResources().getDimensionPixelSize(height);
 56         } catch (Exception e)
 57         {
 58             e.printStackTrace();
 59         }
 60         return statusHeight;
 61     }
 62
 63     /**
 64      * 获取当前屏幕截图,包含状态栏
 65      *
 66      * @param activity
 67      * @return
 68      */
 69     public static Bitmap snapShotWithStatusBar(Activity activity)
 70     {
 71         View view = activity.getWindow().getDecorView();
 72         view.setDrawingCacheEnabled(true);
 73         view.buildDrawingCache();
 74         Bitmap bmp = view.getDrawingCache();
 75         int width = getScreenWidth(activity);
 76         int height = getScreenHeight(activity);
 77         Bitmap bp = null;
 78         bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
 79         view.destroyDrawingCache();
 80         return bp;
 81
 82     }
 83
 84     /**
 85      * 获取当前屏幕截图,不包含状态栏
 86      *
 87      * @param activity
 88      * @return
 89      */
 90     public static Bitmap snapShotWithoutStatusBar(Activity activity)
 91     {
 92         View view = activity.getWindow().getDecorView();
 93         view.setDrawingCacheEnabled(true);
 94         view.buildDrawingCache();
 95         Bitmap bmp = view.getDrawingCache();
 96         Rect frame = new Rect();
 97         activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
 98         int statusBarHeight = frame.top;
 99
100         int width = getScreenWidth(activity);
101         int height = getScreenHeight(activity);
102         Bitmap bp = null;
103         bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
104                 - statusBarHeight);
105         view.destroyDrawingCache();
106         return bp;
107
108     }
109
110 }  

七、App相关辅助类 APPUtils.java

 1 public class AppUtils
 2 {
 3     private AppUtils()
 4     {
 5         /* cannot be instantiated */
 6         throw new UnsupportedOperationException("cannot be instantiated");
 7     }
 8
 9     /**
10      * 获取应用程序名称
11      */
12     public static String getAppName(Context context)
13     {
14         try
15         {
16             PackageManager packageManager = context.getPackageManager();
17             PackageInfo packageInfo = packageManager.getPackageInfo(
18                     context.getPackageName(), 0);
19             int labelRes = packageInfo.applicationInfo.labelRes;
20             return context.getResources().getString(labelRes);
21         } catch (NameNotFoundException e)
22         {
23             e.printStackTrace();
24         }
25         return null;
26     }
27
28     /**
29      * [获取应用程序版本名称信息]
30      *
31      * @param context
32      * @return 当前应用的版本名称
33      */
34     public static String getVersionName(Context context)
35     {
36         try
37         {
38             PackageManager packageManager = context.getPackageManager();
39             PackageInfo packageInfo = packageManager.getPackageInfo(
40                     context.getPackageName(), 0);
41             return packageInfo.versionName;
42
43         } catch (NameNotFoundException e)
44         {
45             e.printStackTrace();
46         }
47         return null;
48     }
49
50 }  

八、软键盘相关辅助类KeyBoardUtils.java

 1 /**
 2  * 打开或关闭软键盘
 3  */
 4 public class KeyBoardUtils
 5 {
 6     /**
 7      * 打卡软键盘
 8      *
 9      * @param mEditText 输入框
10      * @param mContext  上下文
11      */
12     public static void openKeybord(EditText mEditText, Context mContext)
13     {
14         InputMethodManager imm = (InputMethodManager) mContext
15                 .getSystemService(Context.INPUT_METHOD_SERVICE);
16         imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
17         imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
18                 InputMethodManager.HIDE_IMPLICIT_ONLY);
19     }
20
21     /**
22      * 关闭软键盘
23      *
24      * @param mEditText 输入框
25      * @param mContext  上下文
26      */
27     public static void closeKeybord(EditText mEditText, Context mContext)
28     {
29         InputMethodManager imm = (InputMethodManager) mContext
30                 .getSystemService(Context.INPUT_METHOD_SERVICE);
31         imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
32     }
33 }  

九、网络相关辅助类 NetUtils.java

 1 public class NetUtils
 2 {
 3     private NetUtils()
 4     {
 5         /* cannot be instantiated */
 6         throw new UnsupportedOperationException("cannot be instantiated");
 7     }
 8
 9     /**
10      * 判断网络是否连接
11      */
12     public static boolean isConnected(Context context)
13     {
14         ConnectivityManager connectivity = (ConnectivityManager) context
15                 .getSystemService(Context.CONNECTIVITY_SERVICE);
16
17         if (null != connectivity)
18         {
19             NetworkInfo info = connectivity.getActiveNetworkInfo();
20             if (null != info && info.isConnected())
21             {
22                 if (info.getState() == NetworkInfo.State.CONNECTED)
23                 {
24                     return true;
25                 }
26             }
27         }
28         return false;
29     }
30
31     /**
32      * 判断是否是wifi连接
33      */
34     public static boolean isWifi(Context context)
35     {
36         ConnectivityManager cm = (ConnectivityManager) context
37                 .getSystemService(Context.CONNECTIVITY_SERVICE);
38
39         if (cm == null)
40             return false;
41         return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
42
43     }
44
45     /**
46      * 打开网络设置界面
47      */
48     public static void openSetting(Activity activity)
49     {
50         Intent intent = new Intent("/");
51         ComponentName cm = new ComponentName("com.android.settings",
52                 "com.android.settings.WirelessSettings");
53         intent.setComponent(cm);
54         intent.setAction("android.intent.action.VIEW");
55         activity.startActivityForResult(intent, 0);
56     }
57
58 }  

十、Http相关辅助类 HttpUtils.java

  1 /**
  2  * Http请求的工具类
  3  */
  4 public class HttpUtils
  5 {
  6     private static final int TIMEOUT_IN_MILLIONS = 5000;
  7
  8     public interface CallBack
  9     {
 10         void onRequestComplete(String result);
 11     }
 12
 13
 14     /**
 15      * 异步的Get请求
 16      *
 17      * @param urlStr
 18      * @param callBack
 19      */
 20     public static void doGetAsyn(final String urlStr, final CallBack callBack)
 21     {
 22         new Thread()
 23         {
 24             public void run()
 25             {
 26                 try
 27                 {
 28                     String result = doGet(urlStr);
 29                     if (callBack != null)
 30                     {
 31                         callBack.onRequestComplete(result);
 32                     }
 33                 } catch (Exception e)
 34                 {
 35                     e.printStackTrace();
 36                 }
 37
 38             };
 39         }.start();
 40     }
 41
 42     /**
 43      * 异步的Post请求
 44      * @param urlStr
 45      * @param params
 46      * @param callBack
 47      * @throws Exception
 48      */
 49     public static void doPostAsyn(final String urlStr, final String params,
 50             final CallBack callBack) throws Exception
 51     {
 52         new Thread()
 53         {
 54             public void run()
 55             {
 56                 try
 57                 {
 58                     String result = doPost(urlStr, params);
 59                     if (callBack != null)
 60                     {
 61                         callBack.onRequestComplete(result);
 62                     }
 63                 } catch (Exception e)
 64                 {
 65                     e.printStackTrace();
 66                 }
 67
 68             };
 69         }.start();
 70
 71     }
 72
 73     /**
 74      * Get请求,获得返回数据
 75      *
 76      * @param urlStr
 77      * @return
 78      * @throws Exception
 79      */
 80     public static String doGet(String urlStr)
 81     {
 82         URL url = null;
 83         HttpURLConnection conn = null;
 84         InputStream is = null;
 85         ByteArrayOutputStream baos = null;
 86         try
 87         {
 88             url = new URL(urlStr);
 89             conn = (HttpURLConnection) url.openConnection();
 90             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
 91             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
 92             conn.setRequestMethod("GET");
 93             conn.setRequestProperty("accept", "*/*");
 94             conn.setRequestProperty("connection", "Keep-Alive");
 95             if (conn.getResponseCode() == 200)
 96             {
 97                 is = conn.getInputStream();
 98                 baos = new ByteArrayOutputStream();
 99                 int len = -1;
100                 byte[] buf = new byte[128];
101
102                 while ((len = is.read(buf)) != -1)
103                 {
104                     baos.write(buf, 0, len);
105                 }
106                 baos.flush();
107                 return baos.toString();
108             } else
109             {
110                 throw new RuntimeException(" responseCode is not 200 ... ");
111             }
112
113         } catch (Exception e)
114         {
115             e.printStackTrace();
116         } finally
117         {
118             try
119             {
120                 if (is != null)
121                     is.close();
122             } catch (IOException e)
123             {
124             }
125             try
126             {
127                 if (baos != null)
128                     baos.close();
129             } catch (IOException e)
130             {
131             }
132             conn.disconnect();
133         }
134
135         return null ;
136
137     }
138
139     /**
140      * 向指定 URL 发送POST方法的请求
141      *
142      * @param url
143      *            发送请求的 URL
144      * @param param
145      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
146      * @return 所代表远程资源的响应结果
147      * @throws Exception
148      */
149     public static String doPost(String url, String param)
150     {
151         PrintWriter out = null;
152         BufferedReader in = null;
153         String result = "";
154         try
155         {
156             URL realUrl = new URL(url);
157             // 打开和URL之间的连接
158             HttpURLConnection conn = (HttpURLConnection) realUrl
159                     .openConnection();
160             // 设置通用的请求属性
161             conn.setRequestProperty("accept", "*/*");
162             conn.setRequestProperty("connection", "Keep-Alive");
163             conn.setRequestMethod("POST");
164             conn.setRequestProperty("Content-Type",
165                     "application/x-www-form-urlencoded");
166             conn.setRequestProperty("charset", "utf-8");
167             conn.setUseCaches(false);
168             // 发送POST请求必须设置如下两行
169             conn.setDoOutput(true);
170             conn.setDoInput(true);
171             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
172             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
173
174             if (param != null && !param.trim().equals(""))
175             {
176                 // 获取URLConnection对象对应的输出流
177                 out = new PrintWriter(conn.getOutputStream());
178                 // 发送请求参数
179                 out.print(param);
180                 // flush输出流的缓冲
181                 out.flush();
182             }
183             // 定义BufferedReader输入流来读取URL的响应
184             in = new BufferedReader(
185                     new InputStreamReader(conn.getInputStream()));
186             String line;
187             while ((line = in.readLine()) != null)
188             {
189                 result += line;
190             }
191         } catch (Exception e)
192         {
193             e.printStackTrace();
194         }
195         // 使用finally块来关闭输出流、输入流
196         finally
197         {
198             try
199             {
200                 if (out != null)
201                 {
202                     out.close();
203                 }
204                 if (in != null)
205                 {
206                     in.close();
207                 }
208             } catch (IOException ex)
209             {
210                 ex.printStackTrace();
211             }
212         }
213         return result;
214     }
215 }  

十一、时间工具类 TimeUtils.java

 1 public class TimeUtils {
 2
 3     public static final SimpleDateFormat DEFAULT_DATE_FORMAT =
 4         new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 5     public static final SimpleDateFormat DATE_FORMAT_DATE =
 6         new SimpleDateFormat("yyyy-MM-dd");
 7
 8     private TimeUtils() {
 9         throw new AssertionError();
10     }
11
12     /**
13      * long time to string
14      *
15      * @param timeInMillis
16      * @param dateFormat
17      * @return
18      */
19     public static String getTime(long timeInMillis, SimpleDateFormat dateFormat) {
20         return dateFormat.format(new Date(timeInMillis));
21     }
22
23     /**
24      * long time to string, format is {@link #DEFAULT_DATE_FORMAT}
25      *
26      * @param timeInMillis
27      * @return
28      */
29     public static String getTime(long timeInMillis) {
30         return getTime(timeInMillis, DEFAULT_DATE_FORMAT);
31     }
32
33     /**
34      * get current time in milliseconds
35      *
36      * @return
37      */
38     public static long getCurrentTimeInLong() {
39         return System.currentTimeMillis();
40     }
41
42     /**
43      * get current time in milliseconds, format is {@link #DEFAULT_DATE_FORMAT}
44      *
45      * @return
46      */
47     public static String getCurrentTimeInString() {
48         return getTime(getCurrentTimeInLong());
49     }
50
51     /**
52      * get current time in milliseconds
53      *
54      * @return
55      */
56     public static String getCurrentTimeInString(SimpleDateFormat dateFormat) {
57         return getTime(getCurrentTimeInLong(), dateFormat);
58     }
59 }

十二、文件工具类 FileUtils.java

  1 public class FileUtils {
  2
  3     public final static String FILE_EXTENSION_SEPARATOR = ".";
  4
  5     private FileUtils() {
  6         throw new AssertionError();
  7     }
  8
  9     /**
 10      * read file
 11      *
 12      * @param filePath
 13      * @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>}
 14      * @return if file not exist, return null, else return content of file
 15      * @throws RuntimeException if an error occurs while operator BufferedReader
 16      */
 17     public static StringBuilder readFile(String filePath, String charsetName) {
 18         File file = new File(filePath);
 19         StringBuilder fileContent = new StringBuilder("");
 20         if (file == null || !file.isFile()) {
 21             return null;
 22         }
 23
 24         BufferedReader reader = null;
 25         try {
 26             InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
 27             reader = new BufferedReader(is);
 28             String line = null;
 29             while ((line = reader.readLine()) != null) {
 30                 if (!fileContent.toString().equals("")) {
 31                     fileContent.append("\r\n");
 32                 }
 33                 fileContent.append(line);
 34             }
 35             return fileContent;
 36         } catch (IOException e) {
 37             throw new RuntimeException("IOException occurred. ", e);
 38         } finally {
 39             IOUtils.close(reader);
 40         }
 41     }
 42
 43     /**
 44      * write file
 45      *
 46      * @param filePath
 47      * @param content
 48      * @param append is append, if true, write to the end of file, else clear content of file and write into it
 49      * @return return false if content is empty, true otherwise
 50      * @throws RuntimeException if an error occurs while operator FileWriter
 51      */
 52     public static boolean writeFile(String filePath, String content, boolean append) {
 53         if (StringUtils.isEmpty(content)) {
 54             return false;
 55         }
 56
 57         FileWriter fileWriter = null;
 58         try {
 59             makeDirs(filePath);
 60             fileWriter = new FileWriter(filePath, append);
 61             fileWriter.write(content);
 62             return true;
 63         } catch (IOException e) {
 64             throw new RuntimeException("IOException occurred. ", e);
 65         } finally {
 66             IOUtils.close(fileWriter);
 67         }
 68     }
 69
 70     /**
 71      * write file
 72      *
 73      * @param filePath
 74      * @param contentList
 75      * @param append is append, if true, write to the end of file, else clear content of file and write into it
 76      * @return return false if contentList is empty, true otherwise
 77      * @throws RuntimeException if an error occurs while operator FileWriter
 78      */
 79     public static boolean writeFile(String filePath, List<String> contentList, boolean append) {
 80         if (ListUtils.isEmpty(contentList)) {
 81             return false;
 82         }
 83
 84         FileWriter fileWriter = null;
 85         try {
 86             makeDirs(filePath);
 87             fileWriter = new FileWriter(filePath, append);
 88             int i = 0;
 89             for (String line : contentList) {
 90                 if (i++ > 0) {
 91                     fileWriter.write("\r\n");
 92                 }
 93                 fileWriter.write(line);
 94             }
 95             return true;
 96         } catch (IOException e) {
 97             throw new RuntimeException("IOException occurred. ", e);
 98         } finally {
 99             IOUtils.close(fileWriter);
100         }
101     }
102
103     /**
104      * write file, the string will be written to the begin of the file
105      *
106      * @param filePath
107      * @param content
108      * @return
109      */
110     public static boolean writeFile(String filePath, String content) {
111         return writeFile(filePath, content, false);
112     }
113
114     /**
115      * write file, the string list will be written to the begin of the file
116      *
117      * @param filePath
118      * @param contentList
119      * @return
120      */
121     public static boolean writeFile(String filePath, List<String> contentList) {
122         return writeFile(filePath, contentList, false);
123     }
124
125     /**
126      * write file, the bytes will be written to the begin of the file
127      *
128      * @param filePath
129      * @param stream
130      * @return
131      * @see {@link #writeFile(String, InputStream, boolean)}
132      */
133     public static boolean writeFile(String filePath, InputStream stream) {
134         return writeFile(filePath, stream, false);
135     }
136
137     /**
138      * write file
139      *
140      * @param file the file to be opened for writing.
141      * @param stream the input stream
142      * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
143      * @return return true
144      * @throws RuntimeException if an error occurs while operator FileOutputStream
145      */
146     public static boolean writeFile(String filePath, InputStream stream, boolean append) {
147         return writeFile(filePath != null ? new File(filePath) : null, stream, append);
148     }
149
150     /**
151      * write file, the bytes will be written to the begin of the file
152      *
153      * @param file
154      * @param stream
155      * @return
156      * @see {@link #writeFile(File, InputStream, boolean)}
157      */
158     public static boolean writeFile(File file, InputStream stream) {
159         return writeFile(file, stream, false);
160     }
161
162     /**
163      * write file
164      *
165      * @param file the file to be opened for writing.
166      * @param stream the input stream
167      * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
168      * @return return true
169      * @throws RuntimeException if an error occurs while operator FileOutputStream
170      */
171     public static boolean writeFile(File file, InputStream stream, boolean append) {
172         OutputStream o = null;
173         try {
174             makeDirs(file.getAbsolutePath());
175             o = new FileOutputStream(file, append);
176             byte data[] = new byte[1024];
177             int length = -1;
178             while ((length = stream.read(data)) != -1) {
179                 o.write(data, 0, length);
180             }
181             o.flush();
182             return true;
183         } catch (FileNotFoundException e) {
184             throw new RuntimeException("FileNotFoundException occurred. ", e);
185         } catch (IOException e) {
186             throw new RuntimeException("IOException occurred. ", e);
187         } finally {
188             IOUtils.close(o);
189             IOUtils.close(stream);
190         }
191     }
192
193     /**
194      * move file
195      *
196      * @param sourceFilePath
197      * @param destFilePath
198      */
199     public static void moveFile(String sourceFilePath, String destFilePath) {
200         if (TextUtils.isEmpty(sourceFilePath) || TextUtils.isEmpty(destFilePath)) {
201             throw new RuntimeException("Both sourceFilePath and destFilePath cannot be null.");
202         }
203         moveFile(new File(sourceFilePath), new File(destFilePath));
204     }
205
206     /**
207      * move file
208      *
209      * @param srcFile
210      * @param destFile
211      */
212     public static void moveFile(File srcFile, File destFile) {
213         boolean rename = srcFile.renameTo(destFile);
214         if (!rename) {
215             copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
216             deleteFile(srcFile.getAbsolutePath());
217         }
218     }
219
220     /**
221      * copy file
222      *
223      * @param sourceFilePath
224      * @param destFilePath
225      * @return
226      * @throws RuntimeException if an error occurs while operator FileOutputStream
227      */
228     public static boolean copyFile(String sourceFilePath, String destFilePath) {
229         InputStream inputStream = null;
230         try {
231             inputStream = new FileInputStream(sourceFilePath);
232         } catch (FileNotFoundException e) {
233             throw new RuntimeException("FileNotFoundException occurred. ", e);
234         }
235         return writeFile(destFilePath, inputStream);
236     }
237
238     /**
239      * read file to string list, a element of list is a line
240      *
241      * @param filePath
242      * @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>}
243      * @return if file not exist, return null, else return content of file
244      * @throws RuntimeException if an error occurs while operator BufferedReader
245      */
246     public static List<String> readFileToList(String filePath, String charsetName) {
247         File file = new File(filePath);
248         List<String> fileContent = new ArrayList<String>();
249         if (file == null || !file.isFile()) {
250             return null;
251         }
252
253         BufferedReader reader = null;
254         try {
255             InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
256             reader = new BufferedReader(is);
257             String line = null;
258             while ((line = reader.readLine()) != null) {
259                 fileContent.add(line);
260             }
261             return fileContent;
262         } catch (IOException e) {
263             throw new RuntimeException("IOException occurred. ", e);
264         } finally {
265             IOUtils.close(reader);
266         }
267     }
268
269     /**
270      * get file name from path, not include suffix
271      *
272      * <pre>
273      *      getFileNameWithoutExtension(null)               =   null
274      *      getFileNameWithoutExtension("")                 =   ""
275      *      getFileNameWithoutExtension("   ")              =   "   "
276      *      getFileNameWithoutExtension("abc")              =   "abc"
277      *      getFileNameWithoutExtension("a.mp3")            =   "a"
278      *      getFileNameWithoutExtension("a.b.rmvb")         =   "a.b"
279      *      getFileNameWithoutExtension("c:\\")              =   ""
280      *      getFileNameWithoutExtension("c:\\a")             =   "a"
281      *      getFileNameWithoutExtension("c:\\a.b")           =   "a"
282      *      getFileNameWithoutExtension("c:a.txt\\a")        =   "a"
283      *      getFileNameWithoutExtension("/home/admin")      =   "admin"
284      *      getFileNameWithoutExtension("/home/admin/a.txt/b.mp3")  =   "b"
285      * </pre>
286      *
287      * @param filePath
288      * @return file name from path, not include suffix
289      * @see
290      */
291     public static String getFileNameWithoutExtension(String filePath) {
292         if (StringUtils.isEmpty(filePath)) {
293             return filePath;
294         }
295
296         int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
297         int filePosi = filePath.lastIndexOf(File.separator);
298         if (filePosi == -1) {
299             return (extenPosi == -1 ? filePath : filePath.substring(0, extenPosi));
300         }
301         if (extenPosi == -1) {
302             return filePath.substring(filePosi + 1);
303         }
304         return (filePosi < extenPosi ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1));
305     }
306
307     /**
308      * get file name from path, include suffix
309      *
310      * <pre>
311      *      getFileName(null)               =   null
312      *      getFileName("")                 =   ""
313      *      getFileName("   ")              =   "   "
314      *      getFileName("a.mp3")            =   "a.mp3"
315      *      getFileName("a.b.rmvb")         =   "a.b.rmvb"
316      *      getFileName("abc")              =   "abc"
317      *      getFileName("c:\\")              =   ""
318      *      getFileName("c:\\a")             =   "a"
319      *      getFileName("c:\\a.b")           =   "a.b"
320      *      getFileName("c:a.txt\\a")        =   "a"
321      *      getFileName("/home/admin")      =   "admin"
322      *      getFileName("/home/admin/a.txt/b.mp3")  =   "b.mp3"
323      * </pre>
324      *
325      * @param filePath
326      * @return file name from path, include suffix
327      */
328     public static String getFileName(String filePath) {
329         if (StringUtils.isEmpty(filePath)) {
330             return filePath;
331         }
332
333         int filePosi = filePath.lastIndexOf(File.separator);
334         return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
335     }
336
337     /**
338      * get folder name from path
339      *
340      * <pre>
341      *      getFolderName(null)               =   null
342      *      getFolderName("")                 =   ""
343      *      getFolderName("   ")              =   ""
344      *      getFolderName("a.mp3")            =   ""
345      *      getFolderName("a.b.rmvb")         =   ""
346      *      getFolderName("abc")              =   ""
347      *      getFolderName("c:\\")              =   "c:"
348      *      getFolderName("c:\\a")             =   "c:"
349      *      getFolderName("c:\\a.b")           =   "c:"
350      *      getFolderName("c:a.txt\\a")        =   "c:a.txt"
351      *      getFolderName("c:a\\b\\c\\d.txt")    =   "c:a\\b\\c"
352      *      getFolderName("/home/admin")      =   "/home"
353      *      getFolderName("/home/admin/a.txt/b.mp3")  =   "/home/admin/a.txt"
354      * </pre>
355      *
356      * @param filePath
357      * @return
358      */
359     public static String getFolderName(String filePath) {
360
361         if (StringUtils.isEmpty(filePath)) {
362             return filePath;
363         }
364
365         int filePosi = filePath.lastIndexOf(File.separator);
366         return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
367     }
368
369     /**
370      * get suffix of file from path
371      *
372      * <pre>
373      *      getFileExtension(null)               =   ""
374      *      getFileExtension("")                 =   ""
375      *      getFileExtension("   ")              =   "   "
376      *      getFileExtension("a.mp3")            =   "mp3"
377      *      getFileExtension("a.b.rmvb")         =   "rmvb"
378      *      getFileExtension("abc")              =   ""
379      *      getFileExtension("c:\\")              =   ""
380      *      getFileExtension("c:\\a")             =   ""
381      *      getFileExtension("c:\\a.b")           =   "b"
382      *      getFileExtension("c:a.txt\\a")        =   ""
383      *      getFileExtension("/home/admin")      =   ""
384      *      getFileExtension("/home/admin/a.txt/b")  =   ""
385      *      getFileExtension("/home/admin/a.txt/b.mp3")  =   "mp3"
386      * </pre>
387      *
388      * @param filePath
389      * @return
390      */
391     public static String getFileExtension(String filePath) {
392         if (StringUtils.isBlank(filePath)) {
393             return filePath;
394         }
395
396         int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
397         int filePosi = filePath.lastIndexOf(File.separator);
398         if (extenPosi == -1) {
399             return "";
400         }
401         return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1);
402     }
403
404     /**
405      * Creates the directory named by the trailing filename of this file, including the complete directory path required
406      * to create this directory. <br/>
407      * <br/>
408      * <ul>
409      * <strong>Attentions:</strong>
410      * <li>makeDirs("C:\\Users\\Trinea") can only create users folder</li>
411      * <li>makeFolder("C:\\Users\\Trinea\\") can create Trinea folder</li>
412      * </ul>
413      *
414      * @param filePath
415      * @return true if the necessary directories have been created or the target directory already exists, false one of
416      *         the directories can not be created.
417      *         <ul>
418      *         <li>if {@link FileUtils#getFolderName(String)} return null, return false</li>
419      *         <li>if target directory already exists, return true</li>
420      *         <li>return {@link java.io.File#makeFolder}</li>
421      *         </ul>
422      */
423     public static boolean makeDirs(String filePath) {
424         String folderName = getFolderName(filePath);
425         if (StringUtils.isEmpty(folderName)) {
426             return false;
427         }
428
429         File folder = new File(folderName);
430         return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
431     }
432
433     /**
434      * @param filePath
435      * @return
436      * @see #makeDirs(String)
437      */
438     public static boolean makeFolders(String filePath) {
439         return makeDirs(filePath);
440     }
441
442     /**
443      * Indicates if this file represents a file on the underlying file system.
444      *
445      * @param filePath
446      * @return
447      */
448     public static boolean isFileExist(String filePath) {
449         if (StringUtils.isBlank(filePath)) {
450             return false;
451         }
452
453         File file = new File(filePath);
454         return (file.exists() && file.isFile());
455     }
456
457     /**
458      * Indicates if this file represents a directory on the underlying file system.
459      *
460      * @param directoryPath
461      * @return
462      */
463     public static boolean isFolderExist(String directoryPath) {
464         if (StringUtils.isBlank(directoryPath)) {
465             return false;
466         }
467
468         File dire = new File(directoryPath);
469         return (dire.exists() && dire.isDirectory());
470     }
471
472     /**
473      * delete file or directory
474      * <ul>
475      * <li>if path is null or empty, return true</li>
476      * <li>if path not exist, return true</li>
477      * <li>if path exist, delete recursion. return true</li>
478      * <ul>
479      *
480      * @param path
481      * @return
482      */
483     public static boolean deleteFile(String path) {
484         if (StringUtils.isBlank(path)) {
485             return true;
486         }
487
488         File file = new File(path);
489         if (!file.exists()) {
490             return true;
491         }
492         if (file.isFile()) {
493             return file.delete();
494         }
495         if (!file.isDirectory()) {
496             return false;
497         }
498         for (File f : file.listFiles()) {
499             if (f.isFile()) {
500                 f.delete();
501             } else if (f.isDirectory()) {
502                 deleteFile(f.getAbsolutePath());
503             }
504         }
505         return file.delete();
506     }
507
508     /**
509      * get file size
510      * <ul>
511      * <li>if path is null or empty, return -1</li>
512      * <li>if path exist and it is a file, return file size, else return -1</li>
513      * <ul>
514      *
515      * @param path
516      * @return returns the length of this file in bytes. returns -1 if the file does not exist.
517      */
518     public static long getFileSize(String path) {
519         if (StringUtils.isBlank(path)) {
520             return -1;
521         }
522
523         File file = new File(path);
524         return (file.exists() && file.isFile() ? file.length() : -1);
525     }
526 }

十三、assets和raw资源工具类 ResourceUtils.java

  1 public class ResourceUtils {
  2
  3     private ResourceUtils() {
  4         throw new AssertionError();
  5     }
  6
  7     /**
  8      * get an asset using ACCESS_STREAMING mode. This provides access to files that have been bundled with an
  9      * application as assets -- that is, files placed in to the "assets" directory.
 10      *
 11      * @param context
 12      * @param fileName The name of the asset to open. This name can be hierarchical.
 13      * @return
 14      */
 15     public static String geFileFromAssets(Context context, String fileName) {
 16         if (context == null || StringUtils.isEmpty(fileName)) {
 17             return null;
 18         }
 19
 20         StringBuilder s = new StringBuilder("");
 21         try {
 22             InputStreamReader in = new InputStreamReader(context.getResources().getAssets().open(fileName));
 23             BufferedReader br = new BufferedReader(in);
 24             String line;
 25             while ((line = br.readLine()) != null) {
 26                 s.append(line);
 27             }
 28             return s.toString();
 29         } catch (IOException e) {
 30             e.printStackTrace();
 31             return null;
 32         }
 33     }
 34
 35     /**
 36      * get content from a raw resource. This can only be used with resources whose value is the name of an asset files
 37      * -- that is, it can be used to open drawable, sound, and raw resources; it will fail on string and color
 38      * resources.
 39      *
 40      * @param context
 41      * @param resId The resource identifier to open, as generated by the appt tool.
 42      * @return
 43      */
 44     public static String geFileFromRaw(Context context, int resId) {
 45         if (context == null) {
 46             return null;
 47         }
 48
 49         StringBuilder s = new StringBuilder();
 50         try {
 51             InputStreamReader in = new InputStreamReader(context.getResources().openRawResource(resId));
 52             BufferedReader br = new BufferedReader(in);
 53             String line;
 54             while ((line = br.readLine()) != null) {
 55                 s.append(line);
 56             }
 57             return s.toString();
 58         } catch (IOException e) {
 59             e.printStackTrace();
 60             return null;
 61         }
 62     }
 63
 64     /**
 65      * same to {@link ResourceUtils#geFileFromAssets(Context, String)}, but return type is List<String>
 66      *
 67      * @param context
 68      * @param fileName
 69      * @return
 70      */
 71     public static List<String> geFileToListFromAssets(Context context, String fileName) {
 72         if (context == null || StringUtils.isEmpty(fileName)) {
 73             return null;
 74         }
 75
 76         List<String> fileContent = new ArrayList<String>();
 77         try {
 78             InputStreamReader in = new InputStreamReader(context.getResources().getAssets().open(fileName));
 79             BufferedReader br = new BufferedReader(in);
 80             String line;
 81             while ((line = br.readLine()) != null) {
 82                 fileContent.add(line);
 83             }
 84             br.close();
 85             return fileContent;
 86         } catch (IOException e) {
 87             e.printStackTrace();
 88             return null;
 89         }
 90     }
 91
 92     /**
 93      * same to {@link ResourceUtils#geFileFromRaw(Context, int)}, but return type is List<String>
 94      *
 95      * @param context
 96      * @param resId
 97      * @return
 98      */
 99     public static List<String> geFileToListFromRaw(Context context, int resId) {
100         if (context == null) {
101             return null;
102         }
103
104         List<String> fileContent = new ArrayList<String>();
105         BufferedReader reader = null;
106         try {
107             InputStreamReader in = new InputStreamReader(context.getResources().openRawResource(resId));
108             reader = new BufferedReader(in);
109             String line = null;
110             while ((line = reader.readLine()) != null) {
111                 fileContent.add(line);
112             }
113             reader.close();
114             return fileContent;
115         } catch (IOException e) {
116             e.printStackTrace();
117             return null;
118         }
119     }
120 }

十四、单例工具类 SingletonUtils.java

 1 public abstract class SingletonUtils<T> {
 2
 3     private T instance;
 4
 5     protected abstract T newInstance();
 6
 7     public final T getInstance() {
 8         if (instance == null) {
 9             synchronized (SingletonUtils.class) {
10                 if (instance == null) {
11                     instance = newInstance();
12                 }
13             }
14         }
15         return instance;
16     }
17 }

十五、数据库工具类 SqliteUtils.java

 1 public class SqliteUtils {
 2
 3     private static volatile SqliteUtils instance;
 4
 5     private DbHelper                    dbHelper;
 6     private SQLiteDatabase              db;
 7
 8     private SqliteUtils(Context context) {
 9         dbHelper = new DbHelper(context);
10         db = dbHelper.getWritableDatabase();
11     }
12
13     public static SqliteUtils getInstance(Context context) {
14         if (instance == null) {
15             synchronized (SqliteUtils.class) {
16                 if (instance == null) {
17                     instance = new SqliteUtils(context);
18                 }
19             }
20         }
21         return instance;
22     }
23
24     public SQLiteDatabase getDb() {
25         return db;
26     }
27 }
时间: 2024-10-10 10:59:21

android开发工具类总结(一)的相关文章

Android 开发工具类 13_ SaxService

网络 xml 解析方式 1 package com.example.dashu_saxxml; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.HashMap; 6 import java.util.List; 7 8 import javax.xml.parsers.SAXParser; 9 import javax.xml.parsers.SAXParserFactory; 10

Android 开发工具类 35_PatchUtils

增量更新工具类[https://github.com/cundong/SmartAppUpdates] 1 import java.io.File; 2 3 import android.app.Activity; 4 import android.app.ProgressDialog; 5 import android.content.Context; 6 import android.content.Intent; 7 import android.net.Uri; 8 import and

Android开发工具类之DownloadManagerPro

这个工具类就是Android系统下载管理DownloadManager的一个增强类,提供了一些增强方法.或许大家不太了解这个安卓系统自带的DownloadManager这个类,我先做一个简单介绍吧.DownloadManager是系统开放给第三方应用使用的类,包含两个静态内部类DownloadManager.Query和DownloadManager.Request. DownloadManager.Request用来请求一个下载,DownloadManager.Query用来查询下载信息.用d

Android 开发工具类 03_HttpUtils

Http 请求的工具类: 1.异步的 Get 请求: 2.异步的 Post 请求: 3.Get 请求,获得返回数据: 4.向指定 URL 发送 POST方法的请求. 1 import java.io.BufferedReader; 2 import java.io.ByteArrayOutputStream; 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.InputStreamReader

Android 开发工具类 19_NetworkStateReceiver

检测网络状态改变类: 1.注册网络状态广播: 2.检查网络状态: 3.注销网络状态广播: 4.获取当前网络状态,true为网络连接成功,否则网络连接失败: 5.注册网络连接观察者: 6.注销网络连接观察者. 1 import java.util.ArrayList; 2 3 import android.content.BroadcastReceiver; 4 import android.content.Context; 5 import android.content.Intent; 6 i

Android 开发工具类 10_Toast 统一管理类

Toast 统一管理类: 1.短时间显示Toast: 2.长时间显示 Toast: 3.自定义显示 Toast 时间. 1 import android.content.Context; 2 import android.widget.Toast; 3 4 // Toast 统一管理类 5 public class T 6 { 7 8 private T() 9 { 10 /* cannot be instantiated */ 11 throw new UnsupportedOperation

Android 开发工具类 09_SPUtils

SharedPreferences 辅助类: 1.保存在手机里面的文件名: 2.保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法: 3.得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值: 4.移除某个 key 值已经对应的值: 5.清除所有数据: 6.查询某个 key 是否已经存在: 7.返回所有的键值对: 8.创建一个解决 SharedPreferencesCompat.apply 方法的一个兼容类: 1 import jav

Android 开发工具类 33_开机自运行

原理:该类派生自 BroadcastReceiver,重载方法 onReceive ,检测接收到的 Intent 是否符合 BOOT_COMPLETED,如果符合,则启动用户Activity. 1 import android.content.BroadcastReceiver; 2 import android.content.Context; 3 import android.content.Intent; 4 5 public class BootBroadcastReceiver ext

Android 开发工具类 31_WebService 获取手机号码归属地

AndroidInteractWithWebService.xml 1 <?xml version="1.0" encoding="utf-8"?> 2 <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12=