您的位置:首页 > 移动开发 > Android开发

Android常用工具类...

2017-06-03 11:57 323 查看
在开发andorid中我们经常会使用一些工具类:如:内存、像素、版本、网络、文件等下面具体列出一些。:

话不多说,直接代码:直观、明了…

像素转换、屏幕宽高…

/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}

/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}

public static boolean checkApkExist(Context context, String packageName) {
if (packageName == null || "".equals(packageName))
return false;
try {
ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
return true;
} catch (NameNotFoundException e) {
return false;
}
}

public static String getScreenInfo(Activity context) {
String str = "";
DisplayMetrics metric = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels;  // 屏幕宽度(像素)
int height = metric.heightPixels;  // 屏幕高度(像素)
float density = metric.density;  // 屏幕密度(0.75 / 1.0 / 1.5)
int densityDpi = metric.densityDpi;  // 屏幕密度DPI(120 / 160 / 240
str = "屏幕宽高:" + width + ":" + height + "屏幕密度:" + density + ":" + densityDpi;
return str;
}

//获取屏幕的宽度和高度
public static int[] getScreenWidthHeight(Activity context) {
DisplayMetrics metric = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels;  // 屏幕宽度(像素)
int height = metric.heightPixels;  // 屏幕高度(像素)
int[] wh = new int[2];
wh[0] = width;
wh[1] = height;
return wh;
}

public static int getScreenWidth(Context context) {
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getWidth();
}

public static int getScreenHeight(Context context) {
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
return display.getHeight();
}

/**
* 获取屏幕可用高度
*/
public static int getScreenUseHeight(Activity context) {
Rect rect = new Rect();
context.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
View v = context.getWindow().findViewById(Window.ID_ANDROID_CONTENT);

return rect.height();
}

/**
* 判断当前设备是手机还是平板,代码来自 Google I/O App for Android
*
* @param context
* @return 平板返回 True,手机返回 False
*/
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}


屏幕辅助类

/**
* 获得屏幕相关的辅助类
*
*
*
*/
public class ScreenUtils
{
private ScreenUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}

/**
* 获得屏幕高度
*
* @param context
* @return
*/
public static int getScreenWidth(Context context)
{
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}

/**
* 获得屏幕宽度
*
* @param context
* @return
*/
public static int getScreenHeight(Context context)
{
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}

