原文地址附源码下载地址
在开发中使用一些工具类,能让代码更加简洁,开发效率也更高,下面是我收集的Android中常用的一些开发工具类,如果大家有更好的工具,欢迎私信我。
数据管理的工具类,清理缓存数据
[java] view plaincopy
import java.io.File;
import java.math.BigDecimal;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
/**
* 本应用数据清除管理器
*
*
*/
public class DataCleanManager {
/**
* * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * *
*
* @param context
*/
public static void cleanInternalCache(Context context) {
deleteFilesByDirectory(context.getCacheDir());
}
/**
* * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * *
*
* @param context
*/
public static void cleanDatabases(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/databases"));
}
/**
* * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) *
*
* @param context
*/
public static void cleanSharedPreference(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/shared_prefs"));
}
/**
* * 按名字清除本应用数据库 * *
*
* @param context
* @param dbName
*/
public static void cleanDatabaseByName(Context context, String dbName) {
context.deleteDatabase(dbName);
}
/**
* * 清除/data/data/com.xxx.xxx/files下的内容 * *
*
* @param context
*/
public static void cleanFiles(Context context) {
deleteFilesByDirectory(context.getFilesDir());
}
/**
* * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
*
* @param context
*/
public static void cleanExternalCache(Context context) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
deleteFilesByDirectory(context.getExternalCacheDir());
}
}
/**
* * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * *
*
* @param filePath
* */
public static void cleanCustomCache(String filePath) {
deleteFilesByDirectory(new File(filePath));
}
/**
* * 清除本应用所有的数据 * *
*
* @param context
* @param filepath
*/
public static void cleanApplicationData(Context context, String... filepath) {
cleanInternalCache(context);
cleanExternalCache(context);
cleanDatabases(context);
cleanSharedPreference(context);
cleanFiles(context);
if (filepath == null) {
return;
}
for (String filePath : filepath) {
cleanCustomCache(filePath);
}
}
/**
* * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * *
*
* @param directory
*/
private static void deleteFilesByDirectory(File directory) {
if (directory.isFile()) {
directory.delete();
} else if (directory != null && directory.exists()
&& directory.isDirectory()) {
for (File item : directory.listFiles()) {
deleteFilesByDirectory(item);
}
}
}
// 获取文件
// Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/
// 目录,一般放一些长时间保存的数据
// Context.getExternalCacheDir() -->
// SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据
public static long getFolderSize(File file) throws Exception {
long size = 0;
try {
File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
// 如果下面还有文件
if (fileList[i].isDirectory()) {
size = size + getFolderSize(fileList[i]);
} else {
size = size + fileList[i].length();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
/**
* 删除指定目录下文件及目录
*
* @param deleteThisPath
* @param filepath
* @return
*/
public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
if (!TextUtils.isEmpty(filePath)) {
try {
File file = new File(filePath);
if (file.isDirectory()) {// 如果下面还有文件
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFolderFile(files[i].getAbsolutePath(), true);
}
}
if (deleteThisPath) {
if (!file.isDirectory()) {// 如果是文件,删除
file.delete();
} else {// 目录
if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除
file.delete();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 格式化单位
*
* @param size
* @return
*/
public static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "Byte";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "KB";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "MB";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "GB";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
+ "TB";
}
public static String getCacheSize(File file) throws Exception {
return getFormatSize(getFolderSize(file));
}
}
手机号,邮箱,身份证校验工具类
[java] view plaincopy
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerificationUtils {
private final static Pattern emailer = Pattern
.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
private static String _codeError;
// wi =2(n-1)(mod 11)
final static int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4,
2, 1 };
// verify digit
final static int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 };
private static int[] ai = new int[18];
private static String[] _areaCode = { "11", "12", "13", "14", "15", "21",
"22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42",
"43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62",
"63", "64", "65", "71", "81", "82", "91" };
private static HashMap<String, Integer> dateMap;
private static HashMap<String, String> areaCodeMap;
static {
dateMap = new HashMap<String, Integer>();
dateMap.put("01", 31);
dateMap.put("02", null);
dateMap.put("03", 31);
dateMap.put("04", 30);
dateMap.put("05", 31);
dateMap.put("06", 30);
dateMap.put("07", 31);
dateMap.put("08", 31);
dateMap.put("09", 30);
dateMap.put("10", 31);
dateMap.put("11", 30);
dateMap.put("12", 31);
areaCodeMap = new HashMap<String, String>();
for (String code : _areaCode) {
areaCodeMap.put(code, null);
}
}
/**
* 验证手机号
*
* @param str
* @return
*/
public static boolean isMobile(String str) {
Pattern p = null;
Matcher m = null;
boolean b = false;
p = Pattern.compile("^[1][3,4,5,8,7][0-9]{9}$");
// p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
m = p.matcher(str);
b = m.matches();
return b;
}
/**
* 验证邮箱
*
* @param email
* @return
*/
public static boolean isEmail(String email) {
if (email == null || email.trim().length() == 0)
return false;
return emailer.matcher(email).matches();
}
public static boolean isEmpty(String input) {
if (input == null || "".equals(input))
return true;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
return false;
}
}
return true;
}
/**
* 验证位数
* @param code
* @return
*/
public static boolean verifyLength(String code) {
int length = code.length();
if (length == 15 || length == 18) {
return true;
} else {
return false;
}
}
/**
* 验证省区
* @param code
* @return
*/
public static boolean verifyAreaCode(String code) {
String areaCode = code.substring(0, 2);
if (areaCodeMap.containsKey(areaCode)) {
return true;
} else {
return false;
}
}
/**
* 验证生日
* @param code
* @return
*/
public static boolean verifyBirthdayCode(String code) {
String month = code.substring(10, 12);
boolean isEighteenCode = (18 == code.length());
if (!dateMap.containsKey(month)) {
return false;
}
String dayCode = code.substring(12, 14);
Integer day = dateMap.get(month);
String yearCode = code.substring(6, 10);
Integer year = Integer.valueOf(yearCode);
if (day != null) {
if (Integer.valueOf(dayCode) > day || Integer.valueOf(dayCode) < 1) {
return false;
}
} else {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
if (Integer.valueOf(dayCode) > 29
|| Integer.valueOf(dayCode) < 1) {
return false;
}
} else {
if (Integer.valueOf(dayCode) > 28
|| Integer.valueOf(dayCode) < 1) {
return false;
}
}
}
return true;
}
public static boolean containsAllNumber(String code) {
String str = "";
if (code.length() == 15) {
str = code.substring(0, 15);
} else if (code.length() == 18) {
str = code.substring(0, 17);
}
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (!(ch[i] >= '0' && ch[i] <= '9')) {
return false;
}
}
return true;
}
public static boolean verify(String idcard) {
if (!verifyLength(idcard)) {
return false;
}
if (!containsAllNumber(idcard)) {
return false;
}
String eifhteencard = "";
if (idcard.length() == 15) {
eifhteencard = uptoeighteen(idcard);
} else {
eifhteencard = idcard;
}
if (!verifyAreaCode(eifhteencard)) {
return false;
}
if (!verifyBirthdayCode(eifhteencard)) {
return false;
}
if (!verifyMOD(eifhteencard)) {
return false;
}
return true;
}
public static boolean verifyMOD(String code) {
String verify = code.substring(17, 18);
if ("x".equals(verify)) {
code = code.replaceAll("x", "X");
verify = "X";
}
String verifyIndex = getVerify(code);
if (verify.equals(verifyIndex)) {
return true;
}
// int x=17;
// if(code.length()==15){
// x=14;
// }
return false;
}
public static String getVerify(String eightcardid) {
int remaining = 0;
if (eightcardid.length() == 18) {
eightcardid = eightcardid.substring(0, 17);
}
if (eightcardid.length() == 17) {
int sum = 0;
for (int i = 0; i < 17; i++) {
String k = eightcardid.substring(i, i + 1);
ai[i] = Integer.parseInt(k);
}
for (int i = 0; i < 17; i++) {
sum = sum + wi[i] * ai[i];
}
remaining = sum % 11;
}
return remaining == 2 ? "X" : String.valueOf(vi[remaining]);
}
public static String uptoeighteen(String fifteencardid) {
String eightcardid = fifteencardid.substring(0, 6);
eightcardid = eightcardid + "19";
eightcardid = eightcardid + fifteencardid.substring(6, 15);
eightcardid = eightcardid + getVerify(eightcardid);
return eightcardid;
}
}
sharedPreferences封装工具类
[java] view plaincopy
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class SharedPreferencesUtil {
/**
* 保存在手机里面的文件名
*/
private static final String SP_NAME = "sp_name";
public static void setStringParam(Context context, String key, String value) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME,
Context.MODE_PRIVATE);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
key = null;
value = null;
edit = null;
sp = null;
context = null;
}
/**
* 保存字符串数据类型
*
* @param context
* @param keys
* @param values
*/
public static void setStringParams(Context context, String[] keys,
String[] values) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME,
Context.MODE_PRIVATE);
Editor edit = sp.edit();
for (int i = 0; i < keys.length; i++) {
edit.putString(keys[i], values[i]);
}
keys = null;
values = null;
edit.commit();
edit = null;
sp = null;
context = null;
}
/**
* 保存所有数据类型 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*
* @param context
* @param key
* @param object
*/
public static void setParam(Context context, String key, Object object) {
String type = object.getClass().getSimpleName();
SharedPreferences sp = context.getSharedPreferences(SP_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if ("String".equals(type)) {
editor.putString(key, (String) object);
} else if ("Integer".equals(type)) {
editor.putInt(key, (Integer) object);
} else if ("Boolean".equals(type)) {
editor.putBoolean(key, (Boolean) object);
} else if ("Float".equals(type)) {
editor.putFloat(key, (Float) object);
} else if ("Long".equals(type)) {
editor.putLong(key, (Long) object);
}
key = null;
object = null;
editor.commit();
editor = null;
sp = null;
context = null;
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object getParam(Context context, String key,
Object defaultObject) {
String type = defaultObject.getClass().getSimpleName();
SharedPreferences sp = context.getSharedPreferences(SP_NAME,
Context.MODE_PRIVATE);
if ("String".equals(type)) {
return sp.getString(key, (String) defaultObject);
} else if ("Integer".equals(type)) {
return sp.getInt(key, (Integer) defaultObject);
} else if ("Boolean".equals(type)) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if ("Float".equals(type)) {
return sp.getFloat(key, (Float) defaultObject);
} else if ("Long".equals(type)) {
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
}
Service工具类
[java] view plaincopy
import java.util.List;
import android.app.ActivityManager;
import android.content.Context;
/**
* 服务是否运行检测帮助类
*
*/
public class ServiceUtil {
/**
* 判断服务是否后台运行
*
* @param context
* Context
* @param className
* 判断的服务名字
* @return true 在运行 false 不在运行
*/
public static boolean isServiceRun(Context mContext, String className) {
boolean isRun = false;
ActivityManager activityManager = (ActivityManager) mContext
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(40);
int size = serviceList.size();
for (int i = 0; i < size; i++) {
if (serviceList.get(i).service.getClassName().equals(className) == true) {
isRun = true;
break;
}
}
return isRun;
}
}
Log日志工具类
[java] view plaincopy
import android.util.Log;
/**
* Log显示工具类
*/
public class LogUtil {
/**
* 开发
*/
private final static int DEVELOP = 0;
/**
* 测试
*/
private final static int TEST = 1;
/**
* 上线
*/
private final static int ONLINE = 2;
/**
* 当前状态
*/
private final static int NOWSTATE = DEVELOP;
public static void info(String msg) {
info("volunteer", msg);
}
public static void info(String TAG, String msg) {
switch (NOWSTATE) {
case DEVELOP:
Log.i(TAG, "develop:---" + msg);
break;
case TEST:
Log.i(TAG, "test:---" + msg);
break;
case ONLINE:
break;
}
}
}
MD5 加密工具类
[java] view plaincopy
public final class MD5Utils {
private static final char Digit[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'
};
private static final byte PADDING[] = {
-128, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0
};
private static long state[] = new long[4];
private static long count[] = new long[2];
private static byte buffer[] = new byte[64];
private static String digestHexStr;
private static byte digest[] = new byte[16];
private MD5Utils() {
}
/**
* 没有加盐 小写输出
* @param s
* @return
*/
public static String toMD5(String s) {
md5Init();
md5Update(s.getBytes(), s.length());
md5Final();
digestHexStr = "";
for(int i = 0; i < 16; i++)
digestHexStr = digestHexStr + byteHEX(digest[i]);
return digestHexStr;
}
private static void md5Init() {
count[0] = 0L;
count[1] = 0L;
state[0] = 0x67452301L;
state[1] = 0xefcdab89L;
state[2] = 0x98badcfeL;
state[3] = 0x10325476L;
}
private static long F(long x, long y, long z) {
return (x & y) | ((~x) & z);
}
private static long G(long x, long y, long z) {
return (x & z) | (y & (~z));
}
private static long H(long x, long y, long z) {
return x ^ y ^ z;
}
private static long I(long x, long y, long z) {
return y ^ (x | (~z));
}
private static long FF(long l, long l1, long l2, long l3,
long l4, long l5, long l6) {
l += F(l1, l2, l3) + l4 + l6;
l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);
l += l1;
return l;
}
private static long GG(long l, long l1, long l2, long l3,
long l4, long l5, long l6) {
l += G(l1, l2, l3) + l4 + l6;
l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);
l += l1;
return l;
}
private static long HH(long l, long l1, long l2, long l3,
long l4, long l5, long l6) {
l += H(l1, l2, l3) + l4 + l6;
l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);
l += l1;
return l;
}
private static long II(long l, long l1, long l2, long l3,
long l4, long l5, long l6) {
l += I(l1, l2, l3) + l4 + l6;
l = (int)l << (int)l5 | (int)l >>> (int)(32L - l5);
l += l1;
return l;
}
private static void md5Update(byte abyte0[], int i) {
byte abyte1[] = new byte[64];
int k = (int)(count[0] >>> 3) & 0x3f;
if ((count[0] += i << 3) < (long)(i << 3))
count[1]++;
count[1] += i >>> 29;
int l = 64 - k;
int j;
if (i >= l) {
md5Memcpy(buffer, abyte0, k, 0, l);
md5Transform(buffer);
for(j = l; j + 63 < i; j += 64) {
md5Memcpy(abyte1, abyte0, 0, j, 64);
md5Transform(abyte1);
}
k = 0;
} else {
j = 0;
}
md5Memcpy(buffer, abyte0, k, j, i - j);
}
private static void md5Final() {
byte abyte0[] = new byte[8];
Encode(abyte0, count, 8);
int i = (int)(count[0] >>> 3) & 0x3f;
int j = i >= 56 ? 120 - i : 56 - i;
md5Update(PADDING, j);
md5Update(abyte0, 8);
Encode(digest, state, 16);
}
private static void md5Memcpy(byte abyte0[], byte abyte1[], int i, int j, int k) {
for(int l = 0; l < k; l++)
abyte0[i + l] = abyte1[j + l];
}
private static void md5Transform(byte abyte0[]) {
long l = state[0];
long l1 = state[1];
long l2 = state[2];
long l3 = state[3];
long al[] = new long[16];
Decode(al, abyte0, 64);
l = FF(l, l1, l2, l3, al[0], 7L, 0xd76aa478L);
l3 = FF(l3, l, l1, l2, al[1], 12L, 0xe8c7b756L);
l2 = FF(l2, l3, l, l1, al[2], 17L, 0x242070dbL);
l1 = FF(l1, l2, l3, l, al[3], 22L, 0xc1bdceeeL);
l = FF(l, l1, l2, l3, al[4], 7L, 0xf57c0fafL);
l3 = FF(l3, l, l1, l2, al[5], 12L, 0x4787c62aL);
l2 = FF(l2, l3, l, l1, al[6], 17L, 0xa8304613L);
l1 = FF(l1, l2, l3, l, al[7], 22L, 0xfd469501L);
l = FF(l, l1, l2, l3, al[8], 7L, 0x698098d8L);
l3 = FF(l3, l, l1, l2, al[9], 12L, 0x8b44f7afL);
l2 = FF(l2, l3, l, l1, al[10], 17L, 0xffff5bb1L);
l1 = FF(l1, l2, l3, l, al[11], 22L, 0x895cd7beL);
l = FF(l, l1, l2, l3, al[12], 7L, 0x6b901122L);
l3 = FF(l3, l, l1, l2, al[13], 12L, 0xfd987193L);
l2 = FF(l2, l3, l, l1, al[