/**
* 日期操作
*/
public class DateUtil {
private static final String[] weekDayStrings = {“日”, “一”, “二”, “三”, “四”, “五”, “六”};
public static final String DATETIME_PATTERN_1_1 = "yyyy-MM-dd HH:mm:ss.SSS";
public static final String DATETIME_PATTERN_2_1 = "yyyy-MM-dd HH:mm";
public static final String DATETIME_PATTERN_2_2 = "yyyy/MM/dd HH:mm";
public static final String DATETIME_PATTERN_2_3 = "yyyy年MM月dd日 HH:mm";
public static final String DATETIME_PATTERN_3_1 = "yyyy-MM-dd";
public static final String DATETIME_PATTERN_3_2 = "yyyy/MM/dd";
public static final String DATETIME_PATTERN_3_3 = "yyyy年MM月dd日";
public static final String DATETIME_PATTERN_3_4 = "yyyyMMdd";
public static final String DATETIME_PATTERN_4_1 = "yyyy";
public static final String DATETIME_PATTERN_5_1 = "MM-dd";
public static final String DATETIME_PATTERN_6_1 = "yyyy-MM-dd HH:mm:ss";
/**
* 获取任意一段时间内的简单日历,主要包含日期和星期对应关系
*
* @param startDay 起始日期
* @param endDay 结束日期
* @return 二维数组, <br>星期/日期
*/
public static String[][] getWeekDays(Calendar startDay, Calendar endDay) {
ArrayList<String[]> weekDays = new ArrayList<>();
Calendar tempStart = (Calendar) startDay.clone();
while (endDay.compareTo(tempStart) == 1) {
String[] arr = new String[2];
arr[0] = weekDayStrings[tempStart.get(Calendar.DAY_OF_WEEK) - 1];
arr[1] = String.valueOf(tempStart.get(Calendar.DAY_OF_MONTH));
weekDays.add(arr);
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
return (weekDays.toArray(new String[0][0]));
}
public static String getFormatTime(String datetime, String pattern, String pattern_new) {
if (datetime != null && datetime.trim().length() > 0) {
try {
Date date = new SimpleDateFormat(pattern).parse(datetime);
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern_new);
return dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
/**
* 获取星期几
*
* @return
*/
public static String getWeek() {
Calendar cal = Calendar.getInstance();
int i = cal.get(Calendar.DAY_OF_WEEK);
switch (i) {
case 1:
return "星期日";
case 2:
return "星期一";
case 3:
return "星期二";
case 4:
return "星期三";
case 5:
return "星期四";
case 6:
return "星期五";
case 7:
return "星期六";
default:
return "";
}
}
public static String getWeekOfDate(Date dt, Calendar calendar) {
String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
calendar.setTime(dt);
int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
/**
* 判断是白天还是晚上
*
* @return 白天返回 true ; 晚上 返回false
*/
public static boolean isDayOrNight(Context context) {
//获得内容提供者
// ContentResolver mResolver = context.getContentResolver();
//获得系统时间制
// String timeFormat = android.provider.Settings.System.getString(mResolver, android.provider.Settings.System.TIME_12_24);
// if (timeFormat.equals(“24”)) {
boolean hourFormat = DateFormat.is24HourFormat(context);
//判断时间制
if (hourFormat) {
//24小时制
SimpleDateFormat df = new SimpleDateFormat(“HH:mm:ss”);//设置日期格式
String time = df.format(new Date());
int hour = Integer.parseInt(time.substring(0, 2));
if (hour >= 6 && hour < 18) { //白天
return true;
} else {
return false;
}
} else {
//12小时制
//获得日历
Calendar mCalendar = Calendar.getInstance();
if (mCalendar.get(Calendar.AM_PM) == Calendar.AM) {
//白天
if(mCalendar.get(Calendar.HOUR)>=6){
return true;
}else{
return false;
}
}else{
if(mCalendar.get(Calendar.HOUR)<6){
return true;
}else{
//晚
return false;
}
}
}
}
public static String getCurrentTime() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());//获取当前时间
return formatter.format(curDate);
}
/**
* 将字符串转为时间戳
* @param user_time "2010年12月08日11时17分00秒"
* @return
*/
public static String getTime(String user_time) {
String re_time = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
Date d;
try {
d = sdf.parse(user_time);
long l = d.getTime();
String str = String.valueOf(l);
re_time = str.substring(0, 10);
} catch (ParseException e) {
e.printStackTrace();
}
return re_time;
}
/**
* 将yyyy年MM月dd日格式时间转换成毫秒值
* @param time
* @return
*/
public static long getLongTime(String time){
long l = 0;
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_PATTERN_3_1);
Date d;
try {
d = sdf.parse(time);
l = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return l;
}
/**
* 将毫秒值转换成yyyy年MM月dd日格式
* @param ms
* @return
*/
public static String getStringTime(long ms) {
SimpleDateFormat formatter = new SimpleDateFormat(DATETIME_PATTERN_3_1);
Date curDate = new Date(ms);//获取当前时间
return formatter.format(curDate);
}
/**
* 将yyyy-MM-dd hh:mm:ss 格式时间转换成毫秒值
* @param time
* @return
*/
public static long parseLongTime(String time){
long l = 0;
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_PATTERN_6_1);
Date d;
try {
d = sdf.parse(time);
l = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return l;
}
/**
* 将毫秒值转换成yyyy-MM-dd hh:mm:ss 格式
* @param ms
* @return
*/
public static String parseStrTime(long ms) {
SimpleDateFormat formatter = new SimpleDateFormat(DATETIME_PATTERN_6_1);
Date curDate = new Date(ms);//获取当前时间
return formatter.format(curDate);
}
}
/**
* sp工具类
*/
public class SharePreferencesUtil {
public static final String DEFAULT_SHARE_NODE = “followup_sharepreference”;
public static void saveInt(String node, String key, int value) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(node, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(key, value);
editor.commit();
}
public static void saveInt(String key, int value) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(DEFAULT_SHARE_NODE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(key, value);
editor.commit();
}
public static void saveBoolean(String node, String key, boolean value) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(node, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void saveBoolean(String key, boolean value) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(DEFAULT_SHARE_NODE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void saveString(String node, String key, String value) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(node, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static void saveString(String key, String value) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(DEFAULT_SHARE_NODE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static int getInt(String node, String key, int defaultvalue) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(node, Context.MODE_PRIVATE);
return sp.getInt(key, defaultvalue);
}
public static int getInt(String key, int defaultvalue) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(DEFAULT_SHARE_NODE, Context.MODE_PRIVATE);
return sp.getInt(key, defaultvalue);
}
public static boolean getBoolean(String node, String key, boolean defaultvalue) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(node, Context.MODE_PRIVATE);
return sp.getBoolean(key, defaultvalue);
}
public static boolean getBoolean(String key, boolean defaultvalue) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(DEFAULT_SHARE_NODE, Context.MODE_PRIVATE);
return sp.getBoolean(key, defaultvalue);
}
public static String getString(String node, String key, String defaultvalue) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(node, Context.MODE_PRIVATE);
return sp.getString(key, defaultvalue);
}
public static String getString(String key, String defaultvalue) {
SharedPreferences sp = BaseApplication.getAppContext().getSharedPreferences(DEFAULT_SHARE_NODE, Context.MODE_PRIVATE);
return sp.getString(key, defaultvalue);
}
}
/**
* @Description String 处理类
*/
public class StringUtil {
/**
* 金额转换为小数点后两位
* @param money
* @return
*/
public static String formatMoney(String money) {
if (TextUtils.isEmpty(money)) {
return “0.00”;
} else {
if(isNumber(money)) {
return String.format(“%.2f”, Double.valueOf(money));
}else {
return money;
}
}
}
/**
* 判断字符串是否是整数
*/
public static boolean isInteger(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* 判断字符串是否是浮点数
*/
public static boolean isDouble(String value) {
try {
Double.parseDouble(value);
if (value.contains("."))
return true;
return false;
} catch (NumberFormatException e) {
return false;
}
}
/**
* 判断字符串是否是数字
*/
public static boolean isNumber(String value) {
return isInteger(value) || isDouble(value);
}
}
/**
* dip转换px
*/
public class UIUtils
{
public static Context getContext()
{
return BaseApplication.getInstance();
}
public static Thread getMainThread()
{
return BaseApplication.getMainThread();
}
public static long getMainThreadId()
{
return BaseApplication.getMainThreadId();
}
public static int getScreenHight()
{
final float scale = getContext().getResources().getDisplayMetrics().heightPixels;
return (int) scale;
}
/** dip转换px */
public static int dp2px(int dip)
{
final float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (dip * scale + 0.5f);
}
/** pxz转换dip */
public static int px2dp(int px)
{
final float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
}
/** 获取主线程的handler */
public static Handler getHandler()
{
return BaseApplication.getMainThreadHandler();
}
/** 延时在主线程执行runnable */
public static boolean postDelayed(Runnable runnable, long delayMillis)
{
return getHandler().postDelayed(runnable, delayMillis);
}
/** 在主线程执行runnable */
public static boolean post(Runnable runnable)
{
return getHandler().post(runnable);
}
/** 从主线程looper里面移除runnable */
public static void removeCallbacks(Runnable runnable)
{
getHandler().removeCallbacks(runnable);
}
public static View inflate(int resId)
{
return LayoutInflater.from(getContext()).inflate(resId, null);
}
/** 获取资源 */
public static Resources getResources()
{
return getContext().getResources();
}
/** 获取文字 */
public static String getString(int resId)
{
return getResources().getString(resId);
}
/** 获取文字数组 */
public static String[] getStringArray(int resId)
{
return getResources().getStringArray(resId);
}
/** 获取dimen */
public static int getDimens(int resId)
{
return getResources().getDimensionPixelSize(resId);
}
/** 获取drawable */
public static Drawable getDrawable(int resId)
{
return getResources().getDrawable(resId);
}
/** 获取颜色 */
public static int getColor(int resId)
{
return getResources().getColor(resId);
}
/** 获取颜色选择器 */
public static ColorStateList getColorStateList(int resId)
{
return getResources().getColorStateList(resId);
}
// 判断当前的线程是不是在主线程
public static boolean isRunInMainThread()
{
return android.os.Process.myTid() == getMainThreadId();
}
public static void runInMainThread(Runnable runnable)
{
if (isRunInMainThread())
{
runnable.run();
} else
{
post(runnable);
}
}
public static void startActivity(Intent intent)
{
// MainActivity activity = MainActivity.getForegroundActivity();
// if (activity != null)
// {
// activity.startActivity(intent);
// } else
// {
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// getContext().startActivity(intent);
// }
}
/** 对toast的简易封装。线程安全,可以在非UI线程调用。 */
public static void showToastSafe(final int resId)
{
showToastSafe(getString(resId));
}
/** 对toast的简易封装。线程安全,可以在非UI线程调用。 */
public static void showToastSafe(final String str)
{
if (isRunInMainThread())
{
showToast(str);
} else
{
post(new Runnable()
{
@Override
public void run()
{
showToast(str);
}
});
}
}
private static void showToast(String str)
{
// MainActivity frontActivity = MainActivity.getForegroundActivity();
// if (frontActivity != null)
// {
// Toast.makeText(frontActivity, str, Toast.LENGTH_SHORT).show();
// }
}
public static void showNormalToast(final int resId)
{
showToast(getString(resId));
}
public static void showToast(final int resId)
{
// MainActivity frontActivity = MainActivity.getForegroundActivity();
// if (frontActivity != null)
// {
// Toast toast = Toast.makeText(getContext(), getString(resId),
// Toast.LENGTH_SHORT);
// toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, UIUtils.dp2px(200));
// toast.show();
// }
}
/**
* 判断app是否存活
* @param context
* @return
*/
public static boolean isAppAlive(Context context){
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
for (ActivityManager.RunningTaskInfo info : list) {
if (info.topActivity.getPackageName().equals(context.getPackageName()) && info.baseActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
}
/**
* 设备信息工具类,用以获取屏幕分辨率,设备识别号等硬件信息
*/
public class DeviceUtil {
private static int screenWidth = 0;
private static int screenHeight = 0;
private static int statusBarHeight = 0;
public static boolean isTablet = false;
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(float dpValue) {
final float scale = BaseApplication.getInstance().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
/**
* 获得状态栏高度
*
* @return
*/
public static int getStatusBarHeight() {
if (statusBarHeight == 0) {
Class<?> c;
Object obj;
Field field;
int x;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = BaseApplication.getInstance().getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
//
// View view = activity.getWindow().getDecorView();
// Rect rect = new Rect();
// view.getWindowVisibleDisplayFrame(rect);
// statusBarHeight = rect.top;
}
return statusBarHeight;
}
public static int getScreenWidth() {
if (screenWidth == 0) {
screenWidth = BaseApplication.getInstance().getResources().getDisplayMetrics().widthPixels;
}
return screenWidth;
}
public static DisplayMetrics getDisplayMetrics() {
return BaseApplication.getInstance().getResources().getDisplayMetrics();
}
public static int getScreenHeight() {
if (screenHeight == 0) {
screenHeight = BaseApplication.getInstance().getResources().getDisplayMetrics().heightPixels;
}
return screenHeight;
}
public static int getSDKVersion() {
return Build.VERSION.SDK_INT;
}
/**
* 判断是否平板
*
* @param context
* @return
*/
public static boolean isTablet(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));
double screenSize = diagonalPixels / (160 * dm.density);
if (screenSize >= 6) {
return true;
} else {
return false;
}
}
/**
* 判断sdk版本是否高于11.目前关系到属性动画的使用
*
* @return
*/
public static boolean isHigherThanSDK11() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return true;
}
return false;
}
/**
* 获取手机厂商
*
* @return
*/
public static String getDeviceManufacturers() {
return Build.MANUFACTURER;
}
/**
* 获取屏幕宽度和高度,单位为px
* @param context
* @return
*/
public static Point getScreenMetrics(Context context){
DisplayMetrics dm =context.getResources().getDisplayMetrics();
int w_screen = dm.widthPixels;
int h_screen = dm.heightPixels;
AbLogUtil.d( "Screen---Width = " + w_screen + " Height = " + h_screen + " densityDpi = " + dm.densityDpi);
return new Point(w_screen, h_screen);
}
/**
* 获取屏幕长宽比
* @param context
* @return
*/
public static float getScreenRate(Context context){
Point P = getScreenMetrics(context);
float H = P.y;
float W = P.x;
return (H/W);
}
}
/**
*软键盘管理类
/
public class RstInputMethodManager {
/**
* 隐藏输入框
*
* @param view
*/
public static void hideSoftInput(EditText view) {
hideSoftInput(view.getWindowToken());
}
/**
* 隐藏输入框
*/
public static void hideSoftInput(IBinder windowToken) {
final InputMethodManager imm = (InputMethodManager) BaseApplication.getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);
final IMMResult result = new IMMResult();
if (null != windowToken) {
imm.hideSoftInputFromWindow(windowToken, 0, result);
}
}
/**
* 显示 输入框
*
* @param view
*/
public static void showSoftInput(EditText view) {
final InputMethodManager imm = (InputMethodManager) BaseApplication.getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);
final IMMResult result = new IMMResult();
imm.showSoftInput(view, 0, result);
view.postDelayed(new Runnable() {
@Override
public void run() {
int res = result.getResult();
if (res != InputMethodManager.RESULT_SHOWN && res != InputMethodManager.RESULT_UNCHANGED_HIDDEN) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
}, 500);
view.requestFocus();
}
public static class IMMResult extends ResultReceiver {
public int result = -1;
public IMMResult() {
super(null);
}
@Override
public void onReceiveResult(int r, Bundle data) {
result = r;
}
public int getResult() {
return result;
}
}
}