/**
* 获得状态栏的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context)
{

int statusHeight = -1;
try
{
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e)
{
e.printStackTrace();
}
return statusHeight;
}

/**
* 获取当前屏幕截图,包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithStatusBar(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;

}

/**
* 获取当前屏幕截图,不包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;

int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;

}

}


软键盘

/**
* 打开或关闭软键盘
*
* @author zhy
*
*/
public class KeyBoardUtils
{
/**
* 打卡软键盘
*
* @param mEditText
*            输入框
* @param mContext
*            上下文
*/
public static void openKeybord(EditText mEditText, Context mContext)
{
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}

/**
* 关闭软键盘
*
* @param mEditText
*            输入框
* @param mContext
*            上下文
*/
public static void closeKeybord(EditText mEditText, Context mContext)
{
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
}


手机存储

public static String getPhoneCardPath() {
return Environment.getDataDirectory().getPath();

}

/**
* 获取sd卡路径
* 双sd卡时,根据”设置“里面的数据存储位置选择,获得的是内置sd卡或外置sd卡
*
* @return
*/
public static String getNormalSDCardPath() {
return Environment.getExternalStorageDirectory().getPath();

}

/**
* 获取sd卡路径
* 双sd卡时,获得的是外置sd卡
*
* @return
*/
public static String getSDCardPath() {
String cmd = "cat /proc/mounts";
Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象
BufferedInputStream in = null;
BufferedReader inBr = null;
try {
Process p = run.exec(cmd);// 启动另一个进程来执行命令
in = new BufferedInputStream(p.getInputStream());
inBr = new BufferedReader(new InputStreamReader(in));
String lineStr;
while ((lineStr = inBr.readLine()) != null) {
// 获得命令执行后在控制台的输出信息
//Log.i("CommonUtil:getSDCardPath", lineStr);
//                Log.v("GetPath", "lineStr == " + lineStr);
if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) {
String[] strArray = lineStr.split(" ");
if (strArray != null && strArray.length >= 5) {
String result = strArray[1].replace("/.android_secure", "");
return result;
}
}
// 检查命令是否执行失败。
if (p.waitFor() != 0 && p.exitValue() == 1) {
// p.exitValue()==0表示正常结束,1:非正常结束
//Log.e("CommonUtil:getSDCardPath", "命令执行失败!");
}
}
} catch (Exception e) {
//Log.e("CommonUtil:getSDCardPath", e.toString());
//return Environment.getExternalStorageDirectory().getPath();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
try {
if (inBr != null) {
inBr.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
return Environment.getExternalStorageDirectory().getPath();

//        String path = Environment.getExternalStorageDirectory().getPath();
//        if (path.contains("0")) {
//            path = path.replace("0", "legacy");
//        }
//        return path;
}

//查看所有的sd路径
public String getSDCardPathEx() {
String mount = new String();
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;

if (line.contains("fat")) {
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat("*" + columns[1] + "\n");
}
} else if (line.contains("fuse")) {
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat(columns[1] + "\n");
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mount;
}

//获取当前路径,可用空间
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@SuppressLint("NewApi")
public static long getAvailableSize(String path) {
try {
File base = new File(path);
StatFs stat = new StatFs(base.getPath());

long nAvailableCount = stat.getBlockSizeLong() * (stat.getAvailableBlocksLong());
return nAvailableCount;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}


创建文件

/***
* 创建文件
*/
public static void createFile(String name) {
if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
.getExternalStorageState())) {
String oldsdcardpath = GetPath.getNormalSDCardPath();
String sdcardpath = GetPath.getSDCardPath();
File oldpath = new File(oldsdcardpath + "/test");
File newpath = new File(sdcardpath + "/test");
if (!sdcardpath.equals(oldsdcardpath) && oldpath.exists() && !newpath.exists()) {
sdcardpath = oldsdcardpath;
}
updateDir = new File(sdcardpath + "/test");
updateFile = new File(updateDir + "/" + name + ".apk");

if (!updateDir.exists()) {
updateDir.mkdirs();
}
if (!updateFile.exists()) {
try {
updateFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

}


获取版本号/比较版本号大小

// 取得版本号
public static String GetVersion(Context context) {
try {
PackageInfo manager = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return manager.versionName;
} catch (NameNotFoundException e) {
return "Unknown";
}
}

/**
* 比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0
* @param version1
* @param version2
* @return
*/
public static int compareVersion(String version1, String version2) throws Exception {
if (version1 == null || version2 == null) {
throw new Exception("compareVersion error:illegal params.");
}
String[] versionArray1 = version1.split("\\.");//注意此处为正则匹配,不能用".";
String[] versionArray2 = version2.split("\\.");
int idx = 0;
int minLength = Math.min(versionArray1.length, versionArray2.length);//取最小长度值
int diff = 0;
while (idx < minLength
&& (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0//先比较长度
&& (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {//再比较字符
++idx;
}
//如果已经分出大小,则直接返回,如果未分出大小,则再比较位数,有子版本的为大;
diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
return diff;
}


网络判断

public static boolean networkStatusOK(Context mContext) {
boolean netStatus = false;
try {
ConnectivityManager connectManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectManager.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
if (activeNetworkInfo.isAvailable() && activeNetworkInfo.isConnected()) {
netStatus = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return netStatus;
}

public static boolean isWIFIConn(Context mContext) {
ConnectivityManager connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
return true;
}

return false;
}
/**
* 判断网络是否连接
*
* @param context
* @return
*/
public static boolean isConnected(Context context)
{

ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

if (null != connectivity)
{

NetworkInfo info = connectivity.getActiveNetworkInfo();
if (null != info && info.isConnected())
{
if (info.getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
return false;
}

/**
* 判断是否是wifi连接
*/
public static boolean isWifi(Context context)
{
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

if (cm == null)
return false;
return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

}

/**
* 打开网络设置界面
*/
public static void openSetting(Activity activity)
{
Intent intent = new Intent("/");
ComponentName cm = new ComponentName("com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(cm);
intent.setAction("android.intent.action.VIEW");
activity.startActivityForResult(intent, 0);
}


HTTP请求:GET、POST

/**
* Http请求的工具类
*
* @author
*
*/
public class HttpUtils
{

private static final int TIMEOUT_IN_MILLIONS = 5000;

public interface CallBack
{
void onRequestComplete(String result);
}

/**
* 异步的Get请求
*
* @param urlStr
* @param callBack
*/
public static void doGetAsyn(final String urlStr, final CallBack callBack)
{
new Thread()
{
public void run()
{
try
{
String result = doGet(urlStr);
if (callBack != null)
{
callBack.onRequestComplete(result);
}
} catch (Exception e)
{
e.printStackTrace();
}

};
}.start();
}

/**
* 异步的Post请求
* @param urlStr
* @param params
* @param callBack
* @throws Exception
*/
public static void doPostAsyn(final String urlStr, final String params,
final CallBack callBack) throws Exception
{
new Thread()
{
public void run()
{
try
{
String result = doPost(urlStr, params);
if (callBack != null)
{
callBack.onRequestComplete(result);
}
} catch (Exception e)
{
e.printStackTrace();
}

};
}.start();

}

/**
* Get请求,获得返回数据
*
* @param urlStr
* @return
* @throws Exception
*/
public static String doGet(String urlStr)
{
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try
{
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestMethod("GET");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
if (conn.getResponseCode() == 200)
{
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[128];

while ((len = is.read(buf)) != -1)
{
baos.write(buf, 0, len);
}
baos.flush();
return baos.toString();
} else
{
throw new RuntimeException(" responseCode is not 200 ... ");
}

} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
if (is != null)
is.close();
} catch (IOException e)
{
}
try
{
if (baos != null)
baos.close();
} catch (IOException e)
{
}
conn.disconnect();
}

return null ;

}

/**
* 向指定 URL 发送POST方法的请求
*
* @param url
*            发送请求的 URL
* @param param
*            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
* @throws Exception
*/
public static String doPost(String url, String param)
{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try
{
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl
.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setUseCaches(false);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

if (param != null && !param.trim().equals(""))
{
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += line;
}
} catch (Exception e)
{
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
} catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
}


SharePreferences存储

public class PreferencesUtils {

public static String PREFERENCE_NAME = "Sys_info";

private PreferencesUtils() {
throw new AssertionError();
}

public static boolean putString(Context context, String key, String value) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}

public static String getString(Context context, String key) {
return getString(context, key, null);
}

public static String getString(Context context, String key, String defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getString(key, defaultValue);
}

public static boolean putInt(Context context, String key, int value) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value);
return editor.commit();
}

public static int getInt(Context context, String key) {
return getInt(context, key, -1);
}

public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getInt(key, defaultValue);
}

public static boolean putLong(Context context, String key, long value) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(key, value);
return editor.commit();
}

public static long getLong(Context context, String key) {
return getLong(context, key, -1);
}

public static long getLong(Context context, String key, long defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getLong(key, defaultValue);
}

public static boolean putFloat(Context context, String key, float value) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putFloat(key, value);
return editor.commit();
}

public static float getFloat(Context context, String key) {
return getFloat(context, key, -1);
}

public static float getFloat(Context context, String key, float defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getFloat(key, defaultValue);
}

public static boolean putBoolean(Context context, String key, boolean value) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value);
return editor.commit();
}

public static boolean getBoolean(Context context, String key) {
return getBoolean(context, key, false);
}

public static boolean getBoolean(Context context, String key, boolean defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
return settings.getBoolean(key, defaultValue);
}

//是否包含关键字
public static boolean isContainKey(Context context,String filename,String key){
SharedPreferences settings = context.getSharedPreferences(filename, Context.MODE_PRIVATE);
return settings.contains(key);
}
}


正则表达式:验证手机号、邮箱、QQ、网址、表单

/**
* 使用正则表达式进行表单验证
*/
public class RegexValidateUtils {
static boolean flag = false;
static String regex = "";

public static boolean check(String str, String regex) {
try {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
flag = matcher.matches();
} catch (Exception e) {
flag = false;
}
return flag;
}

/**
* 验证非空
* @return
*/
public static boolean checkNotEmputy(String notEmputy) {
regex = "^\\s*$";
return check(notEmputy, regex) ? false : true;
}

/**
* 验证邮箱
*
* @param email
* @return
*/
public static boolean checkEmail(String email) {
String regex = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
return check(email, regex);
}

/**
* 验证手机号码
* <p>
* 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147
* 联通号码段:130、131、132、136、185、186、145 电信号码段:133、153、180、189
*
* @param cellphone
* @return
*/
public static boolean checkCellphone(String cellphone) {
String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
return check(cellphone, regex);
}

/**
* 验证固话号码
*
* @param telephone
* @return
*/
public static boolean checkTelephone(String telephone) {
String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";
return check(telephone, regex);
}

/**
* 验证传真号码
*
* @param fax
* @return
*/
public static boolean checkFax(String fax) {
String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";
return check(fax, regex);
}

/**
* 验证QQ号码
*
* @param QQ
* @return
*/
public static boolean checkQQ(String QQ) {
String regex = "^[1-9][0-9]{4,}$";
return check(QQ, regex);
}

/**
* 验证网址
* @param keyword
* @return
*/
public static boolean checkUrl(String keyword){
String domainRules = "com.cn|net.cn|org.cn|gov.cn|com.hk|公司|中国|网络|com|net|org|int|edu|gov|mil|arpa|Asia|biz|info|name|pro|coop|aero|museum|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cf|cg|ch|ci|ck|cl|cm|cn|co|cq|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|es|et|ev|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gp|gr|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|ml|mm|mn|mo|mp|mq|mr|ms|mt|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|va|vc|ve|vg|vn|vu|wf|ws|ye|yu|za|zm|zr|zw";

String regex = "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
+ "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
+ "|" // 允许IP和DOMAIN(域名)
+ "(([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]+\\.)?" // 域名- www.
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
+ "("+domainRules+"))" // first level domain- .com or .museum
+ "(:[0-9]{1,4})?" // 端口- :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
Pattern pattern = Pattern.compile(regex);
Matcher isUrl = pattern.matcher(keyword.toLowerCase());
return isUrl.matches();
}


SD卡相关辅助类

/**
* SD卡相关的辅助类
*
* @author zhy
*/
public class SDCardUtils {
private SDCardUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}

/**
* 判断SDCard是否可用
*
* @return
*/
public static boolean isSDCardEnable() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);

}

/**
* 获取SD卡路径
* TODO
* 新修改
*
* @return
*/
public static String getSDCardPath() {
String result = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator;
return result = result.contains("0") ? result.replace("0", "legacy") : result;

//      return Environment.getExternalStorageDirectory().getAbsolutePath()
//              + File.separator;
}

/**
* @param context 磁盘缓存地址
* @return
*/
public static File getDiskCacheDir() {
String filePath = "dugu" + File.separator + "cache";
String saveAddress = SDCardUtils.getSavePath(filePath);
File dir = new File(saveAddress + File.separator);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}

/**
* 文件保存路径
*
* @param filePath
* @return
*/
public static String getSavePath(String filePath) {
return File.separator + "mnt" + File.separator + "sdcard" + File.separator + filePath;
}

/**
* 从httpurl路径中截取文件的文件名
*
* @param url
* @return
*/
public static String getFileName(String url) {
return url.substring(url.lastIndexOf("/") + 1);
}

/**
* 获取SD卡的剩余容量 单位byte
*
* @return
*/
public static long getSDCardAllSize() {
if (isSDCardEnable()) {
StatFs stat = new StatFs(getSDCardPath());
// 获取空闲的数据块的数量
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
// 获取单个数据块的大小(byte)
long freeBlocks = stat.getAvailableBlocks();
return freeBlocks * availableBlocks;
}
return 0;
}

/**
* 获取指定路径所在空间的剩余可用容量字节数,单位byte
*
* @param filePath
* @return 容量字节 SDCard可用空间,内部存储可用空间
*/
public static long getFreeBytes(String filePath) {
// 如果是sd卡的下的路径,则获取sd卡可用容量
if (filePath.startsWith(getSDCardPath())) {
filePath = getSDCardPath();
} else {// 如果是内部存储的路径,则获取内存存储的可用容量
filePath = Environment.getDataDirectory().getAbsolutePath();
}
StatFs stat = new StatFs(filePath);
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
return stat.getBlockSize() * availableBlocks;
}

/**
* 获取系统存储路径
*
* @return
*/
public static String getRootDirectoryPath() {
return Environment.getRootDirectory().getAbsolutePath();
}

}


String工具、编码转换

public class StringUtils {

private StringUtils() {
throw new AssertionError();
}

public static boolean isBlank(String str) {
return (str == null || str.trim().length() == 0);
}

public static boolean isEmpty(CharSequence str) {
return (str == null || str.length() == 0);
}

public static boolean isEquals(String actual, String expected) {
return ObjectUtils.isEquals(actual, expected);
}

public static String nullStrToEmpty(Object str) {
return (str == null ? "" : (str instanceof String ? (String)str : str.toString()));
}

public static String capitalizeFirstLetter(String str) {
if (isEmpty(str)) {
return str;
}

char c = str.charAt(0);
return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str : new StringBuilder(str.length())
.append(Character.toUpperCase(c)).append(str.substring(1)).toString();
}

public static String utf8Encode(String str) {
if (!isEmpty(str) && str.getBytes().length != str.length()) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
}
}
return str;
}

public static String utf8Encode(String str, String defultReturn) {
if (!isEmpty(str) && str.getBytes().length != str.length()) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
return defultReturn;
}
}
return str;
}

