Android开发的工具类一

来源:互联网 发布:钩针和棒针的区别知乎 编辑:程序博客网 时间:2024/06/07 16:59

  Android开发的工具类能很好的封装一些常用的操作,以后使用起来也非常方便,我把我经常使用的工具类分享给大家。

FileCache:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
packagecom.pztuan.common.util;
 
importjava.io.File;
importandroid.content.Context;
 
publicclass FileCache {
    privateFile cacheDir;
 
    publicFileCache(Context context) {
        // 判断外存SD卡挂载状态,如果挂载正常,创建SD卡缓存文件夹
        if(android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            cacheDir = newFile(
                    android.os.Environment.getExternalStorageDirectory(),
                    "PztCacheDir");
        }else{
            // SD卡挂载不正常,获取本地缓存文件夹(应用包所在目录)
            cacheDir = context.getCacheDir();
        }
        if(!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
    }
 
    publicFile getFile(String url) {
        String fileName = String.valueOf(url.hashCode());
        File file = newFile(cacheDir, fileName);
        returnfile;
    }
 
    publicvoid clear() {
        File[] files = cacheDir.listFiles();
        for(File f : files)
            f.delete();
    }
 
    publicString getCacheSize() {
        longsize = 0;
        if(cacheDir.exists()) {
            File[] files = cacheDir.listFiles();
            for(File f : files) {
                size += f.length();
            }
        }
        String cacheSize = String.valueOf(size / 1024/ 1024) + "M";
        returncacheSize;
    }
 
}

NetWorkUtil(网络类): 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
packagecom.pztuan.common.util;
 
importandroid.content.Context;
importandroid.net.ConnectivityManager;
importandroid.net.NetworkInfo;
importandroid.net.NetworkInfo.State;
importandroid.net.wifi.WifiManager;
 
importjava.security.MessageDigest;
 
/**
 *
 * @author suncat
 * @category 网络工具
 */
publicclass NetWorkUtil {
    privatefinal static String[] hexDigits = { "0","1","2","3","4","5",
            "6","7","8","9","a","b","c","d","e","f"};
    publicstatic final int STATE_DISCONNECT = 0;
    publicstatic final int STATE_WIFI = 1;
    publicstatic final int STATE_MOBILE = 2;
 
    publicstatic String concatUrlParams() {
 
        returnnull;
    }
 
    publicstatic String encodeUrl() {
 
        returnnull;
    }
 
    publicstatic boolean isNetWorkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] nis = cm.getAllNetworkInfo();
        if(nis != null) {
            for(NetworkInfo ni : nis) {
                if(ni != null) {
                    if(ni.isConnected()) {
                        returntrue;
                    }
                }
            }
        }
 
        returnfalse;
    }
 
    publicstatic boolean isWifiConnected(Context context) {
        WifiManager wifiMgr = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        booleanisWifiEnable = wifiMgr.isWifiEnabled();
 
        returnisWifiEnable;
    }
 
    publicstatic boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if(networkInfo != null) {
            returnnetworkInfo.isAvailable();
        }
 
        returnfalse;
    }
 
    privatestatic String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = newStringBuffer();
        for(inti = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        returnresultSb.toString();
    }
 
    privatestatic String byteToHexString(byteb) {
        intn = b;
        if(n < 0)
            n = 256+ n;
        intd1 = n / 16;
        intd2 = n % 16;
        returnhexDigits[d1] + hexDigits[d2];
    }
 
    publicstatic String md5Encode(String origin) {
        String resultString = null;
 
        try{
            resultString = newString(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = newString(md.digest(resultString.getBytes()));
        }catch(Exception ex) {
            ex.printStackTrace();
        }
 
        returnresultString;
    }
 
    publicstatic String md5EncodeToHexString(String origin) {
        String resultString = null;
 
        try{
            resultString = newString(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString
                    .getBytes()));
        }catch(Exception ex) {
            ex.printStackTrace();
        }
 
        returnresultString;
    }
 
    publicstatic int getNetworkState(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
 
        // Wifi
        State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                .getState();
        if(state == State.CONNECTED || state == State.CONNECTING) {
            returnSTATE_WIFI;
        }
 
        // 3G
        state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState();
        if(state == State.CONNECTED || state == State.CONNECTING) {
            returnSTATE_MOBILE;
        }
        returnSTATE_DISCONNECT;
    }
}

