android开发工具类总结

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 preferenc

以上是关于android开发工具类总结的主要内容,如果未能解决你的问题,请参考以下文章

Android开发——UI_片段

在扩展片段活动android的类中加载soundpool

Android片段中的手电筒 - SurfaceView

Android开发常用代码片段

在Android中,如何将数据从类传递到相应的布局/片段文件?

Android 逆向ART 脱壳 ( DexClassLoader 脱壳 | DexClassLoader 构造函数 | 参考 Dalvik 的 DexClassLoader 类加载流程 )(代码片段