public static String getHrefInnerHtml(String href) {
if (isEmpty(href)) {
return "";
}

String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);
Matcher hrefMatcher = hrefPattern.matcher(href);
if (hrefMatcher.matches()) {
return hrefMatcher.group(1);
}
return href;
}

public static String htmlEscapeCharsToString(String source) {
return StringUtils.isEmpty(source) ? source : source.replaceAll("<", "<").replaceAll(">", ">")
.replaceAll("&", "&").replaceAll(""", "\"");
}

public static String fullWidthToHalfWidth(String s) {
if (isEmpty(s)) {
return s;
}

char[] source = s.toCharArray();
for (int i = 0; i < source.length; i++) {
if (source[i] == 12288) {
source[i] = ' ';
// } else if (source[i] == 12290) {
// source[i] = '.';
} else if (source[i] >= 65281 && source[i] <= 65374) {
source[i] = (char)(source[i] - 65248);
} else {
source[i] = source[i];
}
}
return new String(source);
}

public static String halfWidthToFullWidth(String s) {
if (isEmpty(s)) {
return s;
}

char[] source = s.toCharArray();
for (int i = 0; i < source.length; i++) {
if (source[i] == ' ') {
source[i] = (char)12288;
// } else if (source[i] == '.') {
// source[i] = (char)12290;
} else if (source[i] >= 33 && source[i] <= 126) {
source[i] = (char)(source[i] + 65248);
} else {
source[i] = source[i];
}
}
return new String(source);
}

/**
* 通过url获取名称
*
* @param url
* @return
*/
public static String getNameByURL(String url) {
return url.substring(url.lastIndexOf("/") + 1);
}
}


时间、日期工具类

public class TimeUtils {

public static String FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";
public static String FORMAT_YMD = "yyyy-MM-dd";

public static void CheckUpdateTask(Activity mContext) {
long current = System.currentTimeMillis();
Date date = new Date(current);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentStr = sdf.format(date);

String last = PreferencesUtils.getString(mContext, "lastchek");

KJLoger.debug("上次检测版本时间 = " + last);

if (StringUtils.isEmpty(last)) {
PreferencesUtils.putString(mContext,"lastchek",currentStr);
UpdateCheckerUtils.isTip = false;
UpdateCheckerUtils.checkForDialog(mContext, mContext.getString(R.string.check_version_url));

return;
} else {
Date lastDate = null;
long lastTimestamp = 0;
int hours = 0;
try {
lastDate = sdf.parse(last);
lastTimestamp = lastDate.getTime();
hours = (int) (current - lastTimestamp) / 3600 / 1000;
} catch (ParseException e) {
e.printStackTrace();
}

KJLoger.debug("相隔时间 = " + hours);
if (hours >= 24) {
PreferencesUtils.putString(mContext,"lastchek",currentStr);
UpdateCheckerUtils.isTip = false;
UpdateCheckerUtils.checkForDialog(mContext, mContext.getString(R.string.check_version_url));
}
}

}

/**
* 时间戳转换成日期格式字符串
*
* @param seconds   精确到秒的字符串
* @return
*/
public static String timeStamp2Date(String seconds, String format) {
if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
return "";
}
if (format == null || format.isEmpty()) format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new Date(Long.valueOf(seconds + "000")));
}

/**
* 日期格式字符串转换成时间戳
*
* @param format 如:yyyy-MM-dd HH:mm:ss
* @return
*/
public static String date2TimeStamp(String date_str, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return String.valueOf(sdf.parse(date_str).getTime() / 1000);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

/**
* 取得当前时间戳(精确到秒)
*
* @return
*/
public static String timeStamp() {
long time = System.currentTimeMillis();
String t = String.valueOf(time / 1000);
return t;
}

//    其实就是将毫秒数转换为日期
//            具体方法
/**
* 把毫秒转化成日期
* @param dateFormat(日期格式,例如:MM/ dd/yyyy HH:mm:ss)
* @param millSec(毫秒数)
* @return
*/
public static  String transferLongToDate(String dateFormat,Long millSec){
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date date= new Date(millSec);
return sdf.format(date);
}

public static String getDateStr(long millis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
Formatter ft=new Formatter(Locale.CHINA);
return ft.format("%1$tY年%1$tm月%1$td日%1$tA,%1$tT %1$tp", cal).toString();
}

// formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
// data Date类型的时间
public  static String dateToString(Date data, String formatType) {
return new SimpleDateFormat(formatType).format(data);
}

// currentTime要转换的long类型的时间
// formatType要转换的时间格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
public   Date longToDate(long currentTime, String formatType)
throws ParseException {
Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间
String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为string
Date date = stringToDate(sDateTime, formatType); // 把String类型转换为Date类型
return date;
}

// strTime要转换的string类型的时间,formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
// HH时mm分ss秒,
// strTime的时间格式必须要与formatType的时间格式相同
public  static Date stringToDate(String strTime, String formatType)
throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat(formatType);
Date date = null;
try {
date = formatter.parse(strTime);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}

//TJ:工具类
//LS:获取当前时间 年 月 日
public  static String Utils_getDatas() {
SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd");
Date curDate = new Date(System.currentTimeMillis());//获取当前时间
String str = formatter.format(curDate);
return str;
}

//TJ:工具类
//LS:获取当前时间 年 月 日
public  static String Utils_getDatas2() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date curDate = new Date(System.currentTimeMillis());//获取当前时间
String str = formatter.format(curDate);
return str;
}

/**
*  通过Calendar类的日期比较。注意:

  日期是跨年份的,如一个是2012年,一个是2015年的
    年份是分闰年和平年的,各自的天数不同
* date2比date1多的天数
* @param date1
* @param date2
* @return
*
* 只是通过日期来进行比较两个日期的相差天数的比较,没有精确到相差到一天的时间。
* 只是纯粹通过日期(年月日)来比较。
*/
public static int differentDays(Date date1,Date date2)
{
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);

Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
int day1= cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);

int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if(year1 != year2)   //同一年
{
int timeDistance = 0 ;
for(int i = year1 ; i < year2 ; i ++)
{
if(i%4==0 && i%100!=0 || i%400==0)    //闰年
{
timeDistance += 366;
}
else    //不是闰年
{
timeDistance += 365;
}
}

return timeDistance + (day2-day1) ;
}
else    //不同年
{
System.out.println("判断day2 - day1 : " + (day2-day1));
return day2-day1;
}
}

/**直接通过计算两个日期的毫秒数,他们的差除以一天的毫秒数,
* 即可得到我们想要的两个日期相差的天数。
*
* 通过时间秒毫秒数判断两个时间的间隔
* @param date1
* @param date2
* @return
*
* 是通过计算两个日期相差的毫秒数来计算两个日期的天数差的。
* 注意:当他们相差是23个小时的时候,它就不算一天了。
*/
public static int differentDaysByMillisecond(Date date1,Date date2)
{
int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
return days;
}

}


避免短时间内按钮重复点击操作

/**
* 避免短时间内重复点击
* @return
*/
private static long lastClickTime;
public static boolean isFastDoubleClick() {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if ( 0 < timeD && timeD < 2000) {
return true;
}
lastClickTime = time;
return false;
}


吐司(Toast)工具类

public class ToastUtils {

private ToastUtils() {
throw new AssertionError();
}

public static void show(Context context, int resId) {
show(context, context.getResources().getText(resId), Toast.LENGTH_SHORT);
}

public static void show(Context context, int resId, int duration) {
show(context, context.getResources().getText(resId), duration);
}

public static void show(Context context, CharSequence text) {
show(context, text, Toast.LENGTH_SHORT);
}

public static void show(Context context, CharSequence text, int duration) {
Toast.makeText(context, text, duration).show();
}

public static void show(Context context, int resId, Object... args) {
show(context, String.format(context.getResources().getString(resId), args), Toast.LENGTH_SHORT);
}

public static void show(Context context, String format, Object... args) {
show(context, String.format(format, args), Toast.LENGTH_SHORT);
}

public static void show(Context context, int resId, int duration, Object... args) {
show(context, String.format(context.getResources().getString(resId), args), duration);
}

public static void show(Context context, String format, int duration, Object... args) {
show(context, String.format(format, args), duration);
}
}


图片工具类

public class Tools {
/**
* 检查SDCard
*
* @return
*/
public static boolean hasSdcard() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}

/**
* 压缩图片
*
* @return
*/
public static byte[] decodeBitmap(String path) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;// 设置成了true,不占用内存,只获取bitmap宽高
BitmapFactory.decodeFile(path, opts);
opts.inSampleSize = computeSampleSize(opts, -1, 1024 * 800);
opts.inJustDecodeBounds = false;// 这里一定要将其设置回false,因为之前我们将其设置成了true
opts.inPurgeable = true;
opts.inInputShareable = true;
opts.inDither = false;
opts.inPurgeable = true;
opts.inTempStorage = new byte[16 * 1024];
FileInputStream is = null;
Bitmap bmp = null;
ByteArrayOutputStream baos = null;
try {
is = new FileInputStream(path);
bmp = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);
double scale = getScaling(opts.outWidth * opts.outHeight,
1024 * 600);
Bitmap bmp2 = Bitmap.createScaledBitmap(bmp,
(int) (opts.outWidth * scale),
(int) (opts.outHeight * scale), true);
bmp.recycle();
baos = new ByteArrayOutputStream();
bmp2.compress(CompressFormat.JPEG, 100, baos);
bmp2.recycle();
return baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
System.gc();
}
return baos.toByteArray();
}

private static double getScaling(int src, int des) {
/**
* 48 目标尺寸÷原尺寸 sqrt开方,得出宽高百分比 49
*/
double scale = Math.sqrt((double) des / (double) src);
return scale;
}

public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);

int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}

return roundedSize;
}

private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;

int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
Math.floor(w / minSideLength), Math.floor(h / minSideLength));

if (upperBound < lowerBound) {
return lowerBound;
}

if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}

// 压缩图片
public static Bitmap getSmallBitmap(String filePath) {

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 400, 400);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;

Bitmap bm = BitmapFactory.decodeFile(filePath, options);
if (bm == null) {
return null;
}
int degree = readPictureDegree(filePath);
bm = rotateBitmap(bm, degree);
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 80, baos);

} finally {
try {
if (baos != null)
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bm;

}

private static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
if (bitmap == null)
return null;

int w = bitmap.getWidth();
int h = bitmap.getHeight();

// Setting post rotate to 90
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}

private static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}

private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
}

return inSampleSize;
}

/**
* 下载图片
*/
public static void saveImageToGallery(Context context, Bitmap bmp) {
File file;
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), "xiaoshuidi");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
ToastUtils.show(context, "下载成功");
} catch (FileNotFoundException e) {
e.printStackTrace();
ToastUtils.show(context, "下载失败");
} finally {
bmp.recycle();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
}


unicode 和中文: 互转编码

//LS:添加 的中文 和 unicode 相互转化

public static String unicodeToCn(String unicode) { //LS: unicode 转中文
/** 以 \ u 分割,因为java注释也能识别unicode,因此中间加了一个空格*/
String[] strs = unicode.split("\\\\u");
String returnStr = "";
// 由于unicode字符串以 \ u 开头,因此分割出的第一个字符是""。
for (int i = 1; i < strs.length; i++) {
returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
}
return returnStr;
}

public static String cnToUnicode(String cn) {//LS:中文转 unicode
char[] chars = cn.toCharArray();
String returnStr = "";
for (int i = 0; i < chars.length; i++) {
returnStr += "\\u" + Integer.toString(chars[i], 16);
}
return returnStr;
}


视频毫秒转:时、分、秒

//设置时间
public static String setTime(long total) {
long hour = total / (1000 * 60 * 60);
long letf1 = total % (1000 * 60 * 60);
long minute = letf1 / (1000 * 60);
long left2 = letf1 % (1000 * 60);
long second = left2 / 1000;

return hour + "'" + minute + "'" + second + "''";
}


byte(字节)根据长度转成kb(千字节)和mb(兆字节)

/**
* byte(字节)根据长度转成kb(千字节)和mb(兆字节)
*
* @param bytes
* @return
*/
public static String bytes2kb(long bytes) {
BigDecimal filesize = new BigDecimal(bytes);
BigDecimal megabyte = new BigDecimal(1024 * 1024);
BigDecimal megabyteGB = new BigDecimal(1024 * 1024*1024);
float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)  //LS:2:表示是小数点后面的位数; BigDecimal.ROUND_UP:表示四舍五入
.floatValue();

float returnValueGB = filesize.divide(megabyteGB, 2, BigDecimal.ROUND_UP)  //LS:2:表示是小数点后面的位数; BigDecimal.ROUND_UP:表示四舍五入
.floatValue();

if(returnValueGB > 1){
returnValue = returnValueGB;
return (returnValue + "GB");

}
else if (returnValue > 1)
{return (returnValue + "MB");}
BigDecimal kilobyte = new BigDecimal(1024);
returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
.floatValue();
return (returnValue + "KB");
}


获取手机唯一码:IMEI+MAC

/**
* TJ:IMEI+MAC
* 获取设备唯一码,并用MD5加密
*摘掉了加密操作:SHA不可逆
* @param con
* @return
*/
public static String getDeviceKey(Context con) {
WifiManager wm = (WifiManager) con.getSystemService(Context.WIFI_SERVICE);
String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
if (m_szWLANMAC == null) {
m_szWLANMAC = "";
}
TelephonyManager TelephonyMgr = (TelephonyManager) con.getSystemService(con.TELEPHONY_SERVICE);
String szImei = TelephonyMgr.getDeviceId();
if (szImei == null) {
szImei = "";
}

String getNewNum = null;
try {
getNewNum =  szImei + m_szWLANMAC;//摘掉了加密操作:SHA不可逆
} catch (Exception e) {
e.printStackTrace();
}
return getNewNum;

}


身份证工具类

/**
* 身份证工具类
*/
public class IdcardUtils {

/** 中国公民身份证号码最小长度。 */
public static final int CHINA_ID_MIN_LENGTH = 15;

/** 中国公民身份证号码最大长度。 */
public static final int CHINA_ID_MAX_LENGTH = 18;

/** 省、直辖市代码表 */
public static final String cityCode[] = {
"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"
};

/** 每位加权因子 */
public static final int power[] = {
7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2
};

/** 第18位校检码 */
public static final String verifyCode[] = {
"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"
};
/** 最低年限 */
public static final int MIN = 1930;
public static Map<String, String> cityCodes = new HashMap<String, String>();
/** 台湾身份首字母对应数字 */
public static Map<String, Integer> twFirstCode = new HashMap<String, Integer>();
/** 香港身份首字母对应数字 */
public static Map<String, Integer> hkFirstCode = new HashMap<String, Integer>();
static {
cityCodes.put("11", "北京");
cityCodes.put("12", "天津");
cityCodes.put("13", "河北");
cityCodes.put("14", "山西");
cityCodes.put("15", "内蒙古");
cityCodes.put("21", "辽宁");
cityCodes.put("22", "吉林");
cityCodes.put("23", "黑龙江");
cityCodes.put("31", "上海");
cityCodes.put("32", "江苏");
cityCodes.put("33", "浙江");
cityCodes.put("34", "安徽");
cityCodes.put("35", "福建");
cityCodes.put("36", "江西");
cityCodes.put("37", "山东");
cityCodes.put("41", "河南");
cityCodes.put("42", "湖北");
cityCodes.put("43", "湖南");
cityCodes.put("44", "广东");
cityCodes.put("45", "广西");
cityCodes.put("46", "海南");
cityCodes.put("50", "重庆");
cityCodes.put("51", "四川");
cityCodes.put("52", "贵州");
cityCodes.put("53", "云南");
cityCodes.put("54", "西藏");
cityCodes.put("61", "陕西");
cityCodes.put("62", "甘肃");
cityCodes.put("63", "青海");
cityCodes.put("64", "宁夏");
cityCodes.put("65", "新疆");
cityCodes.put("71", "台湾");
cityCodes.put("81", "香港");
cityCodes.put("82", "澳门");
cityCodes.put("91", "国外");
twFirstCode.put("A", 10);
twFirstCode.put("B", 11);
twFirstCode.put("C", 12);
twFirstCode.put("D", 13);
twFirstCode.put("E", 14);
twFirstCode.put("F", 15);
twFirstCode.put("G", 16);
twFirstCode.put("H", 17);
twFirstCode.put("J", 18);
twFirstCode.put("K", 19);
twFirstCode.put("L", 20);
twFirstCode.put("M", 21);
twFirstCode.put("N", 22);
twFirstCode.put("P", 23);
twFirstCode.put("Q", 24);
twFirstCode.put("R", 25);
twFirstCode.put("S", 26);
twFirstCode.put("T", 27);
twFirstCode.put("U", 28);
twFirstCode.put("V", 29);
twFirstCode.put("X", 30);
twFirstCode.put("Y", 31);
twFirstCode.put("W", 32);
twFirstCode.put("Z", 33);
twFirstCode.put("I", 34);
twFirstCode.put("O", 35);
hkFirstCode.put("A", 1);
hkFirstCode.put("B", 2);
hkFirstCode.put("C", 3);
hkFirstCode.put("R", 18);
hkFirstCode.put("U", 21);
hkFirstCode.put("Z", 26);
hkFirstCode.put("X", 24);
hkFirstCode.put("W", 23);
hkFirstCode.put("O", 15);
hkFirstCode.put("N", 14);
}

/**
* 将15位身份证号码转换为18位
*
* @param idCard
*            15位身份编码
* @return 18位身份编码
*/
public static String conver15CardTo18(String idCard) {
String idCard18 = "";
if (idCard.length() != CHINA_ID_MIN_LENGTH) {
return null;
}
if (isNum(idCard)) {
// 获取出生年月日
String birthday = idCard.substring(6, 12);
Date birthDate = null;
try {
birthDate = new SimpleDateFormat("yyMMdd").parse(birthday);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
if (birthDate != null)
cal.setTime(birthDate);
// 获取出生年(完全表现形式,如:2010)
String sYear = String.valueOf(cal.get(Calendar.YEAR));
idCard18 = idCard.substring(0, 6) + sYear + idCard.substring(8);
// 转换字符数组
char[] cArr = idCard18.toCharArray();
if (cArr != null) {
int[] iCard = converCharToInt(cArr);
int iSum17 = getPowerSum(iCard);
// 获取校验位
String sVal = getCheckCode18(iSum17);
if (sVal.length() > 0) {
idCard18 += sVal;
} else {
return null;
}
}
} else {
return null;
}
return idCard18;
}

/**
* 验证身份证是否合法
*/
public static boolean validateCard(String idCard) {
String card = idCard.trim();
if (validateIdCard18(card)) {
return true;
}
if (validateIdCard15(card)) {
return true;
}
String[] cardval = validateIdCard10(card);
if (cardval != null) {
if (cardval[2].equals("true")) {
return true;
}
}
return false;
}

/**
* 验证18位身份编码是否合法
*
* @param idCard 身份编码
* @return 是否合法
*/
public static boolean validateIdCard18(String idCard) {
boolean bTrue = false;
if (idCard.length() == CHINA_ID_MAX_LENGTH) {
// 前17位
String code17 = idCard.substring(0, 17);
// 第18位
String code18 = idCard.substring(17, CHINA_ID_MAX_LENGTH);
if (isNum(code17)) {
char[] cArr = code17.toCharArray();
if (cArr != null) {
int[] iCard = converCharToInt(cArr);
int iSum17 = getPowerSum(iCard);
// 获取校验位
String val = getCheckCode18(iSum17);
if (val.length() > 0) {
if (val.equalsIgnoreCase(code18)) {
bTrue = true;
}
}
}
}
}
return bTrue;
}

/**
* 验证15位身份编码是否合法
*
* @param idCard
*            身份编码
* @return 是否合法
*/
public static boolean validateIdCard15(String idCard) {
if (idCard.length() != CHINA_ID_MIN_LENGTH) {
return false;
}
if (isNum(idCard)) {
String proCode = idCard.substring(0, 2);
if (cityCodes.get(proCode) == null) {
return false;
}
String birthCode = idCard.substring(6, 12);
Date birthDate = null;
try {
birthDate = new SimpleDateFormat("yy").parse(birthCode.substring(0, 2));
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
if (birthDate != null)
cal.setTime(birthDate);
if (!valiDate(cal.get(Calendar.YEAR), Integer.valueOf(birthCode.substring(2, 4)),
Integer.valueOf(birthCode.substring(4, 6)))) {
return false;
}
} else {
return false;
}
return true;
}

/**
* 验证10位身份编码是否合法
*
* @param idCard 身份编码
* @return 身份证信息数组
*         <p>
*         [0] - 台湾、澳门、香港 [1] - 性别(男M,女F,未知N) [2] - 是否合法(合法true,不合法false)
*         若不是身份证件号码则返回null
*         </p>
*/
public static String[] validateIdCard10(String idCard) {
String[] info = new String[3];
String card = idCard.replaceAll("[\\(|\\)]", "");
if (card.length() != 8 && card.length() != 9 && idCard.length() != 10) {
return null;
}
if (idCard.matches("^[a-zA-Z][0-9]{9}$")) { // 台湾
info[0] = "台湾";
System.out.println("11111");
String char2 = idCard.substring(1, 2);
if (char2.equals("1")) {
info[1] = "M";
System.out.println("MMMMMMM");
} else if (char2.equals("2")) {
info[1] = "F";
System.out.println("FFFFFFF");
} else {
info[1] = "N";
info[2] = "false";
System.out.println("NNNN");
return info;
}
info[2] = validateTWCard(idCard) ? "true" : "false";
} else if (idCard.matches("^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$")) { // 澳门
info[0] = "澳门";
info[1] = "N";
// TODO
} else if (idCard.matches("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")) { // 香港
info[0] = "香港";
info[1] = "N";
info[2] = validateHKCard(idCard) ? "true" : "false";
} else {
return null;
}
return info;
}

/**
* 验证台湾身份证号码
*
* @param idCard
*            身份证号码
* @return 验证码是否符合
*/
public static boolean validateTWCard(String idCard) {
String start = idCard.substring(0, 1);
String mid = idCard.substring(1, 9);
String end = idCard.substring(9, 10);
Integer iStart = twFirstCode.get(start);
Integer sum = iStart / 10 + (iStart % 10) * 9;
char[] chars = mid.toCharArray();
Integer iflag = 8;
for (char c : chars) {
sum = sum + Integer.valueOf(c + "") * iflag;
iflag--;
}
return (sum % 10 == 0 ? 0 : (10 - sum % 10)) == Integer.valueOf(end) ? true : false;
}

/**
* 验证香港身份证号码(存在Bug,部份特殊身份证无法检查)
* <p>
* 身份证前2位为英文字符,如果只出现一个英文字符则表示第一位是空格,对应数字58 前2位英文字符A-Z分别对应数字10-35
* 最后一位校验码为0-9的数字加上字符"A","A"代表10
* </p>
* <p>
* 将身份证号码全部转换为数字,分别对应乘9-1相加的总和,整除11则证件号码有效
* </p>
*
* @param idCard 身份证号码
* @return 验证码是否符合
*/
public static boolean validateHKCard(String idCard) {
String card = idCard.replaceAll("[\\(|\\)]", "");
Integer sum = 0;
if (card.length() == 9) {
sum = (Integer.valueOf(card.substring(0, 1).toUpperCase().toCharArray()[0]) - 55) * 9
+ (Integer.valueOf(card.substring(1, 2).toUpperCase().toCharArray()[0]) - 55) * 8;
card = card.substring(1, 9);
} else {
sum = 522 + (Integer.valueOf(card.substring(0, 1).toUpperCase().toCharArray()[0]) - 55) * 8;
}
String mid = card.substring(1, 7);
String end = card.substring(7, 8);
char[] chars = mid.toCharArray();
Integer iflag = 7;
for (char c : chars) {
sum = sum + Integer.valueOf(c + "") * iflag;
iflag--;
}
if (end.toUpperCase().equals("A")) {
sum = sum + 10;
} else {
sum = sum + Integer.valueOf(end);
}
return (sum % 11 == 0) ? true : false;
}

/**
* 将字符数组转换成数字数组
*
* @param ca
*            字符数组
* @return 数字数组
*/
public static int[] converCharToInt(char[] ca) {
int len = ca.length;
int[] iArr = new int[len];
try {
for (int i = 0; i < len; i++) {
iArr[i] = Integer.parseInt(String.valueOf(ca[i]));
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return iArr;
}

/**
* 将身份证的每位和对应位的加权因子相乘之后,再得到和值
*
* @param iArr
* @return 身份证编码。
*/
public static int getPowerSum(int[] iArr) {
int iSum = 0;
if (power.length == iArr.length) {
for (int i = 0; i < iArr.length; i++) {
for (int j = 0; j < power.length; j++) {
if (i == j) {
iSum = iSum + iArr[i] * power[j];
}
}
}
}
return iSum;
}

/**
* 将power和值与11取模获得余数进行校验码判断
*
* @param iSum
* @return 校验位
*/
public static String getCheckCode18(int iSum) {
String sCode = "";
switch (iSum % 11) {
case 10:
sCode = "2";
break;
case 9:
sCode = "3";
break;
case 8:
sCode = "4";
break;
case 7:
sCode = "5";
break;
case 6:
sCode = "6";
break;
case 5:
sCode = "7";
break;
case 4:
sCode = "8";
break;
case 3:
sCode = "9";
break;
case 2:
sCode = "x";
break;
case 1:
sCode = "0";
break;
case 0:
sCode = "1";
break;
}
return sCode;
}

/**
* 根据身份编号获取年龄
*
* @param idCard
*            身份编号
* @return 年龄
*/
public static int getAgeByIdCard(String idCard) {
int iAge = 0;
if (idCard.length() == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
String year = idCard.substring(6, 10);
Calendar cal = Calendar.getInstance();
int iCurrYear = cal.get(Calendar.YEAR);
iAge = iCurrYear - Integer.valueOf(year);
return iAge;
}

/**
* 根据身份编号获取生日
*
* @param idCard 身份编号
* @return 生日(yyyyMMdd)
*/
public static String getBirthByIdCard(String idCard) {
Integer len = idCard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
return idCard.substring(6, 14);
}

/**
* 根据身份编号获取生日年
*
* @param idCard 身份编号
* @return 生日(yyyy)
*/
public static Short getYearByIdCard(String idCard) {
Integer len = idCard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
return Short.valueOf(idCard.substring(6, 10));
}

/**
* 根据身份编号获取生日月
*
* @param idCard
*            身份编号
* @return 生日(MM)
*/
public static Short getMonthByIdCard(String idCard) {
Integer len = idCard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
return Short.valueOf(idCard.substring(10, 12));
}

/**
* 根据身份编号获取生日天
*
* @param idCard
*            身份编号
* @return 生日(dd)
*/
public static Short getDateByIdCard(String idCard) {
Integer len = idCard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
return Short.valueOf(idCard.substring(12, 14));
}

/**
* 根据身份编号获取性别
*
* @param idCard 身份编号
* @return 性别(M-男,F-女,N-未知)
*/
public static String getGenderByIdCard(String idCard) {
String sGender = "N";
if (idCard.length() == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
String sCardNum = idCard.substring(16, 17);
if (Integer.parseInt(sCardNum) % 2 != 0) {
sGender = "M";
} else {
sGender = "F";
}
return sGender;
}

/**
* 根据身份编号获取户籍省份
*
* @param idCard 身份编码
* @return 省级编码。
*/
public static String getProvinceByIdCard(String idCard) {
int len = idCard.length();
String sProvince = null;
String sProvinNum = "";
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
sProvinNum = idCard.substring(0, 2);
}
sProvince = cityCodes.get(sProvinNum);
return sProvince;
}

/**
* 数字验证
*
* @param val
* @return 提取的数字。
*/
public static boolean isNum(String val) {
return val == null || "".equals(val) ? false : val.matches("^[0-9]*$");
}

/**
* 验证小于当前日期 是否有效
*
* @param iYear
*            待验证日期(年)
* @param iMonth
*            待验证日期(月 1-12)
* @param iDate
*            待验证日期(日)
* @return 是否有效
*/
public static boolean valiDate(int iYear, int iMonth, int iDate) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int datePerMonth;
if (iYear < MIN || iYear >= year) {
return false;
}
if (iMonth < 1 || iMonth > 12) {
return false;
}
switch (iMonth) {
case 4:
case 6:
case 9:
case 11:
datePerMonth = 30;
break;
case 2:
boolean dm = ((iYear % 4 == 0 && iYear % 100 != 0) || (iYear % 400 == 0))
&& (iYear > MIN && iYear < year);
datePerMonth = dm ? 29 : 28;
break;
default:
datePerMonth = 31;
}
return (iDate >= 1) && (iDate <= datePerMonth);
}
}


持续更新中…欢迎指正学习。

能够获取你的认可是我最大的动力!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息