Android开发常用工具类
来源:互联网 发布:淘宝代购海外直邮真假 编辑:程序博客网 时间:2024/04/28 07:19
做开发也有一段时间了,自己的加上网上找的也有比较不错的工具类,这里和大家分享下项目中比较常用的一些工具类。
/** * App相关的工具类 * 1.安装指定路径下的Apk * 2.卸载指定包名的App * 3.获取App名称 * 4.获取当前App版本号 * 5.获取当前App版本Code * 6. 打开指定包名的App * 7.打开指定包名的App应用信息界面 * 8.分享Apk信息 * 9.获取App信息的一个封装类(包名、版本号、应用信息、图标、名称等) * 10.判断当前App处于前台还是后台 */public class AppUtilStudio { /** * 安装指定路径下的Apk */ public static void installApk(String filePath, Activity activity) { Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive"); activity.startActivityForResult(intent, 0); } /** * 卸载指定包名的App */ public static void uninstallApp(String packageName, Activity activity) { Intent intent = new Intent(); intent.setAction("android.intent.action.DELETE"); intent.addCategory("android.intent.category.DEFAULT"); intent.setData(Uri.parse("package:" + packageName)); activity.startActivityForResult(intent, 0); } /** * 获取App名称 */ public static String getAppName(Context context) { try { PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0); int labelRes = packageInfo.applicationInfo.labelRes; return context.getResources().getString(labelRes); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } /** * 获取当前App版本号 */ public static String getVersionName(Context context) { String versionName = null; PackageManager pm = context.getPackageManager(); PackageInfo info = null; try { info = pm.getPackageInfo(context.getApplicationContext().getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (info != null) { versionName = info.versionName; } return versionName; } /** * 获取当前App版本Code */ public static int getVersionCode(Context context) { int versionCode = 0; PackageManager pm = context.getPackageManager(); PackageInfo info = null; try { info = pm.getPackageInfo(context.getApplicationContext().getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (info != null) { versionCode = info.versionCode; } return versionCode; } /** * 打开指定包名的App */ public static void openOtherApp(String packageName, Context context) { PackageManager manager = context.getPackageManager(); Intent launchIntentForPackage = manager.getLaunchIntentForPackage(packageName); if (launchIntentForPackage != null) { context.startActivity(launchIntentForPackage); } } /** * 打开指定包名的App应用信息界面 */ public static void showAppInfo(String packageName, Context context) { Intent intent = new Intent(); intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); intent.setData(Uri.parse("package:" + packageName)); context.startActivity(intent); } /** * 分享Apk信息 */ public static void shareApkInfo(String info, Context context) { Intent intent = new Intent(); intent.setAction("android.intent.action.SEND"); intent.addCategory("android.intent.category.DEFAULT"); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, info); context.startActivity(intent); } /** * 获取App信息的一个封装类(包名、版本号、应用信息、图标、名称等) */ public static List<AppInfo> getAppInfos(Context context) { List<AppInfo> list = new ArrayList<AppInfo>(); //获取应用程序信息 //包的管理者 PackageManager pm = context.getPackageManager(); //获取系统中安装到所有软件信息 List<PackageInfo> installedPackages = pm.getInstalledPackages(0); for (PackageInfo packageInfo : installedPackages) { //获取包名 String packageName = packageInfo.packageName; //获取版本号 String versionName = packageInfo.versionName; //获取application ApplicationInfo applicationInfo = packageInfo.applicationInfo; int uid = applicationInfo.uid; //获取应用程序的图标 Drawable icon = applicationInfo.loadIcon(pm); //获取应用程序的名称 String name = applicationInfo.loadLabel(pm).toString(); //是否是用户程序 //获取应用程序中相关信息,是否是系统程序和是否安装到SD卡 boolean isUser; int flags = applicationInfo.flags; if ((applicationInfo.FLAG_SYSTEM & flags) == applicationInfo.FLAG_SYSTEM) { //系统程序 isUser = false; } else { //用户程序 isUser = true; } //是否安装到SD卡 boolean isSD; if ((applicationInfo.FLAG_EXTERNAL_STORAGE & flags) == applicationInfo.FLAG_EXTERNAL_STORAGE) { //安装到了SD卡 isSD = true; } else { //安装到手机中 isSD = false; } //添加到bean中 AppInfo appInfo = new AppInfo(name, icon, packageName, versionName, isSD, isUser); //将bean存放到list集合 list.add(appInfo); } return list; } // 封装软件信息的bean类 static class AppInfo { //名称 private String name; //图标 private Drawable icon; //包名 private String packagName; //版本号 private String versionName; //是否安装到SD卡 private boolean isSD; //是否是用户程序 private boolean isUser; public AppInfo() { super(); } public AppInfo(String name, Drawable icon, String packagName, String versionName, boolean isSD, boolean isUser) { super(); this.name = name; this.icon = icon; this.packagName = packagName; this.versionName = versionName; this.isSD = isSD; this.isUser = isUser; } } // 需添加<uses-permission android:name="android.permission.GET_TASKS"/>// 并且必须是系统应用该方法才有效 /** * 判断当前App处于前台还是后台 */ public static boolean isApplicationBackground(final Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); @SuppressWarnings("deprecation") List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; }}
自定义Toast,默认的Toast如果点击了10次,那么时间将是10次的总和。这个工具类方便的解决这种问题
public class CustomToast { private static Toast mToast; private static Handler mhandler = new Handler(); private static Runnable r = new Runnable() { public void run() { mToast.cancel(); } }; public static void showToast(Context context, String text, int duration) { mhandler.removeCallbacks(r); if (null != mToast) { mToast.setText(text); } else { mToast = Toast.makeText(context, text, Toast.LENGTH_LONG); } mhandler.postDelayed(r, 5000); mToast.show(); } public static void showToast(Context context, int strId, int duration) { showToast(context, context.getString(strId), duration); }}
/** * JSON工具类 * */public abstract class JSONUtil { public static final String EMPTY_JSON_OBJECT_STRING = "{}"; public static JSONObject merge(JSONObject... jsonObjects) { int length = 0; if (null == jsonObjects || 0 == (length = jsonObjects.length)) { return new JSONObject(); } JSONObject base = jsonObjects[0]; for (int i = 1; i < length; i++) { JSONObject other = jsonObjects[i]; if (null == other) { continue; } for (Entry<String, Object> entry : other.entrySet()) { base.put(entry.getKey(), entry.getValue()); } } return base; } public static JSONObject merge(JSONObject base, String key, Object value) { if (null == base) { base = new JSONObject(); } if (null != key) { base.put(key, value); } return base; } public static JSONObject merge(JSONObject base, Map<String, Object> map) { if (null == base) { base = new JSONObject(); } if (null != map && !map.isEmpty()) { for (Entry<String, Object> entry : map.entrySet()) { base.put(entry.getKey(), entry.getValue()); } } return base; } public static JSONObject merge(JSONObject base, Properties prop) { if (null == base) { base = new JSONObject(); } if (null != prop && !prop.isEmpty()) { for (Entry<Object, Object> entry : prop.entrySet()) { base.put((String) entry.getKey(), entry.getValue()); } } return base; } public static boolean equals(JSONObject o, JSONObject ao) { if (null == o) { return null == ao; } return o.equals(ao); } public static boolean equals(JSONArray o, JSONArray ao) { if (null == o) { return null == ao; } return o.equals(ao); } public static boolean equals(JSONObject o, JSONObject ao, String[] keys) { if (null == o) { return null == ao; } if (o.equals(ao)) { return true; } if (null == keys || 0 == keys.length) { return true; } for (String key : keys) { Object ov = o.get(key); Object aov = ao.get(key); if (null == ov) { if (null != aov) { return false; } } else { if (null == aov) { return false; } else { if (!ov.equals(aov)) { return false; } } } } return true; } public static JSONObject clone(JSONObject o) { if (null == o) { return null; } return (JSONObject) o.clone(); } public static JSONArray clone(JSONArray o) { if (null == o) { return null; } return (JSONArray) o.clone(); } /** * * @date 2016年7月16日 * @Description: 将from入参的属性赋值到 toClass对象 * @param from * @param toClass * @return T */ public static <F, T> T trans(F from, Class<T> toClass) { String jsonString = JSON.toJSONString(from); return trans(jsonString, toClass); } /** * JSON字符串转实体对象 * * @param jsonString * @param toClass * @return */ public static <T> T trans(String jsonString, Class<T> toClass) { return JSON.parseObject(jsonString, toClass); } /** * JSON字符串转List * * @param jsonList * @param toClass * @return */ public static <T> List<T> trans2List(String jsonList, Class<T> toClass) { return JSON.parseArray(jsonList, toClass); } /** * JSON字符串赚Map * * @param jsonMap * @param toClass * @return */ public static <T> Map<String, T> trans2Map(String jsonMap, Class<T> toClass) { return (Map<String, T>) JSON.parse(jsonMap); } public static <T> T trans(Map<String, Object> from, Class<T> toClass) { JSONObject json = new JSONObject(from); return JSON.toJavaObject(json, toClass); } public static <T> List<T> trans(List<Map<String, Object>> fromList, Class<T> toElementClass) { int size = fromList.size(); List<T> resultList = new ArrayList<T>(size); for (int i = 0; i < size; i++) { Map<String, Object> from = fromList.get(i); T element = null; if (null != from) { element = trans(from, toElementClass); } resultList.add(element); } return resultList; } /** * @date 2016年7月13日 * @Description: 遍历修改里面的类型 * @param fromList * @param toElementClass * @return List<T> */ public static <T> List<T> transInSide(List<?> fromList, Class<T> toElementClass) { int size = fromList.size(); List<T> resultList = new ArrayList<T>(size); for (int i = 0; i < size; i++) { T element = null; if (null != fromList.get(i)) { if (fromList.get(i).getClass() == String.class) { element = trans(fromList.get(i).toString(), toElementClass); } else { element = trans(fromList.get(i), toElementClass); } } resultList.add(element); } return resultList; }}
/** * 计算ListView高度的工具类 */public class ListViewHeight { /** * 计算listview总高度 * * @param listView */ public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); params.height += 5;//if without this statement,the listview will be a little short listView.setLayoutParams(params); }}
/** * 网络工具类 */public final class NetUtil { /** * 判断网络连接是否打开,包括移动数据连接 * * @param context 上下文 * @return 是否联网 */ public static boolean isNetworkAvailable(Context context) { boolean netstate = false; ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == State.CONNECTED) { netstate = true; break; } } } } return netstate; } /** * GPS是否打开 * * @param context 上下文 * @return Gps是否可用 */ public static boolean isGpsEnabled(Context context) { LocationManager lm = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); return lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } /** * 检测当前打开的网络类型是否WIFI * * @param context 上下文 * @return 是否是Wifi上网 */ public static boolean isWifi(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); return activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI; } /** * 检测当前打开的网络类型是否3G * * @param context 上下文 * @return 是否是3G上网 */ public static boolean is3G(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); return activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE; } /** * 检测当前开打的网络类型是否4G * * @param context 上下文 * @return 是否是4G上网 */ public static boolean is4G(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.isConnectedOrConnecting()) { if (activeNetInfo.getType() == TelephonyManager.NETWORK_TYPE_LTE) { return true; } } return false; } /** * 只是判断WIFI * * @param context 上下文 * @return 是否打开Wifi */ public static boolean isWiFi(Context context) { ConnectivityManager manager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .getState(); return wifi == State.CONNECTED || wifi == State.CONNECTING; } /** * IP地址校验 * * @param ip 待校验是否是IP地址的字符串 * @return 是否是IP地址 */ public static boolean isIP(String ip) { Pattern pattern = Pattern .compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b"); Matcher matcher = pattern.matcher(ip); return matcher.matches(); } /** * IP转化成int数字 * * @param addr IP地址 * @return Integer */ public static int ipToInt(String addr) { String[] addrArray = addr.split("\\."); int num = 0; for (int i = 0; i < addrArray.length; i++) { int power = 3 - i; num += ((Integer.parseInt(addrArray[i]) % 256 * Math .pow(256, power))); } return num; } /** * 枚举网络状态 NET_NO:没有网络 NET_2G:2g网络 NET_3G:3g网络 NET_4G:4g网络 NET_WIFI:wifi * NET_UNKNOWN:未知网络 */ public enum NetState { NET_NO, NET_2G, NET_3G, NET_4G, NET_WIFI, NET_UNKNOWN } /** * 判断当前是否网络连接 * * @param context 上下文 * @return 状态码 */ public NetState isConnected(Context context) { NetState stateCode = NetState.NET_NO; ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null && ni.isConnectedOrConnecting()) { switch (ni.getType()) { case ConnectivityManager.TYPE_WIFI: stateCode = NetState.NET_WIFI; break; case ConnectivityManager.TYPE_MOBILE: switch (ni.getSubtype()) { case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: stateCode = NetState.NET_2G; break; case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: stateCode = NetState.NET_3G; break; case TelephonyManager.NETWORK_TYPE_LTE: stateCode = NetState.NET_4G; break; default: stateCode = NetState.NET_UNKNOWN; } break; default: stateCode = NetState.NET_UNKNOWN; } } return stateCode; } /** * 获取URL中参数 并返回Map * @param url * @return */ public static Map<String, String> getUrlParams(String url) { Map<String, String> params = null; try { String[] urlParts = url.split("\\?"); if (urlParts.length > 1) { params = new HashMap<>(); String query = urlParts[1]; for (String param : query.split("&")) { String[] pair = param.split("="); String key = URLDecoder.decode(pair[0], "UTF-8"); String value = ""; if (pair.length > 1) { value = URLDecoder.decode(pair[1], "UTF-8"); } params.put(key, value); } } } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } return params; } /** * 是否是网络链接 * @param url * @return */ public static boolean isUrl(String url) { try { URL url1 = new URL(url); return true; } catch (MalformedURLException e) { e.printStackTrace(); return false; } }}
/** * 手机组件调用工具类 */public final class PhoneUtil { /** * Don't let anyone instantiate this class. */ private PhoneUtil() { throw new Error("Do not need instantiate!"); } /** * 调用系统发短信界面 * * @param activity Activity * @param phoneNumber 手机号码 * @param smsContent 短信内容 */ public static void sendMessage(Context activity, String phoneNumber, String smsContent) { if (phoneNumber == null || phoneNumber.length() < 4) { return; } Uri uri = Uri.parse("smsto:" + phoneNumber); Intent it = new Intent(Intent.ACTION_SENDTO, uri); it.putExtra("sms_body", smsContent); it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(it); } /** * 调用系统打电话界面 * * @param context 上下文 * @param phoneNumber 手机号码 */ public static void callPhones(Context context, String phoneNumber) { if (phoneNumber == null || phoneNumber.length() < 1) { return; } Uri uri = Uri.parse("tel:" + phoneNumber); Intent intent = new Intent(Intent.ACTION_CALL, uri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling return; } context.startActivity(intent); }}
/** * 窗口工具箱 */public final class WindowUtils { /** * Don't let anyone instantiate this class. */ private WindowUtils() { throw new Error("Do not need instantiate!"); } /** * 获取当前窗口的旋转角度 * * @param activity * @return */ @TargetApi(Build.VERSION_CODES.FROYO) public static int getDisplayRotation(Activity activity) { switch (activity.getWindowManager().getDefaultDisplay().getRotation()) { case Surface.ROTATION_0: return 0; case Surface.ROTATION_90: return 90; case Surface.ROTATION_180: return 180; case Surface.ROTATION_270: return 270; default: return 0; } } /** * 当前是否是横屏 * * @param context * @return */ public static boolean isLandscape(Context context) { return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; } /** * 当前是否是竖屏 * * @param context * @return */ public static boolean isPortrait(Context context) { return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; }}
/** * 日期时间工具类 * */public class DateUtils extends android.text.format.DateUtils { public static String mygetDate(){ SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm"); Date curDate = new Date(System.currentTimeMillis());//获取当前时间 String str = formatter.format(curDate); return str; } /** * The enum Difference mode. */ public enum DifferenceMode { /** * Second difference mode. */ Second, /** * Minute difference mode. */ Minute, /** * Hour difference mode. */ Hour, /** * Day difference mode. */ Day } // 获取当前日期 @SuppressLint("SimpleDateFormat") public static String getCurrentDate() { Calendar c = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(c.getTime()); } public static int[] getYMDArray(String datetime, String splite) { int[] date = {0, 0, 0, 0, 0}; if (datetime != null && datetime.length() > 0) { String[] dates = datetime.split(splite); int position = 0; for (String temp : dates) { date[position] = Integer.valueOf(temp); position++; } } return date; } /** * 将当前时间戳转化为标准时间函数 * * @param timestamp * @return */ @SuppressLint("SimpleDateFormat") public static String getTime(String time1) { int timestamp = Integer.parseInt(time1);// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String time = null; try { Date currentdate = new Date(); // 当前时间 long i = (currentdate.getTime() / 1000 - timestamp) / (60); System.out.println(currentdate.getTime()); System.out.println(i); Timestamp now = new Timestamp(System.currentTimeMillis()); // 获取系统当前时间 System.out.println("now-->" + now); // 返回结果精确到毫秒。 String str = sdf.format(new Timestamp(intToLong(timestamp))); time = str.substring(11, 16); String month = str.substring(5, 7); String day = str.substring(8, 10); System.out.println(str); System.out.println(time); System.out.println(getDate(month, day)); time = getDate(month, day) + time; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return time; } public static String getTime(int timestamp) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = null; try { String str = sdf.format(new Timestamp(intToLong(timestamp))); time = str.substring(11, 16); String month = str.substring(5, 7); String day = str.substring(8, 10); time = getDate(month, day) + time; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return time; } public static String getHMS(long timestamp) { SimpleDateFormat sdf = new SimpleDateFormat("HH时mm分ss"); String time = null; try { return sdf.format(new Date(timestamp)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return time; } /** * 将当前时间戳转化为标准时间函数 * * @param timestamp * @return */ @SuppressLint("SimpleDateFormat") public static String getHMS(String time) { long timestamp = Long.parseLong(time); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); try { String str = sdf.format(new Timestamp(timestamp)); return str; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return time; } // java Timestamp构造函数需传入Long型 public static long intToLong(int i) { long result = (long) i; result *= 1000; return result; } @SuppressLint("SimpleDateFormat") public static String getDate(String month, String day) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 24小时制 Date d = new Date(); ; String str = sdf.format(d); @SuppressWarnings("unused") String nowmonth = str.substring(5, 7); String nowday = str.substring(8, 10); String result = null; int temp = Integer.parseInt(nowday) - Integer.parseInt(day); switch (temp) { case 0: result = "今天"; break; case 1: result = "昨天"; break; case 2: result = "前天"; break; default: StringBuilder sb = new StringBuilder(); sb.append(Integer.parseInt(month) + "月"); sb.append(Integer.parseInt(day) + "日"); result = sb.toString(); break; } return result; } /* 将字符串转为时间戳 */ public static String getTimeToStamp(String time) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒", Locale.CHINA); Date date = new Date(); try { date = sdf.parse(time); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } String tmptime = String.valueOf(date.getTime()).substring(0, 10); return tmptime; } @SuppressLint("SimpleDateFormat") public static String getYMD(long timestamp) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(new Date(timestamp)); } public static String getTimestamp() { long time = System.currentTimeMillis() / 1000; return String.valueOf(time); } /** * Calculate different second long. * * @param startDate the start date * @param endDate the end date * @return the long */ public static long calculateDifferentSecond(Date startDate, Date endDate) { return calculateDifference(startDate, endDate, DifferenceMode.Second); } /** * Calculate different minute long. * * @param startDate the start date * @param endDate the end date * @return the long */ public static long calculateDifferentMinute(Date startDate, Date endDate) { return calculateDifference(startDate, endDate, DifferenceMode.Minute); } /** * Calculate different hour long. * * @param startDate the start date * @param endDate the end date * @return the long */ public static long calculateDifferentHour(Date startDate, Date endDate) { return calculateDifference(startDate, endDate, DifferenceMode.Hour); } /** * Calculate different day long. * * @param startDate the start date * @param endDate the end date * @return the long */ public static long calculateDifferentDay(Date startDate, Date endDate) { return calculateDifference(startDate, endDate, DifferenceMode.Day); } /** * Calculate different second long. * * @param startTimeMillis the start time millis * @param endTimeMillis the end time millis * @return the long */ public static long calculateDifferentSecond(long startTimeMillis, long endTimeMillis) { return calculateDifference(startTimeMillis, endTimeMillis, DifferenceMode.Second); } /** * Calculate different minute long. * * @param startTimeMillis the start time millis * @param endTimeMillis the end time millis * @return the long */ public static long calculateDifferentMinute(long startTimeMillis, long endTimeMillis) { return calculateDifference(startTimeMillis, endTimeMillis, DifferenceMode.Minute); } /** * Calculate different hour long. * * @param startTimeMillis the start time millis * @param endTimeMillis the end time millis * @return the long */ public static long calculateDifferentHour(long startTimeMillis, long endTimeMillis) { return calculateDifference(startTimeMillis, endTimeMillis, DifferenceMode.Hour); } /** * Calculate different day long. * * @param startTimeMillis the start time millis * @param endTimeMillis the end time millis * @return the long */ public static long calculateDifferentDay(long startTimeMillis, long endTimeMillis) { return calculateDifference(startTimeMillis, endTimeMillis, DifferenceMode.Day); } /** * Calculate difference long. * * @param startTimeMillis the start time millis * @param endTimeMillis the end time millis * @param mode the mode * @return the long */ public static long calculateDifference(long startTimeMillis, long endTimeMillis, DifferenceMode mode) { return calculateDifference(new Date(startTimeMillis), new Date(endTimeMillis), mode); } /** * Calculate difference long. * * @param startDate the start date * @param endDate the end date * @param mode the mode * @return the long */ public static long calculateDifference(Date startDate, Date endDate, DifferenceMode mode) { long[] different = calculateDifference(startDate, endDate); if (mode.equals(DifferenceMode.Minute)) { return different[2]; } else if (mode.equals(DifferenceMode.Hour)) { return different[1]; } else if (mode.equals(DifferenceMode.Day)) { return different[0]; } else { return different[3]; } } /** * Calculate difference long [ ]. * * @param startDate the start date * @param endDate the end date * @return the long [ ] */ public static long[] calculateDifference(Date startDate, Date endDate) { return calculateDifference(endDate.getTime() - startDate.getTime()); } /** * Calculate difference long [ ]. * * @param differentMilliSeconds the different milli seconds * @return the long [ ] */ public static long[] calculateDifference(long differentMilliSeconds) { long secondsInMilli = 1000;//1s==1000ms long minutesInMilli = secondsInMilli * 60; long hoursInMilli = minutesInMilli * 60; long daysInMilli = hoursInMilli * 24; long elapsedDays = differentMilliSeconds / daysInMilli; differentMilliSeconds = differentMilliSeconds % daysInMilli; long elapsedHours = differentMilliSeconds / hoursInMilli; differentMilliSeconds = differentMilliSeconds % hoursInMilli; long elapsedMinutes = differentMilliSeconds / minutesInMilli; differentMilliSeconds = differentMilliSeconds % minutesInMilli; long elapsedSeconds = differentMilliSeconds / secondsInMilli; LogUtils.debug(String.format("different: %d ms, %d days, %d hours, %d minutes, %d seconds", differentMilliSeconds, elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds)); return new long[]{elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds}; } /** * Calculate days in month int. * * @param month the month * @return the int */ public static int calculateDaysInMonth(int month) { return calculateDaysInMonth(0, month); } /** * Calculate days in month int. * * @param year the year * @param month the month * @return the int */ public static int calculateDaysInMonth(int year, int month) { // 添加大小月月份并将其转换为list,方便之后的判断 String[] bigMonths = {"1", "3", "5", "7", "8", "10", "12"}; String[] littleMonths = {"4", "6", "9", "11"}; List<String> bigList = Arrays.asList(bigMonths); List<String> littleList = Arrays.asList(littleMonths); // 判断大小月及是否闰年,用来确定"日"的数据 if (bigList.contains(String.valueOf(month))) { return 31; } else if (littleList.contains(String.valueOf(month))) { return 30; } else { if (year <= 0) { return 29; } // 是否闰年 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { return 29; } else { return 28; } } } /** * 月日时分秒,0-9前补0 * * @param number the number * @return the string */ @NonNull public static String fillZero(int number) { return number < 10 ? "0" + number : "" + number; } /** * 功能:判断日期是否和当前date对象在同一天。 * 参见:http://www.cnblogs.com/myzhijie/p/3330970.html * * @param date 比较的日期 * @return boolean 如果在返回true,否则返回false。 * @author 沙琪玛 QQ:862990787 Aug 21, 2013 7:15:53 AM */ public static boolean isSameDay(Date date) { if (date == null) { throw new IllegalArgumentException("date is null"); } Calendar nowCalendar = Calendar.getInstance(); Calendar newCalendar = Calendar.getInstance(); newCalendar.setTime(date); return (nowCalendar.get(Calendar.ERA) == newCalendar.get(Calendar.ERA) && nowCalendar.get(Calendar.YEAR) == newCalendar.get(Calendar.YEAR) && nowCalendar.get(Calendar.DAY_OF_YEAR) == newCalendar.get(Calendar.DAY_OF_YEAR)); } /** * 将yyyy-MM-dd HH:mm:ss字符串转换成日期<br/> * * @param dateStr 时间字符串 * @param dataFormat 当前时间字符串的格式。 * @return Date 日期 ,转换异常时返回null。 */ public static Date parseDate(String dateStr, String dataFormat) { try { @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat(dataFormat); Date date = dateFormat.parse(dateStr); return new Date(date.getTime()); } catch (Exception e) { LogUtils.warn(e); return null; } } /** * 将yyyy-MM-dd HH:mm:ss字符串转换成日期<br/> * * @param dateStr yyyy-MM-dd HH:mm:ss字符串 * @return Date 日期 ,转换异常时返回null。 */ public static Date parseDate(String dateStr) { return parseDate(dateStr, "yyyy-MM-dd HH:mm:ss"); }}
0 0
- Android开发常用工具类
- Android开发常用工具类
- Android开发常用工具类
- Android开发常用工具类
- Android开发常用工具类
- Android开发常用工具类
- Android开发常用工具类
- Android开发常用工具类
- Android开发常用工具类
- Android开发常用工具类
- android 开发常用工具类
- Android开发常用工具类
- Android快速开发常用工具类
- Android开发 几个常用工具类
- 【福利】-Android开发常用工具类
- Android快速开发常用工具类
- android开发常用工具类集合
- android开发常用工具类网站
- Python3--Print用法
- Android使用DiskLruCachede的异常和封装
- linux下mysql安装
- 【无中生有】---15---分布式业务系统原子性控制
- jquey添加修改列表内容
- Android开发常用工具类
- sphinx+scws 全文检索使用之 sphinx配置文件详解
- 由文件的路径通过其他应用打开图片,PPT,Word,excel,PDF
- Mockito与PowerMock
- 回话跟踪技术Cookie
- 一个诡异的crontab执行提示1045错误码的MySQL问题定位
- 项目实践--跳动的小鸟
- 关于LeetCode中Implement strStr()一题的理解
- 动手写一个Android数据加载时界面状态切换的开源库