Tools(常用小功能:号码正则匹配、日期计算、获取imei号、计算listview高度):


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
packagecom.pztuan.common.util;
 
importjava.security.MessageDigest;
importjava.text.ParseException;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
 
importandroid.annotation.SuppressLint;
importandroid.content.Context;
importandroid.os.Environment;
importandroid.telephony.TelephonyManager;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.ListAdapter;
importandroid.widget.ListView;
importandroid.widget.Toast;
 
@SuppressLint("DefaultLocale")
publicclass Tools {
 
    privatefinal static String[] hexDigits = { "0","1","2","3","4","5",
            "6","7","8","9","a","b","c","d","e","f"};
 
    publicstatic String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = newStringBuffer();
        for(inti = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        returnresultSb.toString();
    }
 
    privatestatic String byteToHexString(byteb) {
        intn = b;
        if(n < 0)
            n = 256+ n;
        intd1 = n / 16;
        intd2 = n % 16;
        returnhexDigits[d1] + hexDigits[d2];
    }
 
    /**
     * md5 加密
     *
     * @param origin
     * @return
     */
    publicstatic String md5Encode(String origin) {
        String resultString = null;
        try{
            resultString = newString(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString
                    .getBytes()));
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        returnresultString;
    }
 
    /**
     * 手机号码格式匹配
     *
     * @param mobiles
     * @return
     */
    publicstatic boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(18[0,1,3,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "-telnum-");
        returnm.matches();
    }
 
    /**
     * 是否含有指定字符
     *
     * @param expression
     * @param text
     * @return
     */
    privatestatic boolean matchingText(String expression, String text) {
        Pattern p = Pattern.compile(expression);
        Matcher m = p.matcher(text);
        booleanb = m.matches();
        returnb;
    }
 
    /**
     * 邮政编码
     *
     * @param zipcode
     * @return
     */
    publicstatic boolean isZipcode(String zipcode) {
        Pattern p = Pattern.compile("[0-9]\\d{5}");
        Matcher m = p.matcher(zipcode);
        System.out.println(m.matches() + "-zipcode-");
        returnm.matches();
    }
 
    /**
     * 邮件格式
     *
     * @param email
     * @return
     */
    publicstatic boolean isValidEmail(String email) {
        Pattern p = Pattern
                .compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
        Matcher m = p.matcher(email);
        System.out.println(m.matches() + "-email-");
        returnm.matches();
    }
 
    /**
     * 固话号码格式
     *
     * @param telfix
     * @return
     */
    publicstatic boolean isTelfix(String telfix) {
        Pattern p = Pattern.compile("d{3}-d{8}|d{4}-d{7}");
        Matcher m = p.matcher(telfix);
        System.out.println(m.matches() + "-telfix-");
        returnm.matches();
    }
 
    /**
     * 用户名匹配
     *
     * @param name
     * @return
     */
    publicstatic boolean isCorrectUserName(String name) {
        Pattern p = Pattern.compile("([A-Za-z0-9]){2,10}");
        Matcher m = p.matcher(name);
        System.out.println(m.matches() + "-name-");
        returnm.matches();
    }
 
    /**
     * 密码匹配,以字母开头,长度 在6-18之间,只能包含字符、数字和下划线。
     *
     * @param pwd
     * @return
     *
     */
    publicstatic boolean isCorrectUserPwd(String pwd) {
        Pattern p = Pattern.compile("\\w{6,18}");
        Matcher m = p.matcher(pwd);
        System.out.println(m.matches() + "-pwd-");
        returnm.matches();
    }
 
    /**
     * 检查是否存在SDCard
     *
     * @return
     */
    publicstatic boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)) {
            returntrue;
        }else{
            returnfalse;
        }
    }
 
    /**
     * 计算剩余日期
     *
     * @param remainTime
     * @return
     */
    publicstatic String calculationRemainTime(String endTime, longcountDown) {
 
        SimpleDateFormat df = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            Date now = newDate(System.currentTimeMillis());// 获取当前时间
            Date endData = df.parse(endTime);
            longl = endData.getTime() - countDown - now.getTime();
            longday = l / (24* 60* 60* 1000);
            longhour = (l / (60* 60* 1000) - day * 24);
            longmin = ((l / (60* 1000)) - day * 24* 60- hour * 60);
            longs = (l / 1000- day * 24* 60* 60- hour * 60* 60- min * 60);
            return"剩余" + day + "天"+ hour + "小时"+ min + "分"+ s + "秒";
        }catch(ParseException e) {
            e.printStackTrace();
        }
        return"";
    }
 
    publicstatic void showLongToast(Context act, String pMsg) {
        Toast toast = Toast.makeText(act, pMsg, Toast.LENGTH_LONG);
        toast.show();
    }
 
    publicstatic void showShortToast(Context act, String pMsg) {
        Toast toast = Toast.makeText(act, pMsg, Toast.LENGTH_SHORT);
        toast.show();
    }
 
    /**
     * 获取手机Imei号
     *
     * @param context
     * @return
     */
    publicstatic String getImeiCode(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        returntm.getDeviceId();
    }
 
    /**
     * @author sunglasses
     * @param listView
     * @category 计算listview的高度
     */
    publicstatic void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if(listAdapter == null) {
            // pre-condition
            return;
        }
 
        inttotalHeight = 0;
        for(inti = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0,0);
            totalHeight += listItem.getMeasuredHeight();
        }
 
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}

