Android开发过程中,我们需要的很多代码都是重复多次使用的,写成工具类是一个比较好的做法,下面是我常用的几个工具类,也希望对你有所帮助。分别是:日期格式化工具、转换图片颜色工具、app启动引导页控制工具、Intent 工具、手机信息采集工具、存储和访问SharedPreferences工具、正则表达式工具、SD卡片工具、Toast信息工具、app版本工具、错误信息反馈工具、类型转换工具。
大家可到github上下载代码AndroidUtils。
package cn.studyou.baselibrary.utils; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 基本功能:日期格式化工具 * 创建:王杰 * 创建时间:13/3/14 * 邮箱:w489657152@gmail.com */ public class DateFormatUtil { private static SimpleDateFormat second = new SimpleDateFormat( "yy-MM-dd hh:mm:ss"); private static SimpleDateFormat day = new SimpleDateFormat("yyyy-MM-dd"); private static SimpleDateFormat detailDay = new SimpleDateFormat("yyyy年MM月dd日"); private static SimpleDateFormat fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); private static SimpleDateFormat tempTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static SimpleDateFormat excelDate = new SimpleDateFormat("yyyy/MM/dd"); /** * 格式化excel中的时间 * @param date * @return */ public static String formatDateForExcelDate(Date date) { return excelDate.format(date); } /** * 将日期格式化作为文件名 * @param date * @return */ public static String formatDateForFileName(Date date) { return fileName.format(date); } /** * 格式化日期(精确到秒) * * @param date * @return */ public static String formatDateSecond(Date date) { return second.format(date); } /** * 格式化日期(精确到秒) * * @param date * @return */ public static String tempDateSecond(Date date) { return tempTime.format(date); } public static Date tempDateSecond(String str) { try { return tempTime.parse(str); } catch (ParseException e) { e.printStackTrace(); } return new Date(); } /** * 格式化日期(精确到天) * * @param date * @return */ public static String formatDateDay(Date date) { return day.format(date); } /** * 格式化日期(精确到天) * * @param date * @return */ public static String formatDateDetailDay(Date date) { return detailDay.format(date); } /** * 将double类型的数字保留两位小数(四舍五入) * * @param number * @return */ public static String formatNumber(double number) { DecimalFormat df = new DecimalFormat(); df.applyPattern("#0.00"); return df.format(number); } /** * 将字符串转换成日期 * * @param date * @return * @throws Exception */ public static Date formateDate(String date) throws Exception { return day.parse(date); } /** * 将字符日期转换成Date * @param date * @return * @throws Exception */ public static Date parseStringToDate(String date) throws Exception { return day.parse(date); } public static String formatDoubleNumber(double number) { DecimalFormat df = new DecimalFormat("#"); return df.format(number); } }
package cn.studyou.baselibrary.utils; import android.app.Activity; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; /** * 基本功能:转换图片颜色工具 * 创建:王杰 * 创建时间:15/1/23 * 邮箱:w489657152@gmail.com */ public class ConvertImageColor { Activity activity; public ConvertImageColor(Activity activity) { this.activity = activity; } // 改变图标的颜色 public Drawable changeImageColor(int drawable,int color){ Drawable myIcon = activity.getResources().getDrawable(drawable); myIcon.setColorFilter(activity.getResources().getColor(color), PorterDuff.Mode.SRC_ATOP); return myIcon; } }
package cn.studyou.baselibrary.utils; import android.content.Context; import android.text.TextUtils; /** * 基本功能:app启动引导页控制 * 创建:王杰 * 创建时间:16/3/7 * 邮箱:w489657152@gmail.com */ public class AppIntroUtil { public static final int LMODE_NEW_INSTALL = 1; //再次启动 public static final int LMODE_UPDATE = 2;//更新后第一次启动 public static final int LMODE_AGAIN = 3;//首次安装启动 public static final String SHARENAME= "lastVersion"; private boolean isOpenMarked = false; private int launchMode = LMODE_AGAIN; //启动-模式 private static AppIntroUtil instance; public static AppIntroUtil getThis() { if (instance == null) instance = new AppIntroUtil(); return instance; } /** * 标记-打开app,用于产生-是否首次打开 * @param context */ public void markOpenApp(Context context) { // 防止-重复调用 if (isOpenMarked) return; isOpenMarked = true; String lastVersion = OperatingSharedPreferences.getString(context,SHARENAME,SHARENAME); String thisVersion = VersionUtil.getVersion(context); // 首次启动 if (TextUtils.isEmpty(lastVersion)) { launchMode = LMODE_NEW_INSTALL; OperatingSharedPreferences.setString(context,SHARENAME,SHARENAME,thisVersion); } // 更新 else if (VersionUtil.compareVersion(lastVersion,thisVersion)) { launchMode = LMODE_UPDATE; OperatingSharedPreferences.setString(context, SHARENAME, SHARENAME, thisVersion); } // 二次启动(版本未变) else launchMode = LMODE_AGAIN; } public int getLaunchMode() { return launchMode; } /** * 首次打开,新安装、覆盖(版本号不同) * @return */ public boolean isFirstOpen() { return launchMode != LMODE_AGAIN; } }
package cn.studyou.baselibrary.utils; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.widget.Toast; /** * 基本功能:Intent工具 * 创建:王杰 * 创建时间:16/3/7 * 邮箱:w489657152@gmail.com */ public class IntentUtil { private static final String TAG = IntentUtil.class.getSimpleName(); public static Intent getLauncherIntent() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addCategory(Intent.CATEGORY_HOME); return intent; } public static void logIntent(String tag, Intent intent) { if (intent == null) { return; } StringBuffer sb = new StringBuffer(); sb.append("\nAction:" + intent.getAction()); sb.append("\nData:" + intent.getData()); sb.append("\nDataStr:" + intent.getDataString()); sb.append("\nScheme:" + intent.getScheme()); sb.append("\nType:" + intent.getType()); Bundle extras = intent.getExtras(); if (extras != null && !extras.isEmpty()) { for (String key : extras.keySet()) { Object value = extras.get(key); sb.append("\nEXTRA: {" + key + "::" + value + "}"); } } else { sb.append("\nNO EXTRAS"); } Log.i(tag, sb.toString()); } public static int sdkVersion() { return new Integer(Build.VERSION.SDK).intValue(); } public static void startDialer(Context context, String phoneNumber) { try { Intent dial = new Intent(); dial.setAction(Intent.ACTION_DIAL); dial.setData(Uri.parse("tel:" + phoneNumber)); context.startActivity(dial); } catch (Exception ex) { Log.e(TAG, "Error starting phone dialer intent.", ex); Toast.makeText(context, "Sorry, we couldn't find any app to place a phone call!", Toast.LENGTH_SHORT).show(); } } public static void startSmsIntent(Context context, String phoneNumber) { try { Uri uri = Uri.parse("sms:" + phoneNumber); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra("address", phoneNumber); intent.setType("vnd.android-dir/mms-sms"); context.startActivity(intent); } catch (Exception ex) { Log.e(TAG, "Error starting sms intent.", ex); Toast.makeText(context, "Sorry, we couldn't find any app to send an SMS!", Toast.LENGTH_SHORT).show(); } } public static void startEmailIntent(Context context, String emailAddress) { try { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("plain/text"); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailAddress}); context.startActivity(intent); } catch (Exception ex) { Log.e(TAG, "Error starting email intent.", ex); Toast.makeText(context, "Sorry, we couldn't find any app for sending emails!", Toast.LENGTH_SHORT).show(); } } public static void startWebIntent(Context context, String url) { try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); context.startActivity(intent); } catch (Exception ex) { Log.e(TAG, "Error starting url intent.", ex); Toast.makeText(context, "Sorry, we couldn't find any app for viewing this url!", Toast.LENGTH_SHORT).show(); } } }
package cn.studyou.filedwork.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.SystemClock; import android.telephony.TelephonyManager; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; /** * 基本功能:手机信息采集工具 * 创建:王杰 * 创建时间:14/1/1 * 邮箱:w489657152@gmail.com */ public class MobileUtil { /** * Print telephone info. */ public static String printMobileInfo(Context context) { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = dateFormat.format(date); StringBuilder sb = new StringBuilder(); sb.append("系统时间:").append(time).append("\n"); TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String IMSI = tm.getSubscriberId(); //IMSI前面三位460是国家号码,其次的两位是运营商代号,00、02是中国移动,01是联通,03是电信。 String providerName = null; if (IMSI != null) { if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) { providerName = "中国移动"; } else if (IMSI.startsWith("46001")) { providerName = "中国联通"; } else if (IMSI.startsWith("46003")) { providerName = "中国电信"; } } sb.append(providerName).append("\n").append(getNativePhoneNumber(context)).append("\n网络模式:").append(getNetType(context)).append("\nIMSI是:").append(IMSI); sb.append("\nDeviceID(IMEI) :").append(tm.getDeviceId()); sb.append("\nDeviceSoftwareVersion:").append(tm.getDeviceSoftwareVersion()); sb.append("\ngetLine1Number :").append(tm.getLine1Number()); sb.append("\nNetworkCountryIso :").append(tm.getNetworkCountryIso()); sb.append("\nNetworkOperator :").append(tm.getNetworkOperator()); sb.append("\nNetworkOperatorName :").append(tm.getNetworkOperatorName()); sb.append("\nNetworkType :").append(tm.getNetworkType()); sb.append("\nPhoneType :").append(tm.getPhoneType()); sb.append("\nSimCountryIso :").append(tm.getSimCountryIso()); sb.append("\nSimOperator :").append(tm.getSimOperator()); sb.append("\nSimOperatorName :").append(tm.getSimOperatorName()); sb.append("\nSimSerialNumber :").append(tm.getSimSerialNumber()); sb.append("\ngetSimState :").append(tm.getSimState()); sb.append("\nSubscriberId :").append(tm.getSubscriberId()); sb.append("\nVoiceMailNumber :").append(tm.getVoiceMailNumber()); return sb.toString(); } /** * 打印系统信息 * @return */ public static String printSystemInfo() { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = dateFormat.format(date); StringBuilder sb = new StringBuilder(); sb.append("_______ 系统信息 ").append(time).append(" ______________"); sb.append("\nID :").append(Build.ID); sb.append("\nBRAND :").append(Build.BRAND); sb.append("\nMODEL :").append(Build.MODEL); sb.append("\nRELEASE :").append(Build.VERSION.RELEASE); sb.append("\nSDK :").append(Build.VERSION.SDK); sb.append("\n_______ OTHER _______"); sb.append("\nBOARD :").append(Build.BOARD); sb.append("\nPRODUCT :").append(Build.PRODUCT); sb.append("\nDEVICE :").append(Build.DEVICE); sb.append("\nFINGERPRINT :").append(Build.FINGERPRINT); sb.append("\nHOST :").append(Build.HOST); sb.append("\nTAGS :").append(Build.TAGS); sb.append("\nTYPE :").append(Build.TYPE); sb.append("\nTIME :").append(Build.TIME); sb.append("\nINCREMENTAL :").append(Build.VERSION.INCREMENTAL); sb.append("\n_______ CUPCAKE-3 _______"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) { sb.append("\nDISPLAY :").append(Build.DISPLAY); } sb.append("\n_______ DONUT-4 _______"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { sb.append("\nSDK_INT :").append(Build.VERSION.SDK_INT); sb.append("\nMANUFACTURER :").append(Build.MANUFACTURER); sb.append("\nBOOTLOADER :").append(Build.BOOTLOADER); sb.append("\nCPU_ABI :").append(Build.CPU_ABI); sb.append("\nCPU_ABI2 :").append(Build.CPU_ABI2); sb.append("\nHARDWARE :").append(Build.HARDWARE); sb.append("\nUNKNOWN :").append(Build.UNKNOWN); sb.append("\nCODENAME :").append(Build.VERSION.CODENAME); } sb.append("\n_______ GINGERBREAD-9 _______"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { sb.append("\nSERIAL :").append(Build.SERIAL); } return sb.toString(); } /**** * 获取网络类型 * * @param context * @return */ public static String getNetType(Context context) { try { ConnectivityManager connectMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connectMgr.getActiveNetworkInfo(); if (info == null) { return ""; } if (info.getType() == ConnectivityManager.TYPE_WIFI) { return "WIFI"; } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) { if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA) { return "CDMA"; } else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE) { return "EDGE"; } else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_0) { return "EVDO0"; } else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_A) { return "EVDOA"; } else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS) { return "GPRS"; } /* * else if(info.getSubtype() == * TelephonyManager.NETWORK_TYPE_HSDPA){ return "HSDPA"; }else * if(info.getSubtype() == TelephonyManager.NETWORK_TYPE_HSPA){ * return "HSPA"; }else if(info.getSubtype() == * TelephonyManager.NETWORK_TYPE_HSUPA){ return "HSUPA"; } */ else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_UMTS) { return "UMTS"; } else { return "3G"; } } else { return ""; } } catch (Exception e) { return ""; } } /** * 获取当前设置的电话号码 */ public static String getNativePhoneNumber(Context context) { TelephonyManager telephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); String NativePhoneNumber = null; NativePhoneNumber = telephonyManager.getLine1Number(); return String.format("手机号: %s", NativePhoneNumber); } /** * IMSI是国际移动用户识别码的简称(International Mobile Subscriber Identity) * IMSI共有15位,其结构如下: * MCC+MNC+MIN * MCC:Mobile Country Code,移动国家码,共3位,中国为460; * MNC:Mobile NetworkCode,移动网络码,共2位 * 在中国,移动的代码为电00和02,联通的代码为01,电信的代码为03 * 合起来就是(也是Android手机中APN配置文件中的代码): * 中国移动:46000 46002 * 中国联通:46001 * 中国电信:46003 * 举例,一个典型的IMSI号码为460030912121001 */ public static String getIMSI(Context context) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String IMSI = telephonyManager.getSubscriberId(); return IMSI; } /** * IMEI是International Mobile Equipment Identity (国际移动设备标识)的简称 * IMEI由15位数字组成的”电子串号”,它与每台手机一一对应,而且该码是全世界唯一的 * 其组成为: * 1. 前6位数(TAC)是”型号核准号码”,一般代表机型 * 2. 接着的2位数(FAC)是”最后装配号”,一般代表产地 * 3. 之后的6位数(SNR)是”串号”,一般代表生产顺序号 * 4. 最后1位数(SP)通常是”0″,为检验码,目前暂备用 */ public static String getIMEI(Context context) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String IMEI = telephonyManager.getDeviceId(); return IMEI; } /////_________________ 双卡双待系统IMEI和IMSI方案(see more on http://benson37.iteye.com/blog/1923946) /** * 双卡双待神机IMSI、IMSI、PhoneType信息 * <uses-permission android:name="android.permission.READ_PHONE_STATE"/> */ public static class TeleInfo { public String imsi_1; public String imsi_2; public String imei_1; public String imei_2; public int phoneType_1; public int phoneType_2; @Override public String toString() { return "TeleInfo{" + "imsi_1='" + imsi_1 + '\'' + ", imsi_2='" + imsi_2 + '\'' + ", imei_1='" + imei_1 + '\'' + ", imei_2='" + imei_2 + '\'' + ", phoneType_1=" + phoneType_1 + ", phoneType_2=" + phoneType_2 + '}'; } } /** * MTK Phone. * * 获取 MTK 神机的双卡 IMSI、IMSI 信息 */ public static TeleInfo getMtkTeleInfo(Context context) { TeleInfo teleInfo = new TeleInfo(); try { Class<?> phone = Class.forName("com.android.internal.telephony.Phone"); Field fields1 = phone.getField("GEMINI_SIM_1"); fields1.setAccessible(true); int simId_1 = (Integer) fields1.get(null); Field fields2 = phone.getField("GEMINI_SIM_2"); fields2.setAccessible(true); int simId_2 = (Integer) fields2.get(null); TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); Method getSubscriberIdGemini = TelephonyManager.class.getDeclaredMethod("getSubscriberIdGemini", int.class); String imsi_1 = (String) getSubscriberIdGemini.invoke(tm, simId_1); String imsi_2 = (String) getSubscriberIdGemini.invoke(tm, simId_2); teleInfo.imsi_1 = imsi_1; teleInfo.imsi_2 = imsi_2; Method getDeviceIdGemini = TelephonyManager.class.getDeclaredMethod("getDeviceIdGemini", int.class); String imei_1 = (String) getDeviceIdGemini.invoke(tm, simId_1); String imei_2 = (String) getDeviceIdGemini.invoke(tm, simId_2); teleInfo.imei_1 = imei_1; teleInfo.imei_2 = imei_2; Method getPhoneTypeGemini = TelephonyManager.class.getDeclaredMethod("getPhoneTypeGemini", int.class); int phoneType_1 = (Integer) getPhoneTypeGemini.invoke(tm, simId_1); int phoneType_2 = (Integer) getPhoneTypeGemini.invoke(tm, simId_2); teleInfo.phoneType_1 = phoneType_1; teleInfo.phoneType_2 = phoneType_2; } catch (Exception e) { e.printStackTrace(); } return teleInfo; } /** * MTK Phone. * * 获取 MTK 神机的双卡 IMSI、IMSI 信息 */ public static TeleInfo getMtkTeleInfo2(Context context) { TeleInfo teleInfo = new TeleInfo(); try { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); Class<?> phone = Class.forName("com.android.internal.telephony.Phone"); Field fields1 = phone.getField("GEMINI_SIM_1"); fields1.setAccessible(true); int simId_1 = (Integer) fields1.get(null); Field fields2 = phone.getField("GEMINI_SIM_2"); fields2.setAccessible(true); int simId_2 = (Integer) fields2.get(null); Method getDefault = TelephonyManager.class.getMethod("getDefault", int.class); TelephonyManager tm1 = (TelephonyManager) getDefault.invoke(tm, simId_1); TelephonyManager tm2 = (TelephonyManager) getDefault.invoke(tm, simId_2); String imsi_1 = tm1.getSubscriberId(); String imsi_2 = tm2.getSubscriberId(); teleInfo.imsi_1 = imsi_1; teleInfo.imsi_2 = imsi_2; String imei_1 = tm1.getDeviceId(); String imei_2 = tm2.getDeviceId(); teleInfo.imei_1 = imei_1; teleInfo.imei_2 = imei_2; int phoneType_1 = tm1.getPhoneType(); int phoneType_2 = tm2.getPhoneType(); teleInfo.phoneType_1 = phoneType_1; teleInfo.phoneType_2 = phoneType_2; } catch (Exception e) { e.printStackTrace(); } return teleInfo; } /** * Qualcomm Phone. * 获取 高通 神机的双卡 IMSI、IMSI 信息 */ public static TeleInfo getQualcommTeleInfo(Context context) { TeleInfo teleInfo = new TeleInfo(); try { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); Class<?> simTMclass = Class.forName("android.telephony.MSimTelephonyManager"); // Object sim = context.getSystemService("phone_msim"); Object sim = context.getSystemService(Context.TELEPHONY_SERVICE); int simId_1 = 0; int simId_2 = 1; Method getSubscriberId = simTMclass.getMethod("getSubscriberId", int.class); String imsi_1 = (String) getSubscriberId.invoke(sim, simId_1); String imsi_2 = (String) getSubscriberId.invoke(sim, simId_2); teleInfo.imsi_1 = imsi_1; teleInfo.imsi_2 = imsi_2; Method getDeviceId = simTMclass.getMethod("getDeviceId", int.class); String imei_1 = (String) getDeviceId.invoke(sim, simId_1); String imei_2 = (String) getDeviceId.invoke(sim, simId_2); teleInfo.imei_1 = imei_1; teleInfo.imei_2 = imei_2; Method getDataState = simTMclass.getMethod("getDataState"); int phoneType_1 = tm.getDataState(); int phoneType_2 = (Integer) getDataState.invoke(sim); teleInfo.phoneType_1 = phoneType_1; teleInfo.phoneType_2 = phoneType_2; } catch (Exception e) { e.printStackTrace(); } return teleInfo; } /** * Spreadtrum Phone. * * 获取 展讯 神机的双卡 IMSI、IMSI 信息 */ public static TeleInfo getSpreadtrumTeleInfo(Context context) { TeleInfo teleInfo = new TeleInfo(); try { TelephonyManager tm1 = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String imsi_1 = tm1.getSubscriberId(); String imei_1 = tm1.getDeviceId(); int phoneType_1 = tm1.getPhoneType(); teleInfo.imsi_1 = imsi_1; teleInfo.imei_1 = imei_1; teleInfo.phoneType_1 = phoneType_1; Class<?> phoneFactory = Class.forName("com.android.internal.telephony.PhoneFactory"); Method getServiceName = phoneFactory.getMethod("getServiceName", String.class, int.class); getServiceName.setAccessible(true); TelephonyManager tm2 = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String imsi_2 = tm2.getSubscriberId(); String imei_2 = tm2.getDeviceId(); int phoneType_2 = tm2.getPhoneType(); teleInfo.imsi_2 = imsi_2; teleInfo.imei_2 = imei_2; teleInfo.phoneType_2 = phoneType_2; } catch (Exception e) { e.printStackTrace(); } return teleInfo; } /** * 获取 MAC 地址 * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> */ public static String getMacAddress(Context context) { //wifi mac地址 WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); String mac = info.getMacAddress(); return mac; } /** * 获取 开机时间 */ public static String getBootTimeString() { long ut = SystemClock.elapsedRealtime() / 1000; int h = (int) ((ut / 3600)); int m = (int) ((ut / 60) % 60); return h + ":" + m; } }
package cn.studyou.baselibrary.utils; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; /** * 基本功能:存储和访问SharedPreferences * 创建:王杰 * 创建时间:16/3/7 * 邮箱:w489657152@gmail.com */ public class OperatingSharedPreferences { /** * <pre> * 基本功能:保存String类型数据到SharedPreferences * 编写:王杰 * * @param context * @param name * @param key * @param value </pre> */ public static void setString(Context context, String name, String key, String value) { SharedPreferences sharedPreferences = context.getSharedPreferences( name, Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit();// 获取编辑器 editor.putString(key, value); editor.commit();// 提交修改 } /** * <pre> * 基本功能:取得SharedPreferences中存储的String类型数据 * 编写:王杰 * * @param context * @param name * @param key * @return </pre> */ public static String getString(Context context, String name, String key) { SharedPreferences sharedPreferences = context.getSharedPreferences( name, Context.MODE_PRIVATE); String signature = sharedPreferences.getString(key, ""); return signature; } /** * <pre> * 基本功能:存储的Int类型数据到SharedPreferences * 编写:王杰 * * @param context * @param name * @param key * @return </pre> */ public static void setInt(Context context, String name, String key, int value) { SharedPreferences sharedPreferences = context.getSharedPreferences( name, Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit();// 获取编辑器 editor.putInt(key, value); editor.commit();// 提交修改 } /** * <pre> * 基本功能:取得SharedPreferences中存储的Int类型数据 * 编写:王杰 * * @param context * @param name * @param key * @return </pre> */ public static int getInt(Context context, String name, String key) { SharedPreferences sharedPreferences = context.getSharedPreferences( name, Context.MODE_PRIVATE); int signature = sharedPreferences.getInt(key, 0); return signature; } }
package cn.studyou.baselibrary.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 基本功能:正则表达式工具类 * 创建:王杰 * 创建时间:16/3/8 * 邮箱:w489657152@gmail.com */ public class RegexUtil { public static boolean checkEmail(String email) { String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; return Pattern.matches(regex, email); } public static boolean checkIdCard(String idCard) { String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}"; return Pattern.matches(regex,idCard); } public static boolean checkMobile(String mobile) { String regex = "(\\+\\d+)?1[3458]\\d{9}$"; return Pattern.matches(regex,mobile); } public static boolean checkPhone(String phone) { String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; return Pattern.matches(regex, phone); } public static boolean checkDigit(String digit) { String regex = "\\-?[1-9]\\d+"; return Pattern.matches(regex,digit); } public static boolean checkDecimals(String decimals) { String regex = "\\-?[1-9]\\d+(\\.\\d+)?"; return Pattern.matches(regex, decimals); } public static boolean checkBlankSpace(String blankSpace) { String regex = "\\s+"; return Pattern.matches(regex,blankSpace); } public static boolean checkChinese(String chinese) { String regex = "^[\u4E00-\u9FA5]+$"; return Pattern.matches(regex,chinese); } public static boolean checkBirthday(String birthday) { String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; return Pattern.matches(regex,birthday); } public static boolean checkURL(String url) { // String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?"; String regex = "(http|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?"; return Pattern.matches(regex, url); } public static String getDomain(String url) { Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); // 获取完整的域名 // Pattern p=Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(url); matcher.find(); return matcher.group(); } public static boolean checkPostcode(String postcode) { String regex = "[1-9]\\d{5}"; return Pattern.matches(regex, postcode); } public static boolean checkIpAddress(String ipAddress) { String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))"; return Pattern.matches(regex, ipAddress); } }
package cn.studyou.baselibrary.utils; import android.annotation.TargetApi; import android.os.Build; import android.os.Environment; import android.os.StatFs; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; /** * 基本功能:SD卡片工具 * 创建:王杰 * 创建时间:16/3/11 * 邮箱:w489657152@gmail.com */ public class SdCardUtil { /** * is sd card available. * @return true if available */ public boolean isSdCardAvailable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } /** * Get {@link android.os.StatFs}. */ public static StatFs getStatFs(String path) { return new StatFs(path); } /** * Get phone data path. */ public static String getDataPath() { return Environment.getDataDirectory().getPath(); } /** * Get SD card path. */ public static String getNormalSDCardPath() { return Environment.getExternalStorageDirectory().getPath(); } /** * Get SD card path by CMD. */ public static String getSDCardPath() { String cmd = "cat /proc/mounts"; String sdcard = null; Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象 BufferedReader bufferedReader = null; try { Process p = run.exec(cmd);// 启动另一个进程来执行命令 bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream()))); String lineStr; while ((lineStr = bufferedReader.readLine()) != null) { if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) { String[] strArray = lineStr.split(" "); if (strArray.length >= 5) { sdcard = strArray[1].replace("/.android_secure", ""); return sdcard; } } if (p.waitFor() != 0 && p.exitValue() == 1) { // p.exitValue()==0表示正常结束,1:非正常结束 } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException e) { e.printStackTrace(); } } sdcard = Environment.getExternalStorageDirectory().getPath(); return sdcard; } /** * Get SD card path list. */ public static ArrayList<String> getSDCardPathEx() { ArrayList<String> list = new ArrayList<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.length > 1) { list.add("*" + columns[1]); } } else if (line.contains("fuse")) { String columns[] = line.split(" "); if (columns.length > 1) { list.add(columns[1]); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return list; } /** * Get available size of SD card. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static long getAvailableSize(String path) { try { File base = new File(path); StatFs stat = new StatFs(base.getPath()); return stat.getBlockSizeLong() * stat.getAvailableBlocksLong(); } catch (Exception e) { e.printStackTrace(); } return 0; } /** * Get SD card info detail. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static SDCardInfo getSDCardInfo() { SDCardInfo sd = new SDCardInfo(); String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { sd.isExist = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { File sdcardDir = Environment.getExternalStorageDirectory(); StatFs sf = new StatFs(sdcardDir.getPath()); sd.totalBlocks = sf.getBlockCountLong(); sd.blockByteSize = sf.getBlockSizeLong(); sd.availableBlocks = sf.getAvailableBlocksLong(); sd.availableBytes = sf.getAvailableBytes(); sd.freeBlocks = sf.getFreeBlocksLong(); sd.freeBytes = sf.getFreeBytes(); sd.totalBytes = sf.getTotalBytes(); } } return sd; } /** * see more {@link android.os.StatFs} */ public static class SDCardInfo { public boolean isExist; public long totalBlocks; public long freeBlocks; public long availableBlocks; public long blockByteSize; public long totalBytes; public long freeBytes; public long availableBytes; @Override public String toString() { return "SDCardInfo{" + "isExist=" + isExist + ", totalBlocks=" + totalBlocks + ", freeBlocks=" + freeBlocks + ", availableBlocks=" + availableBlocks + ", blockByteSize=" + blockByteSize + ", totalBytes=" + totalBytes + ", freeBytes=" + freeBytes + ", availableBytes=" + availableBytes + '}'; } } }
package cn.studyou.baselibrary.utils; import android.content.Context; import android.view.Gravity; import android.widget.Toast; /** * 基本功能:Toast信息工具 * 创建:王杰 * 创建时间:14/3/11 * 邮箱:w489657152@gmail.com */ public class ToastUtil { /** * 将最长使用的显示方法单独提出来,方便使用。 * 屏幕中心位置短时间显示Toast。 * * @param context * @param message */ public static void show(Context context, String message) { ToastShortCenter(context,message); } /** * 屏幕底部中间位置显示短时间Toast * * @param context * @param message */ public static void ToastShortBottomCenter(Context context, String message) { if (context != null) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } /** * 屏幕底部左边位置短时间显示Toast * * @param context * @param message */ public static void ToastShortBottomLeft(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM | Gravity.LEFT, 0, 0); toast.show(); } } /** * 屏幕底部右边位置短时间显示Toast * * @param context * @param message */ public static void ToastShortBottomRight(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0); toast.show(); } } /** * 屏幕中心位置短时间显示Toast * * @param context * @param message */ public static void ToastShortCenter(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } } /** * 屏幕中心左边位置短时间显示Toast * * @param context * @param message */ public static void ToastShortCenterLeft(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.LEFT, 0, 0); toast.show(); } } /** * 屏幕中心右边位置短时间显示Toast * * @param context * @param message */ public static void ToastShortCenterRight(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.RIGHT, 0, 0); toast.show(); } } /** * 屏幕顶部中心位置短时间显示Toast * * @param context * @param message */ public static void ToastShortTopCenter(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); } } /** * 屏幕顶部左边位置短时间显示Toast * * @param context * @param message */ public static void ToastShortTopLeft(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); toast.show(); } } /** * 屏幕顶部右边位置短时间显示Toast * * @param context * @param message */ public static void ToastShortTopRight(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0); toast.show(); } } /** * 屏幕底部中间位置显示长时间Toast * * @param context * @param message */ public static void ToastLongBottomCenter(Context context, String message) { if (context != null) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } } /** * 屏幕底部左边位置长时间显示Toast * * @param context * @param message */ public static void ToastLongBottomLeft(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.BOTTOM | Gravity.LEFT, 0, 0); toast.show(); } } /** * 屏幕底部右边位置长时间显示Toast * * @param context * @param message */ public static void ToastLongBottomRight(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0); toast.show(); } } /** * 屏幕中心位置长时间显示Toast * * @param context * @param message */ public static void ToastLongCenter(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } } /** * 屏幕中心左边位置长时间显示Toast * * @param context * @param message */ public static void ToastLongCenterLeft(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER | Gravity.LEFT, 0, 0); toast.show(); } } /** * 屏幕中心右边位置短时间显示Toast * * @param context * @param message */ public static void ToastLongCenterRight(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER | Gravity.RIGHT, 0, 0); toast.show(); } } /** * 屏幕顶部中心位置长时间显示Toast * * @param context * @param message */ public static void ToastLongTopCenter(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); } } /** * 屏幕顶部左边位置长时间显示Toast * * @param context * @param message */ public static void ToastLongTopLeft(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); toast.show(); } } /** * 屏幕顶部右边位置长时间显示Toast * * @param context * @param message */ public static void ToastLongTopRight(Context context, String message) { if (context != null) { Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0); toast.show(); } } }
package cn.studyou.baselibrary.utils; /** * 基本功能:类型转换工具 * 创建:王杰 * 创建时间:14/10/11 * 邮箱:w489657152@gmail.com */ public class TypeConvertUtil { public static String nullOfString(String str) { if (str == null) { str = ""; } return str; } public static byte stringToByte(String str) { byte b = 0; if (str != null) { try { b = Byte.parseByte(str); } catch (Exception e) { } } return b; } public static boolean stringToBoolean(String str) { if (str == null) { return false; } else { if (str.equals("1")) { return true; } else if (str.equals("0")) { return false; } else { try { return Boolean.parseBoolean(str); } catch (Exception e) { return false; } } } } public static int stringToInt(String str) { int i = 0; if (str != null) { try { i = Integer.parseInt(str.trim()); } catch (Exception e) { i = 0; } } else { i = 0; } return i; } public static short stringToShort(String str) { short i = 0; if (str != null) { try { i = Short.parseShort(str.trim()); } catch (Exception e) { i = 0; } } else { i = 0; } return i; } public static double stringToDouble(String str) { double i = 0; if (str != null) { try { i = Double.parseDouble(str.trim()); } catch (Exception e) { i = 0; } } else { i = 0; } return i; } public static String intToString(int i) { String str = ""; try { str = String.valueOf(i); } catch (Exception e) { str = ""; } return str; } public static long doubleToLong(double d) { long lo = 0; try { //double转换成long前要过滤掉double类型小数点后数据 lo = Long.parseLong(String.valueOf(d).substring(0, String.valueOf(d).lastIndexOf("."))); } catch (Exception e) { lo = 0; } return lo; } public static int doubleToInt(double d) { int i = 0; try { //double转换成long前要过滤掉double类型小数点后数据 i = Integer.parseInt(String.valueOf(d).substring(0, String.valueOf(d).lastIndexOf("."))); } catch (Exception e) { i = 0; } return i; } public static double longToDouble(long d) { double lo = 0; try { lo = Double.parseDouble(String.valueOf(d)); } catch (Exception e) { lo = 0; } return lo; } public static int longToInt(long d) { int lo = 0; try { lo = Integer.parseInt(String.valueOf(d)); } catch (Exception e) { lo = 0; } return lo; } public static long stringToLong(String str) { Long li = new Long(0); try { li = Long.valueOf(str); } catch (Exception e) { //li = new Long(0); } return li.longValue(); } public static String longToString(long li) { String str = ""; try { str = String.valueOf(li); } catch (Exception e) { } return str; } }
package cn.studyou.baselibrary.utils; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; /** * 基本功能:app版本工具 * 创建:王杰 * 创建时间:14/6/7 * 邮箱:w489657152@gmail.com */ public class VersionUtil { /** * 获取版本号 * * @return 当前应用的版本号 */ public static String getVersion(Context context) { try { PackageManager manager = context.getPackageManager(); PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); String version = info.versionName; return version; } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 版本比较 * * @param nowVersion app版本 * @param serverVersion 服务器版本 * @return */ public static boolean compareVersion(String nowVersion, String serverVersion) { if (nowVersion != null && serverVersion != null) { String[] nowVersions = nowVersion.split("\\."); String[] serverVersions = serverVersion.split("\\."); if (nowVersions != null && serverVersions != null && nowVersions.length > 1 && serverVersions.length > 1) { int nowVersionsFirst = Integer.parseInt(nowVersions[0]); int serverVersionFirst = Integer.parseInt(serverVersions[0]); int nowVersionsSecond = Integer.parseInt(nowVersions[1]); int serverVersionSecond = Integer.parseInt(serverVersions[1]); if (nowVersionsFirst < serverVersionFirst) { return true; } else if (nowVersionsFirst == serverVersionFirst && nowVersionsSecond < serverVersionSecond) { return true; } } } return false; } }
package cn.studyou.baselibrary.utils; import android.content.Context; /** * 基本功能:错误信息反馈信息 * 创建:王杰 * 创建时间:16/3/11 * 邮箱:w489657152@gmail.com */ public class ErrorMessageUtil { public static String printErrorMessage(Context context,String methodName ,String errorMessage){ return "\n############################errorMessage start ##############################\n"+MobileUtil.printMobileInfo(context)+MobileUtil.printSystemInfo()+"\n错误信息:"+errorMessage+"\n方法名:"+methodName+"\n当前app版本号:"+VersionUtil.getVersion(context)+"\n############################errorMessage end##############################"; } }
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句