Android开发工具类
来源:互联网 发布:弱视网络训练软件 编辑:程序博客网 时间:2024/05/18 20:52
log封装类
package Utils;import android.text.TextUtils;import android.util.Log;/** * Created by Administrator on 2017/9/5. */public class LogUtils { private static final String ERROR_MESSAGE = "something was wrong! The log message you want to print is Empty ! By LogUtils!"; private LogUtils.LogConfig defaultLogConfig = new LogUtils.DebugLogConfig(); private LogUtils.LogConfig logConfig; private static volatile LogUtils logUtils = null; private static final int ANY = 14; public LogUtils() { this.logConfig = this.defaultLogConfig; } public static LogUtils getInstance() { if(logUtils == null) { Class var0 = LogUtils.class; synchronized(LogUtils.class) { if(logUtils == null) { logUtils = new LogUtils(); } } } return logUtils; } public void setLogConfig(LogUtils.LogConfig logConfig) { this.logConfig = logConfig; } public static LogUtils.LogConfig getLogConfig() { return getInstance().logConfig; } public static final void defaultLog(String message) { log(3, getLogConfig().getTag(), message, (Throwable)null); } public static final void defaultLog(Throwable throwable) { log(3, getLogConfig().getTag(), (String)null, throwable); } public static final void defaultLog(String message, Throwable throwable) { log(3, getLogConfig().getTag(), message, throwable); } public static final void log(String tag, String message) { log(3, tag, message, (Throwable)null); } public static final void log(String tag, Throwable throwable) { log(7, tag, (String)null, throwable); } public static final void log(String tag, String message, Throwable throwable) { d(tag, message, throwable); } /** @deprecated */ @Deprecated public static final void log(int priority, String tag, String message) { log(priority, tag, message, (Throwable)null); } /** @deprecated */ @Deprecated public static final void log(int priority, String tag, Throwable throwable) { log(priority, tag, (String)null, throwable); } public static final void v(String tag, String message, Throwable throwable) { log(2, tag, message, throwable); } public static final void i(String tag, String message, Throwable throwable) { log(4, tag, message, throwable); } public static final void d(String tag, String message, Throwable throwable) { log(3, tag, message, throwable); } public static final void w(String tag, String message, Throwable throwable) { log(5, tag, message, throwable); } public static final void e(String tag, String message, Throwable throwable) { log(6, tag, message, throwable); } public static final void a(String tag, String message, Throwable throwable) { log(7, tag, message, throwable); } static final void any(String tag, String message, Throwable throwable) { log(14, tag, message, throwable); } private static final void log(int priority, String tag, String message, Throwable throwable) { if(getLogConfig().loggable(priority)) { if(TextUtils.isEmpty(tag)) { tag = getLogConfig().getTag(); } if(TextUtils.isEmpty(message)) { if(throwable == null) { message = "something was wrong! The log message you want to print is Empty ! By LogUtils!"; priority = 7; } else { message = new String(); } } message = message + Log.getStackTraceString(throwable); getLogConfig().log(priority, tag, message); } } public abstract static class LogConfig { public LogConfig() { } public abstract String getTag(); public abstract boolean loggable(int var1); public String getLogFilePath() { return null; } public abstract void log(int var1, String var2, String var3); } public static class DebugLogConfig extends LogUtils.LogConfig { private static final String CMB = "cmb"; private static final int MAX_LOG_LENGTH = 4000; public DebugLogConfig() { } public boolean loggable(int priority) { return true; } public void log(int priority, String tag, String message) { if(priority > 7) { priority = 7; } if(message.length() < 4000) { if(priority == 7) { Log.wtf(tag, message); } else { Log.println(priority, tag, message); } } else { int i = 0; int end; for(int length = message.length(); i < length; i = end + 1) { int newline = message.indexOf(10, i); newline = newline != -1?newline:length; do { end = Math.min(newline, i + 4000); String part = message.substring(i, end); if(priority == 7) { Log.wtf(tag, part); } else { Log.println(priority, tag, part); } i = end; } while(end < newline); } } } public String getTag() { return "cmb"; } }}
Gson解析封装类
导入包
compile 'com.google.code.gson:gson:2.8.1'
import android.util.Log;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.google.gson.JsonSyntaxException;/** * Created by Administrator on 2017/9/5. */public class GsonUtils { public staticT fromJson(String json, Class tClass) { if (json.isEmpty()) { return null; } GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); try { return gson.fromJson(json, tClass); } catch (JsonSyntaxException e) { Log.e("GsonUtils", json + "无法转换为" + tClass.getName() + "对象!" + e.getMessage()); //可以用给出的logutils工具输出错误日志 //LogUtils.e(json + " 无法转换为 " + tClass.getName() + " 对象!",e.getMessage()); return null; } } public static final String toJsonStr(HashMap, ?> map) { Gson gson = new Gson(); return gson.toJson(map); }}
import android.content.Context;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.util.Log;/** * Created by david on 2016/10/20. */public class AppVersionUtils { /** * 获取版本号 * String * @return 当前应用的版本名称 */ public static String getVersionName(Context context) { try { PackageManager manager = context.getPackageManager(); PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); String versionName = info.versionName; Log.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; Log.e("info", "versionCode" + versionCode); return versionCode; } catch (Exception e) { e.printStackTrace(); return 1; } }}
import java.math.BigDecimal;/** * 算数相关 */public class ArithUtil { private static int DEF_DIV_SCALE = 0; //精确到小数点后几位 //默认除法运算精度 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(); }}
package Utils;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/** * Created by Administrator on 2017/9/6. */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(); }}
import android.graphics.Bitmap;import android.os.Environment;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/** * Created by Administrator on 2017/9/6. * 文件相关 */public class FileUtil { 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; }}
import android.content.Context;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * 从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(); }}
import java.math.BigDecimal;/** * Created by Administrator on 2017/9/6. * 去除double类型数字尾巴的0 */public class MathDataUtil { public static BigDecimal stripTrailingZeros(double d) {//去除double尾巴的0 return new BigDecimal(d).stripTrailingZeros(); }}
import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/** * 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 ""; }}
import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.telephony.TelephonyManager;import android.text.TextUtils;import android.util.Log;/** * Created by Administrator on 2016/11/3. * 获取手机网络状态,详细到移动网络类型 */public class NetWorkUtils { /** * 没有网络 */ 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; } Log.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; } }}
import android.app.Activity;import android.util.DisplayMetrics;import android.view.View;/** * 像素相关,获取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); }}
import android.text.TextUtils;import java.util.regex.Pattern;/** * Created by Administrator on 2016/8/10. *正则表达式验证 */public class RegularUtil { private RegularUtil() { 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}(?
package Utils;import android.content.Context;import android.widget.Toast;/** */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(); }}
- android开发工具类
- Android开发 工具类
- Android开发工具类
- Android开发工具类
- Android开发 MeasureSpec工具类
- android开发,http工具类
- android开发,http工具类
- Android快速开发工具类
- Android开发工具类集锦
- Android 常用开发工具类
- Android 常用开发工具类
- Android常用开发工具类
- Android 开发各种工具类
- Android开发必备工具类
- Android开发 date工具类
- Android 开发各种工具类
- Android开发工具类--NetUtils
- Android开发工具类--LogUtils
- ImageLoader要求
- 触摸[2] 拖动
- gcc中-c和-o参数
- 指定栈的进栈顺序,输出所有可能的出栈顺序
- Druid 介绍及配置
- Android开发工具类
- requestWindowFeature
- Redis数据结构简介
- XCTF:练习CTF解题XMAN比赛 8-8 login
- ELK之logstash长久运行
- LintCode 5: Kth Largest Element
- PHP关于VC11,VC9,VC6以及Thread Safe和Non Thread Safe版本选择的问题
- java面向对象(一)
- Mybatis系列(六)接口式编程