主要积累一些开发中比较 常用的工具类,部分借鉴于网络,主要来源于平时开发因需求而生的小工具类
13、ArithUtil
/**
* Created by Administrator on 2016/10/31.
*/
import java.math.BigDecimal;
/**
* 由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精
* 确的浮点数运算,包括加减乘除和四舍五入。
*/
public class ArithUtil {
//默认除法运算精度
private static final int DEF_DIV_SCALE = 10;
//这个类不能实例化
private ArithUtil(){
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1,double v2){
return div(v1,v2,DEF_DIV_SCALE);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1,double v2,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
12、NetWorkUtil
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
/**
* Created by Administrator on 2016/11/3.
* 获取手机网络状态,详细到移动网络类型
*/
public class NetWorkUtil {
/** 没有网络 */
public static final int NETWORKTYPE_INVALID = 0;
/** wap网络 */
public static final int NETWORKTYPE_WAP = 1;
/** 2G网络 */
public static final int NETWORKTYPE_2G = 2;
/** 3G和3G以上网络,或统称为快速网络 */
public static final int NETWORKTYPE_3G = 3;
/** wifi网络 */
public static final int NETWORKTYPE_WIFI = 4;
private static int mNetWorkType;
/**
* 获取网络状态,wifi,wap,2g,3g.
*
* @param context 上下文
* @return int 网络状态 {@link #NETWORKTYPE_2G},{@link #NETWORKTYPE_3G}, *{@link #NETWORKTYPE_INVALID},{@link #NETWORKTYPE_WAP}* {@link #NETWORKTYPE_WIFI}
*/
public static int getNetWorkType(Context context) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String type = networkInfo.getTypeName();
if (type.equalsIgnoreCase("WIFI")) {
mNetWorkType = NETWORKTYPE_WIFI;
} else if (type.equalsIgnoreCase("MOBILE")) {
String proxyHost = android.net.Proxy.getDefaultHost();
mNetWorkType = TextUtils.isEmpty(proxyHost)
? (isFastMobileNetwork(context) ? NETWORKTYPE_3G : NETWORKTYPE_2G)
: NETWORKTYPE_WAP;
}
} else {
mNetWorkType = NETWORKTYPE_INVALID;
}
LogUtil.e("info","mNetWorkType:" + mNetWorkType);
return mNetWorkType;
}
/**
* 通过TelephonyManager判断移动网络的类型
* @param context
* @return
*/
private static boolean isFastMobileNetwork(Context context) {
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
switch (telephonyManager.getNetworkType()) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return false; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return true; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return true; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return false; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return true; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return true; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return true; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return true; // ~ 400-7000 kbps
case TelephonyManager.NETWORK_TYPE_EHRPD:
return true; // ~ 1-2 Mbps
case TelephonyManager.NETWORK_TYPE_EVDO_B:
return true; // ~ 5 Mbps
case TelephonyManager.NETWORK_TYPE_HSPAP:
return true; // ~ 10-20 Mbps
case TelephonyManager.NETWORK_TYPE_IDEN:
return false; // ~25 kbps
case TelephonyManager.NETWORK_TYPE_LTE:
return true; // ~ 10+ Mbps
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
return false;
default:
return false;
}
}
}
11、AppVersionUtil
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
/**
* Created by david on 2016/10/20.
*/
public class AppVersionUtil {
/**
* 获取版本号
* String
* @return 当前应用的版本名称
*/
public static String getVersionName(Context context) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
String versionName = info.versionName;
LogUtil.e("info", "versionName" + versionName);
return versionName;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 获取版本号
* int
* @return 当前应用的版本号
*/
public static int getVersionCode(Context context) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
int versionCode = info.versionCode;
LogUtil.e("info", "versionCode" + versionCode);
return versionCode;
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
}
10、JsonAssetsReaderUtil
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by david on 2016/11/23.
* 从Assets文件夹中读取.json文件 输出String
*/
public class JsonAssetsReaderUtil {
public static String getJsonStrFromAssets(Context context, String jsonFileName) {
InputStreamReader inputStreamReader = null;
StringBuilder stringBuilder = null;
BufferedReader bufferedReader = null;
try {
inputStreamReader = new InputStreamReader(context.getAssets().open(jsonFileName), "UTF-8");
bufferedReader = new BufferedReader(inputStreamReader);
String jsonStr;
stringBuilder = new StringBuilder();
while ((jsonStr = bufferedReader.readLine()) != null) {
stringBuilder.append(jsonStr);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStreamReader.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
}
9、LogUtil
import android.util.Log;
/**
* LEVEL = VERBOSE时打印所有调试信息
* 当项目上线时,改为 LEVEL = NOTHING
* 关闭所有打印信息
* @author 81091
*
*/
public class LogUtil {
public static final int VERBOSE = 1;
public static final int DEBUG = 2;
public static final int INFO = 3;
public static final int WARN = 4;
public static final int ERROR = 5;
public static final int NOTHING = 6;
public static final int LEVEL = VERBOSE;//打印所有等级的信息
// public static final int LEVEL = NOTHING;//关闭所有等级的信息
public static void v(String tag,String msg){
if(LEVEL <= VERBOSE){
Log.v(tag,msg);
}
}
public static void d(String tag,String msg){
if(LEVEL <= DEBUG){
Log.d(tag,msg);
}
}
public static void i(String tag,String msg){
if(LEVEL <= INFO){
Log.i(tag,msg);
}
}
public static void w(String tag,String msg){
if(LEVEL <= WARN){
Log.w(tag,msg);
}
}
public static void e(String tag,String msg){
if(LEVEL <= ERROR){
Log.e(tag,msg);
}
}
}
8、MD5Utils
/**
* 32位小写
* Created by C5-0 on 2015/7/25.
*/
public class MD5Utils {
public static String ecodeTwice(String str) {//MD5两次
return ecode(ecode(str));
}
public static String ecode(String passwd) {
try {
MessageDigest instance = MessageDigest.getInstance("MD5");
byte[] digest = instance.digest(passwd.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
int i = b & 0xff;
String hexString = Integer.toHexString(i);
if (hexString.length() < 2) {
hexString = "0" + hexString;
}
sb.append(hexString);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
7、比较常用的正则表达式验证
/**
* Created by Administrator on 2016/8/10.
*/
public class RegularUtils {
private RegularUtils() {
throw new UnsupportedOperationException("u can't fuck me...");
}
/**
* 验证手机号(简单)
*/
private static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$";
/**
* 验证手机号(精确)
*
*
移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188
*
联通:130、131、132、145、155、156、175、176、185、186
*
电信:133、153、173、177、180、181、189
*
全球星:1349
*
虚拟运营商:170
*/
private static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-8])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$";
/**
* 验证座机号,正确格式:xxx/xxxx-xxxxxxx/xxxxxxxx/
*/
private static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";
/**
* 验证邮箱
*/
private static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
/**
* 验证url
*/
private static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?";
/**
* 验证汉字
*/
private static final String REGEX_CHZ = "^[\\u4e00-\\u9fa5]+$";
/**
* 验证用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位
*/
private static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?
6、像素相关,获取Android屏幕宽度,控件宽度,dp跟px互转
public class PixelUtil {
//获取运行屏幕宽度
public static int getScreenWidth(Activity context) {
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
//宽度 dm.widthPixels
//高度 dm.heightPixels
// LogUtil.i("info", "getScreenWidth" + dm.widthPixels);
return dm.widthPixels;
}
/**
* 获取控件宽
*/
public static int getWidth(View view) {
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(w, h);
return (view.getMeasuredWidth());
}
//DP转PX
public static int dp2px(Activity context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
//PX转DP
public static int px2dp(Activity context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
}
5、去除double类型数字尾巴的0
如:50.00 --> 50
public class MathDataUtil {
public static BigDecimal stripTrailingZeros(double d) {//去除double尾巴的0
return new BigDecimal(d).stripTrailingZeros();
}
}
4、时间戳相关
public class DateUtils {
private static SimpleDateFormat sf;
private static SimpleDateFormat sdf;
/**
* 获取系统时间 格式为:"yyyy/MM/dd "
**/
public static String getCurrentDate() {
Date d = new Date();
sf = new SimpleDateFormat("yyyy年MM月dd日");
return sf.format(d);
}
/**
* 获取系统时间 格式为:"yyyy "
**/
public static String getCurrentYear() {
Date d = new Date();
sf = new SimpleDateFormat("yyyy");
return sf.format(d);
}
/**
* 获取系统时间 格式为:"MM"
**/
public static String getCurrentMonth() {
Date d = new Date();
sf = new SimpleDateFormat("MM");
return sf.format(d);
}
/**
* 获取系统时间 格式为:"dd"
**/
public static String getCurrentDay() {
Date d = new Date();
sf = new SimpleDateFormat("dd");
return sf.format(d);
}
/**
* 获取当前时间戳
*
* @return
*/
public static long getCurrentTime() {
long d = new Date().getTime() / 1000;
return d;
}
/**
* 时间戳转换成字符窜
*/
public static String getDateToString(long time) {
Date d = new Date(time * 1000);
sf = new SimpleDateFormat("yyyy年MM月dd日");
return sf.format(d);
}
/**
* 时间戳中获取年
*/
public static String getYearFromTime(long time) {
Date d = new Date(time * 1000);
sf = new SimpleDateFormat("yyyy");
return sf.format(d);
}
/**
* 时间戳中获取月
*/
public static String getMonthFromTime(long time) {
Date d = new Date(time * 1000);
sf = new SimpleDateFormat("MM");
return sf.format(d);
}
/**
* 时间戳中获取日
*/
public static String getDayFromTime(long time) {
Date d = new Date(time * 1000);
sf = new SimpleDateFormat("dd");
return sf.format(d);
}
/**
* 将字符串转为时间戳
*/
public static long getStringToDate(String time) {
sdf = new SimpleDateFormat("yyyy年MM月dd日");
Date date = new Date();
try {
date = sdf.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date.getTime();
}
}
3、文件相关
public class FileUtils {
public static String SDPATH = Environment.getExternalStorageDirectory() + "/formats/";// 获取文件夹
// 保存图片
public static boolean saveBitmap(Bitmap mBitmap, String path, String imgName) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
return false;
}
FileOutputStream b = null;
File file = new File(path);
file.mkdirs();// 创建文件夹
String fileName = path + imgName;
// delFile(path, imgName);//删除本地旧图
try {
b = new FileOutputStream(fileName);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
public static File createSDDir(String dirName) throws IOException {
File dir = new File(SDPATH + dirName);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
System.out.println("createSDDir:" + dir.getAbsolutePath());
System.out.println("createSDDir:" + dir.mkdir());
}
return dir;
}
public static boolean isFileExist(String fileName) {
File file = new File(SDPATH + fileName);
file.isFile();
return file.exists();
}
// 删除文件
public static void delFile(String path, String fileName) {
File file = new File(path + fileName);
if (file.isFile()) {
file.delete();
}
file.exists();
}
// 删除文件夹和文件夹里面的文件
public static void deleteDir() {
File dir = new File(SDPATH);
if (dir == null || !dir.exists() || !dir.isDirectory())
return;
for (File file : dir.listFiles()) {
if (file.isFile())
file.delete(); // 删除所有文件
else if (file.isDirectory())
deleteDir(); // 递规的方式删除文件夹
}
dir.delete();// 删除目录本身
}
public static boolean fileIsExists(String path) {
try {
File f = new File(path);
if (!f.exists()) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
}
2、AlertDialogUtil
/**
* Created by david on 2016/8/26.
*
* 使用观察者模式来实现确定结果回调
*
* 调用方式:
* AlertDialogUtil dialogUtil = new AlertDialogUtil(context);
* dialogUtil.showDialog("确定删除已上传的图片?");
* dialogUtil.setDialogPositiveButtonListener(new AlertDialogUtil.DialogPositiveButtonListener() {
*
* @Override
* public void setDialogPositiveButtonListener() {
*
* }
* });
*/
public class AlertDialogUtil {
public Context context;
private DialogPositiveButtonListener listener;
public AlertDialogUtil(Context context) {
this.context = context;
}
public void showDialog(String message) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setMessage(message);
dialog.setCancelable(false);//点击框外取消
dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (listener != null) {
listener.setDialogPositiveButtonListener();
}
}
});
dialog.setNegativeButton("取消", null);
dialog.show();
}
public void setDialogPositiveButtonListener(DialogPositiveButtonListener listener) {
this.listener = listener;
}
public interface DialogPositiveButtonListener {
void setDialogPositiveButtonListener();
}
}
1、ToastUtil
public class ToastUtils {
static Toast toast;
private ToastUtils() {
throw new AssertionError();
}
public static void show(Context paramContext, int paramInt) {
show(paramContext, paramContext.getResources().getText(paramInt), 0);
}
public static void show(Context paramContext, int paramInt1, int paramInt2) {
show(paramContext, paramContext.getResources().getText(paramInt1), paramInt2);
}
public static void show(Context paramContext, CharSequence paramCharSequence) {
show(paramContext, paramCharSequence, 0);
}
public static void show(Context paramContext, CharSequence paramCharSequence, int paramInt) {
if (toast != null) {
toast.setText(paramCharSequence);
toast.setDuration(paramInt);
toast.show();//
return;
}
toast = Toast.makeText(paramContext, paramCharSequence, paramInt);
toast.show();
}
public static void toastCancle() {
if (toast != null)
toast.cancel();
}
}