直接上代码
package com.xxx.utils;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.ktc.base.SczwApplication;
import com.ktc.sczwdemo.R;
/**
* @Date 2016-5-15 下午3:27:07
* @Author Arvin
* @Description 工具类
*/
public class ToolUtils {
private static final String TAG = ToolUtils.class.getSimpleName();
public static Context getContext() {
return SczwApplication.getContext();
}
/**
* 得到Resource对象
*/
public static Resources getResources() {
return getContext().getResources();
}
/**
* @Description 获得应用的包名
* @param null
* @return String
* @throws
*/
public static String getPackageName() {
return getContext().getPackageName();
}
/**
* @Description 格式化空间大小
* @param double
* @return String
* @throws
*/
public static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "B";
}
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";
}
/**
* @Description 获取缓存空间cache大小
* @param null
* @return String
* @throws Exception
*/
public static String getCacheSize() throws Exception {
return getFormatSize(getFolderSize(getContext().getExternalCacheDir()));
}
/**
* @Description 获取cache路径空间大小
* @param File
* @return long
* @throws Exception
*/
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;
}
/**
* @Description 清除应用缓存,即删除data/data/packageName/cache目录下文件
* @param null
* @return null
* @throws
*/
public static void clearCache(){
(new Thread(){
@Override
public void run() {
try {
File path = getContext().getCacheDir();
if(path ==null)
return;
String killer =" rm -r " + path.toString();
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os =new DataOutputStream(p.getOutputStream());
os.writeBytes(killer.toString() +"\n");
os.writeBytes("exit\n");
os.flush();
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
/**
* @Description 获取屏幕大小
* @param null
* @return int
* @throws
*/
public static Screen getScreenPix() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
return new Screen(dm.widthPixels, dm.heightPixels);
}
/**
* @Description 获取屏幕宽度
* @param null
* @return int
* @throws
*/
public static int getScreenWidthPix() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
return new Screen(dm.widthPixels, dm.heightPixels).widthPixels;
}
/**
* @Description 获取屏幕高度
* @param null
* @return int
* @throws
*/
public static int getScreenHeightPix() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
return new Screen(dm.widthPixels, dm.heightPixels).heightPixels;
}
/**
* @Description 定义一个screen类型
* @param tags
* @return return_type
* @throws
*/
public static class Screen {
public int widthPixels;
public int heightPixels;
public Screen() {
}
public Screen(int widthPixels, int heightPixels) {
this.widthPixels = widthPixels;
this.heightPixels = heightPixels;
}
@Override
public String toString() {
return "(" + widthPixels + "," + heightPixels + ")";
}
}
/**
* @Description 判断注册邮箱是否填写规范
* @param String
* @return boolean
* @throws
*/
public static boolean emailFormat(String email) {
boolean tag = true;
final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
final Pattern pattern = Pattern.compile(pattern1);
final Matcher mat = pattern.matcher(email);
if (!mat.find()) {
tag = false;
}
return tag;
}
/**
* @Description 判断是否存在SDcard
* @param null
* @return boolean
* @throws
*/
public static boolean hasSdcard() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
/**
* @Description 定义Toast(string)
* @param int
* @return null
* @throws
*/
public static void showToast(String msg) {
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}
/**
* @Description 定义Toast(id)
* @param int
* @return null
* @throws
*/
public static void showToast(int msg) {
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}
/**
* @Description 验证字符串是否为空 或 ""
* @param int
* @return null
* @throws
*/
public static boolean validateString(String str) {
if (str != null && !"".equals(str.trim()))
return false;
return true;
}
/**
* @Description 获得渠道号(推广平台0=本站,1=安智,2=机锋,3=安卓官方)
* @param null
* @return String
* @throws
*/
public static String getChannelCode() {
String channelCode = "0";
try {
ApplicationInfo ai = getContext().getPackageManager()
.getApplicationInfo(getContext().getPackageName(),
PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
if (bundle != null) {
Object obj = bundle.get("UMENG_CHANNEL");
if (obj != null) {
channelCode = obj.toString();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return channelCode;
}
/**
* @Description 检查网络是否可用
* @param null
* @return boolean
* @throws
*/
public static boolean isConnect() {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
try {
ConnectivityManager connectivity = (ConnectivityManager) getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
// 获取网络连接管理的对象
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 判断当前网络是否已经连接
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
} catch (Exception e) {
Log.v("error", e.toString());
}
return false;
}
/**
* @Description 对图片的大小进行判断,并得到合适的缩放比例,比如2即1/2,3即1/3
* @param BitmapFactory.Options options,int minSideLength, int maxNumOfPixels
* @return int
* @throws
*/
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) ? 80 : (int) Math.min(
Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
/**
* @Description MD5加密
* @param String
* @return String
* @throws
*/
public static String encryption(String enc) {
String md5 = null;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] bs = enc.getBytes();
digest.update(bs);
md5 = byte2hex(digest.digest());
Log.i("md5", md5);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return md5;
}
private static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0xFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs;
}
/**
* @Description 以md5方式加密字符串
* @param 默认32位长度
* @return String
* @throws
*/
public static String getMd5() {
try {
String content = Constants.MD5_HEAD+getIMEI();
MessageDigest bmd5 = MessageDigest.getInstance("MD5");
bmd5.update(content.getBytes());
int i;
StringBuffer buf = new StringBuffer();
byte[] b = bmd5.digest();
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
return buf.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
/**
* @Description 以md5方式加密字符串;返回的长度,支持16位和32位,例length=16,length=32
* @param String
* @return String
* @throws
*/
public static String getMd5(String content, int length) {
try {
MessageDigest bmd5 = MessageDigest.getInstance("MD5");
bmd5.update(content.getBytes());
int i;
StringBuffer buf = new StringBuffer();
byte[] b = bmd5.digest();
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
String md5Content = buf.toString();
switch (length) {
case 16:
md5Content = md5Content.substring(0, 16);
break;
case 32:
default:
break;
}
return md5Content;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public ByteArrayOutputStream getByteArrayOutputStreamByInputStream(
InputStream inputStream) throws Exception {
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
return byteArrayOutputStream;
}
/**
* @Description 切换白天和夜间模式
* @param Window 当前的Window窗体;boolean是否是夜间模式
* @return null
* @throws
*/
public void setScreenBrightness(Window window, boolean isNightModel) {
WindowManager.LayoutParams lp = window.getAttributes();
if (isNightModel) {
lp.screenBrightness = 0.4f;
} else {
lp.screenBrightness = 1.0f;
}
window.setAttributes(lp);
}
/**
* @Description 获取当前日期
* @param null
* @return String:2016-05-13
* @throws
*/
public static String getCurrentDate() {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
return mYear + "-" + mMonth + "-" + mDay;
}
/**
* @Description 获取6位随机数字
* @param null
* @return int
* @throws
*/
public static int getSixNum() {
int numcode = (int) ((Math.random() * 9 + 1) * 100000);
return numcode;
}
public static String getNumberFromString(String str) {
String str2 = "";
if (str != null && !"".equals(str)) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
str2 += str.charAt(i);
}
}
}
return str2;
}
/**
* @Description 判断网络状态
* @param null
* @return boolean
* @throws
*/
public static boolean checkNet() {
ConnectivityManager manager = (ConnectivityManager) getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return true;
}
return false;
}
public static String getAPN() {
String apn = "";
ConnectivityManager manager = (ConnectivityManager) getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
if (ConnectivityManager.TYPE_WIFI == info.getType()) {
apn = info.getTypeName();
if (apn == null) {
apn = "wifi";
}
} else {
apn = info.getExtraInfo().toLowerCase();
if (apn == null) {
apn = "mobile";
}
}
}
return apn;
}
public static String getModel() {
return Build.MODEL;
}
public static String getManufacturer() {
return Build.MANUFACTURER;
}
public static String getFirmware() {
return Build.VERSION.RELEASE;
}
/**
* @Description 获取设备SDK版本号
* @param null
* @return String
* @throws
*/
public static String getSDKVer() {
return Integer.valueOf(Build.VERSION.SDK_INT).toString();
}
/**
* @Description 获取当前语言类型
* @param null
* @return String
* @throws
*/
public static String getLanguage() {
Locale locale = Locale.getDefault();
String languageCode = locale.getLanguage();
if (TextUtils.isEmpty(languageCode)) {
languageCode = "";
}
return languageCode;
}
/**
* @Description 获取当前国家码
* @param null
* @return String
* @throws
*/
public static String getCountry() {
Locale locale = Locale.getDefault();
String countryCode = locale.getCountry();
if (TextUtils.isEmpty(countryCode)) {
countryCode = "";
}
return countryCode;
}
/**
* @Description 获取IMEI号码
* @param null
* @return String
* @throws
*/
public static String getIMEI() {
TelephonyManager mTelephonyMgr = (TelephonyManager) getContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String imei = mTelephonyMgr.getDeviceId();
if (TextUtils.isEmpty(imei) || imei.equals("000000000000000")) {
imei = "0";
}
return imei;
}
/**
* @Description 获取到客户ID,即IMSI
* @param null
* @return String
* @throws
*/
public static String getIMSI() {
TelephonyManager mTelephonyMgr = (TelephonyManager) getContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String imsi = mTelephonyMgr.getSubscriberId();
if (TextUtils.isEmpty(imsi)) {
return "0";
} else {
return imsi;
}
}
/**
* @Description 获取本机手机号
* @param null
* @return String
* @throws
*/
public static String getLine1Number(){
TelephonyManager telephonyManager=(TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
String imei=telephonyManager.getLine1Number();
return imei;
}
/**
* @Description 获取网络运营商代号
* @param null
* @return String
* @throws
*/
public static String getMcnc() {
TelephonyManager tm = (TelephonyManager) getContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String mcnc = tm.getNetworkOperator();
if (TextUtils.isEmpty(mcnc)) {
return "0";
} else {
return mcnc;
}
}
/**
* @Description 获取手机的sdk版本号
* @param null
* @return int
* @throws
*/
public static int getPhoneSDK() {
TelephonyManager phoneMgr = (TelephonyManager) getContext()
.getSystemService(Context.TELEPHONY_SERVICE);
Logger.i(TAG, "Bild model:" + Build.MODEL);
Logger.i(TAG, "Phone Number:" + phoneMgr.getLine1Number());
Logger.i(TAG, "SDK VERSION:" + Build.VERSION.SDK);
Logger.i(TAG, "SDK RELEASE:" + Build.VERSION.RELEASE);
int sdk = 7;
try {
sdk = Integer.parseInt(Build.VERSION.SDK);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return sdk;
}
public static Object getMetaData(String keyName) {
try {
ApplicationInfo info = getContext().getPackageManager()
.getApplicationInfo(getContext().getPackageName(),
PackageManager.GET_META_DATA);
Bundle bundle = info.metaData;
Object value = bundle.get(keyName);
return value;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* @Description 获取应用版本信息
* @param null
* @return String
* @throws
*/
public static String getAppVersion() {
PackageManager pm = getContext().getPackageManager();
PackageInfo pi;
try {
pi = pm.getPackageInfo(getContext().getPackageName(), 0);
String versionName = pi.versionName;
return versionName;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* 判断SDCard是否已满
*
* @return
*/
public static boolean isSDCardSizeOverflow() {
boolean result = false;
// 取得SDCard当前的状态
String sDcString = android.os.Environment.getExternalStorageState();
if (sDcString.equals(android.os.Environment.MEDIA_MOUNTED)) {
// 取得sdcard文件路径
File pathFile = android.os.Environment
.getExternalStorageDirectory();
android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());
// 获取SDCard上BLOCK总数
long nTotalBlocks = statfs.getBlockCount();
// 获取SDCard上每个block的SIZE
long nBlocSize = statfs.getBlockSize();
// 获取可供程序使用的Block的数量
long nAvailaBlock = statfs.getAvailableBlocks();
// 获取剩下的所有Block的数量(包括预留的一般程序无法使用的块)
long nFreeBlock = statfs.getFreeBlocks();
// 计算SDCard 总容量大小MB
long nSDTotalSize = nTotalBlocks * nBlocSize / 1024 / 1024;
// 计算 SDCard 剩余大小MB
long nSDFreeSize = nAvailaBlock * nBlocSize / 1024 / 1024;
if (nSDFreeSize <= 1) {
result = true;
}
}// end of if
// end of func
return result;
}
/**
* @Description 格式化时间
* @param Long
* @return String
* @throws
*/
public static String getFomatTime(Long time){
SimpleDateFormat format=new SimpleDateFormat(ResUtils.getString(R.string.time_format));
Date date = new Date(time);
String time_str = format.format(date);
return time_str;
}
/**
* @Description 判断字符串是否是邮箱格式
* @param String
* @return Boolean
* @throws
*/
public static boolean checkEmail(String str) {
Boolean isEmail = false;
String expr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
if (str.matches(expr)) {
isEmail = true;
}
return isEmail;
}
/**
* @Description 判断字符串是否是银行卡号
* @param String
* @return Boolean
* @throws
*/
public static boolean checkBankCard(String cardId) {
char bit = getBankCardCheckCode(cardId
.substring(0, cardId.length() - 1));
if (bit == 'N') {
return false;
}
return cardId.charAt(cardId.length() - 1) == bit;
}
private static char getBankCardCheckCode(String nonCheckCodeCardId) {
if (nonCheckCodeCardId == null
|| nonCheckCodeCardId.trim().length() == 0
|| !nonCheckCodeCardId.matches("\\d+")) {
// 如果传的不是数据返回N
return 'N';
}
char[] chs = nonCheckCodeCardId.trim().toCharArray();
int luhmSum = 0;
for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
int k = chs[i] - '0';
if (j % 2 == 0) {
k *= 2;
k = k / 10 + k % 10;
}
luhmSum += k;
}
return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
}
/**
* @Description 判断字符串是否是手机号
* @param String
* @return Boolean
* @throws
*/
public static boolean checkPhone(String phone) {
Pattern pattern = Pattern
.compile("^(13[0-9]|15[0-9]|153|15[6-9]|180|18[23]|18[5-9])\\d{8}$");
Matcher matcher = pattern.matcher(phone);
if (matcher.matches()) {
return true;
}
return false;
}
/**
* @Description 在指定文件夹中创建文件
* @param tags
* @return return_type
* @throws
*/
public static void makeNewFile(String filePath){
if(hasSdcard()&&!isSDCardSizeOverflow()){
File sdcardDir =Environment.getExternalStorageDirectory();
String rootPath = sdcardDir.getPath()+"/SCZW";
File file = new File(rootPath);
if (!file.exists()) {
file.mkdirs();
}
//创建文件
File newFile = new File(rootPath+"/"+filePath);
if (!newFile.exists()) {
try {
newFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}