SharedPreferencesUtil:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
packagecom.pztuan.db;
 
importandroid.content.Context;
importandroid.content.SharedPreferences;
importandroid.content.SharedPreferences.Editor;
importandroid.util.Log;
 
importjava.util.ArrayList;
importjava.util.Set;
 
publicclass SharedPreferencesUtil {
    privatestatic final String TAG = "PZTuan.SharePreferencesUtil";
    privatestatic final String SHAREDPREFERENCE_NAME = "sharedpreferences_pztuan";
 
    privatestatic SharedPreferencesUtil mInstance;
 
    privatestatic SharedPreferences mSharedPreferences;
 
    privatestatic SharedPreferences.Editor mEditor;
 
    publicsynchronized static SharedPreferencesUtil getInstance(Context context) {
        if(mInstance == null) {
            mInstance = newSharedPreferencesUtil(context);
        }
 
        returnmInstance;
    }
 
    privateSharedPreferencesUtil(Context context) {
        mSharedPreferences = context.getSharedPreferences(
                SHAREDPREFERENCE_NAME, Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
    }
 
    publicsynchronized boolean putString(String key, String value) {
        mEditor.putString(key, value);
        returnmEditor.commit();
    }
 
    publicsynchronized boolean putStringArrayList(String key,
            ArrayList<String> value) {
 
        for(intj = 0; j < value.size() - 1; j++) {
            if(value.get(value.size() - 1).equals(value.get(j))) {
                value.remove(j);
            }
        }
        mEditor.putInt("citySize", value.size());
 
        if(value.size() == 4) {
            mEditor.putString(key + 0, value.get(3));
            mEditor.putString(key + 1, value.get(0));
            mEditor.putString(key + 2, value.get(1));
        }elseif (value.size() == 3) {
            mEditor.putString(key + 0, value.get(2));
            mEditor.putString(key + 1, value.get(0));
            mEditor.putString(key + 2, value.get(1));
        }else{
            for(inti = 0; i < value.size(); i++) {
                mEditor.putString(key + i, value.get(value.size() - 1- i));
            }
 
        }
        returnmEditor.commit();
    }
 
    publicsynchronized boolean putInt(String key, intvalue) {
        mEditor.putInt(key, value);
        returnmEditor.commit();
    }
 
    publicsynchronized boolean putLong(String key, longvalue) {
        mEditor.putLong(key, value);
        returnmEditor.commit();
    }
 
    publicsynchronized boolean putFloat(String key, floatvalue) {
        mEditor.putFloat(key, value);
        returnmEditor.commit();
    }
 
    publicsynchronized boolean putBoolean(String key, booleanvalue) {
        mEditor.putBoolean(key, value);
        returnmEditor.commit();
    }
 
    publicsynchronized boolean putStringSet(String key, Set<String> value) {
        mEditor.putStringSet(key, value);
        returnmEditor.commit();
    }
 
    publicString getString(String key, String value) {
        returnmSharedPreferences.getString(key, value);
    }
 
    publicArrayList<String> getStringArrayList(String key, intsize) {
        ArrayList<String> al = newArrayList<String>();
        intloop;
        if(size > 4)
            loop = 4;
        else
            loop = size;
        for(inti = 0; i < loop; i++) {
            String name = mSharedPreferences.getString(key + i, null);
            al.add(name);
        }
        returnal;
    }
 
    publicint getInt(String key, intvalue) {
        returnmSharedPreferences.getInt(key, value);
    }
 
    publiclong getLong(String key, longvalue) {
        returnmSharedPreferences.getLong(key, value);
    }
 
    publicfloat getFloat(String key, floatvalue) {
        returnmSharedPreferences.getFloat(key, value);
    }
 
    publicboolean getBoolean(String key, booleanvalue) {
        returnmSharedPreferences.getBoolean(key, value);
    }
 
    publicSet<String> getStringSet(String key, Set<String> value) {
        returnmSharedPreferences.getStringSet(key, value);
    }
 
    publicboolean remove(String key) {
        mEditor.remove(key);
        returnmEditor.commit();
    }
 
    privatestatic final String PREFERENCES_AUTO_LOGIN = "yyUserAutoLogin";
    privatestatic final String PREFERENCES_USER_NAME = "yyUserName";
    privatestatic final String PREFERENCES_USER_PASSWORD = "yyUserPassword";
 
    publicboolean isAutoLogin() {
        returnmSharedPreferences.getBoolean(PREFERENCES_AUTO_LOGIN, false);
    }
 
    publicString getUserName() {
        returnmSharedPreferences.getString(PREFERENCES_USER_NAME, "");
    }
 
    publicString getUserPwd() {
        returnmSharedPreferences.getString(PREFERENCES_USER_PASSWORD, "");
    }
 
    publicvoid saveLoginInfo(Boolean autoLogin, String userName,
            String userPassword) {
        assert(mEditor != null);
        mEditor.putBoolean(PREFERENCES_AUTO_LOGIN, autoLogin);
        mEditor.putString(PREFERENCES_USER_NAME, userName);
        mEditor.putString(PREFERENCES_USER_PASSWORD, userPassword);
        mEditor.commit();
    }
 
    publicvoid saveLoginPassword(String userPassword) {
        mEditor.putString(PREFERENCES_USER_PASSWORD, userPassword);
        mEditor.commit();
    }
 
    publicvoid saveLoginUserid(String userid) {
        mEditor.putString("userid", userid);
        mEditor.commit();
    }
 
    publicvoid clearUserInfo() {
        assert(mEditor != null);
        mEditor.putBoolean(PREFERENCES_AUTO_LOGIN,false);
        mEditor.putString(PREFERENCES_USER_NAME,"");
        mEditor.putString(PREFERENCES_USER_PASSWORD,"");
        mEditor.putString("userid","");
        mEditor.commit();
    }
 
}
0 0
原创粉丝点击