Android开发工具系列:Utils工具

Androi开发工具系列:SharedPreference管理工具
Android开发工具系列:弱引用工具
Android开发工具系列:Utils工具

文章目录

  • 1 TimeUtils
  • 2 NTPTimeUtils
  • 3 DrawableUtils
  • 4 DensityUtils
  • 5 SDcardUtils
  • 6 JSONUtils
  • 7 KeyboardUtils
  • 8 ScreenUtils

1 TimeUtils

public class TimeUtils {
     
    public static final int YEAR = 0;
    public static final int MONTH = 1;
    public static final int DAY = 2;
    public static final int HOUR = 3;
    public static final int MINUTE = 4;

    private static final DecimalFormat sDecimalFormat = new DecimalFormat("00");

    @SuppressLint("SimpleDateFormat")
    private static final SimpleDateFormat sDate24HourFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @SuppressLint("SimpleDateFormat")
    private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    private TimeUtils() {
     
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 获取当前年份
     */
    public static int getYear() {
     
        return getYear("");
    }

    public static int getYear(String year) {
     
        if (TextUtils.isEmpty(year)) {
     
            return new Date().getYear() + 1900;
        }
        return Integer.valueOf(year);
    }

    /**
     * 获取当前月份
     */
    public static int getMonth() {
     
        return getMonth("");
    }

    public static int getMonth(String month) {
     
        if (TextUtils.isEmpty(month)) {
     
            return new Date().getMonth() + 1;
        }
        return Integer.valueOf(month);
    }

    /**
     * 获取当前日期
     */
    public static int getDay() {
     
        return getDay("");
    }

    public static int getDay(String day) {
     
        if (TextUtils.isEmpty(day)) {
     
            return new Date().getDate();
        }
        return Integer.valueOf(day);
    }

    /**
     * 获取当前小时
     */
    public static int getHour() {
     
        return getHour("");
    }

    public static int getHour(String hour) {
     
        if (TextUtils.isEmpty(hour)) {
     
            return new Date().getHours();
        }
        return Integer.valueOf(hour);
    }

    /**
     * 获取当前分钟
     */
    public static int getMinute() {
     
        return getMinute("");
    }

    public static int getMinute(String minute) {
     
        if (TextUtils.isEmpty(minute)) {
     
            return new Date().getMinutes();
        }
        return Integer.valueOf(minute);
    }

    /**
     * 根据年月日获取星期几
     */
    public static int getDayOfWeek(int year, int month, int day) {
     
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.YEAR, year);
        instance.set(Calendar.MONTH, month - 1);
        instance.set(Calendar.DAY_OF_MONTH, day);
        return instance.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 传递星期几获取当月相同星期的具体日期
     *
     * @param targetDayOfWeek 星期,targetDayOfWeek=Calendar.SUNDAY~SATURDAY
     * @return [15, 20]
     */
    public static List<Integer> getDayOfMonthsByDayOfWeek(int year, int month, int targetDayOfWeek) {
     
        int maxDayOfMonth = getDayOfMonthByYearAndMonth(year, month);
        List<Integer> dayOfWeeks = new ArrayList<>();
        for (int i = 1; i <= maxDayOfMonth; i++) {
     
            int dayOfWeek = getDayOfWeek(year, month, i);
            if (dayOfWeek == targetDayOfWeek) {
     
                dayOfWeeks.add(i);
            }
        }
        return dayOfWeeks;
    }

    public static int getWeekByStr(Context context, String week) {
     
        if (TextUtils.equals(week, context.getString(R.string.sunday))) {
     
            return Calendar.SUNDAY;
        } else if (TextUtils.equals(week, context.getString(R.string.monday))) {
     
            return Calendar.MONDAY;
        } else if (TextUtils.equals(week, context.getString(R.string.tuesday))) {
     
            return Calendar.TUESDAY;
        } else if (TextUtils.equals(week, context.getString(R.string.wednesday))) {
     
            return Calendar.WEDNESDAY;
        } else if (TextUtils.equals(week, context.getString(R.string.thursday))) {
     
            return Calendar.THURSDAY;
        } else if (TextUtils.equals(week, context.getString(R.string.friday))) {
     
            return Calendar.FRIDAY;
        } else if (TextUtils.equals(week, context.getString(R.string.saturday))) {
     
            return Calendar.SATURDAY;
        } else {
     
            return -1;
        }
    }

    /**
     * 获取某年某月的最大天数
     */
    public static int getDayOfMonthByYearAndMonth(int year, int month) {
     
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.YEAR, year);
        instance.set(Calendar.MONTH, month - 1);
        return instance.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 计算两个日期之间的总秒数
     */
    public static int getTotalSeconds(LocalTime startTime, LocalTime endTime) {
     
        if (endTime.hour < startTime.hour) endTime.day += 1; // 计算时间不需要理会超过当前月份天数问题,超过一天直接+1计算
        DateModel dateModel = new DateModel(startTime, endTime);
        return dateModel.getBetweenSeconds();
    }

    /**
     * 根据提供的开始年月日时分和秒数,计算经过seconds秒后的具体日期
     *
     * @return [year, month, day, hour] 通过TimeUtils上的常量索引YEAR、MONTH、DAY、HOUR、MINUTE获取 
     */
    public static int[] getEndDate(int year, int month, int day, int hour, int minute, int seconds) {
     
        long startTime = new Date(year, month, day, hour, minute).getTime();
        long endTime = startTime + seconds * 1000;

        int[] endDateArr = new int[5];
        Date endDate = new Date(endTime);
        endDateArr[YEAR] = endDate.getYear();
        endDateArr[MONTH] = endDate.getMonth();
        endDateArr[DAY] = endDate.getDate();
        endDateArr[HOUR] = endDate.getHours();
        endDateArr[MINUTE] = endDate.getMinutes();
        int dayOfMonth = getDayOfMonthByYearAndMonth(endDateArr[YEAR], endDateArr[MONTH]);
        // 计算的天数超过了当月的总天数,月份+1
        if (endDateArr[DAY] > dayOfMonth) {
     
            endDateArr[MONTH]++;
            endDateArr[DAY] = 1;
            // 计算的月份超过了总月份,年份+1
            if (endDateArr[MONTH] > 12) {
     
                endDateArr[YEAR]++;
                endDateArr[MONTH] = 1;
            }
        }
        return endDateArr;
    }

    public static boolean isMonthValid(int month) {
     
        return month >= 0 && month <= 12;
    }

    public static boolean isHourValid(int hour) {
     
        return hour >= 0 && hour <= 23;
    }

    public static boolean isMinuteValid(int minute) {
     
        return minute >= 0 && minute <= 59;
    }

    /**
     * 根据秒数获取格式化时分秒
     *
     * @return 00:00:00
     */
    public static String getDecimalFormatTime(int seconds) {
     
        String hour = sDecimalFormat.format(seconds / 3600);
        String minute = sDecimalFormat.format(seconds % 3600 / 60);
        String second = sDecimalFormat.format(seconds % 60);
        return hour + ":" + minute + ":" + second;
    }

    /**
     * 根据年月日时分秒获取当前时区的时间(已处理夏令时)
     *
     * @return 00:00:00
     */
    public String formatZoneTime(Context context, int year, int month, int day, int hour, int minute, int second) {
     
        String zone = TimeZone.getDefault().getID();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     
            return formatZoneTimeAndroidO(context, createLocalDateTime(year, month, day, hour, minute, second), ZoneId.of(zone));
        } else {
     
            TimeZone timeZone = TimeZone.getTimeZone(zone);
            Calendar.getInstance().setTimeZone(timeZone);
            SimpleDateFormat format = NtpTimeUtils.is24HourFormat(context) ? sDate24HourFormat : sDateFormat;
            format.setTimeZone(timeZone);
            return timeFormat(format, getDateTime(year, month - 1, day, hour, minute, second));
        }
    }

    public String timeFormat(SimpleDateFormat format, long time) {
     
        return timeFormat(format, new Date(time));
    }

    public String timeFormat(SimpleDateFormat format, Date date) {
     
        return format.format(date);
    }

    /**
     * 传递年月日时分秒获取日期Date
     */
    public Date getDateTime(int year, int month, int day, int hour, int minute, int second) {
     
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month); // 需要注意Calendar的月份计算时要-1,获取时要+1
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        return calendar.getTime(); // Date.getTime()获取时间戳
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private LocalDateTime createLocalDateTime(int year, int month, int day, int hour, int minute, int second) {
     
        return LocalDateTime.of(year, month, day, hour, minute, second);
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String formatZoneTimeAndroidO(Context context, LocalDateTime time, ZoneId zoneId) {
     
        ZonedDateTime zonedDateTime = time.atZone(ZoneId.systemDefault());
        ZonedDateTime zoneSameInstant = zonedDateTime.withZoneSameInstant(zoneId);
        long hours = Duration.between(zoneSameInstant.withEarlierOffsetAtOverlap(),
                zoneSameInstant.withLaterOffsetAtOverlap()).toHours();
        zoneSameInstant = zoneSameInstant.plusHours(hours);

        String format = NtpTimeUtils.is24HourFormat(context) ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd hh:mm:ss";
        return zoneSameInstant.format(DateTimeFormatter.ofPattern(format));
    }

    /**
     * 0时区的Mjd转换为当前时区日期
     *
     * @param zeroMjd 0时区Mjd
     * @return 当前时区日期
     */
    public LocalTime mjdToLocal(MjdTime zeroMjd) {
     
        LocalTime zeroTime = mjdToDate(zeroMjd.mjdDate);
        if (zeroTime != null) {
     
            zeroTime.hour = zeroMjd.mjdTime / 3600;
            zeroTime.minute = (zeroMjd.mjdTime % 3600) / 60;
            zeroTime.second = ((zeroMjd.mjdTime % 3600) % 60);
            return adjustZoneTime(zeroTime); 
        }

        return null;
    }

    /**
     * Mjd转为0时区日期
     */
    public LocalTime mjdToDate(int mjd) {
     
        if (mjd != 0) {
     
            int year = (int) ((((float) mjd) - 15078.2) / 365.25);
            int month = (int) ((((float) mjd) - 14956.1 - (int) (((float) year) * 365.25)) / 30.6001);
            int day = (int) (mjd - 14956 - ((int) (((float) month) * 365.25)) - ((int) (((float) month) * 30.6001)));
            int k = ((month == 14 || month == 15) ? 1 : 0);
            year = (int) (year + k + 1900);
            month = month - 1 - k * 12;
//            int weekday = ((mjd + 2) % 7) + 1;

            LocalTime zeroTime = new LocalTime();
            zeroTime.year = year;
            zeroTime.month = month;
            zeroTime.day = day;
        }

        return null;
    }

    /**
     * 日期转为Mjd
     */
    public int dateToMjd(int year, int month, int day) {
     
        if (year < 1900) return -1;

        int il = (1 == month) || (2 == month) ? 1 : 0;
        year = year - 1900;

        return 14956 + day + (int) (((float) (year - il)) * 365.25) + (int) (((float) (month + 1 + il * 12)) * 30.6001);
    }

    /**
     * 0时区Mjd转换为当前时区Mjd
     *
     * @param zeroMjd 0时区Mjd
     * @return 当前时区的Mjd
     */
    public MjdTime zeroMjdToLocalMjd(MjdTime zeroMjd) {
     
        LocalTime localTime = mjdToLocal(zeroMjd);
        int localMjdDate = dateToMjd(localTime.year, localTime.month, localTime.day);
        int localMjdTime = getCurrTimeZoneMjdTotalSeconds();
        MjdTime localMjd = new MjdTime();
        localMjd.mjdDate = localMjdDate;
        localMjd.mjdTime = localMjdTime;
        return localMjd;
    }

    /**
     * 获取当前时区从00:00:00到现在的总秒数(已处理夏令时)
     */
    private int getCurrTimeZoneMjdTotalSeconds() {
     
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getDefault());
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        return second + minute * 60 + hour * 3600;
    }

    /**
     * 0时区日期转换为当前时区日期
     *
     * @param zeroTime 0时区日期
     * @return 当前时区日期
     */
    public LocalTime adjustZoneTime(LocalTime zeroTime) {
     
        return adjustZoneTime(zeroTime, TimeZone.getTimeZone("GMT"), TimeZone.getDefault());
    }

    /**
     * 旧时区日期转换为新时区日期
     *
     * @param oldTime     旧时区日期
     * @param oldTimeZone 旧时区,默认为底层的0时区
     * @param newTimeZone 新时区,默认为当前时区
     * @return 新时区日期
     */
    public LocalTime adjustZoneTime(LocalTime oldTime, TimeZone oldTimeZone, TimeZone newTimeZone) {
     
        return adjustZoneTime(oldTime.year, oldTime.month, oldTime.day, oldTime.hour, oldTime.minute, oldTime.second, oldTimeZone, newTimeZone);
    }

    public LocalTime adjustZoneTime(int year, int month, int day, int hour, int minute, int second, TimeZone oldTimeZone, TimeZone newTimeZone) {
     
        Date oldDate = getDateTime(year, month - 1, day, hour, minute, second);
        int timeOffset = oldTimeZone.getOffset(oldDate.getTime()) - newTimeZone.getOffset(oldDate.getTime()); // 时区之间的时间差
        Date newDate = new Date(oldDate.getTime() - timeOffset);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(newDate);
        LocalTime localTime = new LocalTime();
        localTime.year = calendar.get(Calendar.YEAR);
        localTime.month = calendar.get(Calendar.MONTH) + 1;
        localTime.day = calendar.get(Calendar.DAY_OF_MONTH);
        localTime.hour = calendar.get(Calendar.HOUR_OF_DAY);
        localTime.minute = calendar.get(Calendar.MINUTE);
        localTime.second = calendar.get(Calendar.SECOND);
        return localTime;
    }
}

public class LocalTime {
     
    public int year;
    public int month;
    public int day;
    public int hour;
    public int minute;
    public int second;
}

// TimeUtils中的儒略历时间MjdTime默认都是0时区,所以也处理了时区日期转换操作,根据需要取舍是否转换时区
public class MjdTime {
     
    public int mjdDate;
    public int mjdTime;
}

public class DateModel {
     
    private final LocalTime start;
    private final LocalTime end;

    public DateModel(LocalTime start, LocalTime end) {
     
        this.start = start;
        this.end = end;
    }

    public int getBetweenSeconds() {
     
        long seconds = getDate(end).getTime() - getDate(start).getTime();
        if (seconds < 0) {
     
            return 0;
        }
        return (int) (seconds / 1000);
    }

    private Date getDate(LocalTime localTime) {
     
        return new Date(localTime.year, localTime.month, localTime.day, localTime.hour, localTime.minute);
    }

    public LocalTime getStart() {
     
        return start;
    }

    public LocalTime getEnd() {
     
        return end;
    }
}

2 NTPTimeUtils

参考:通过NTP获取网络时间
参考:设置系统日期和时间

public class NtpTimeUtils {
     

	// NTP服务器地址,同步获取网络时间(网络获取的时间已处理夏令时)
    private static String[] ntpServerHost = new String[]{
     
            "cn.pool.ntp.org",
            "ntp1.aliyun.com",
            "ntp2.aliyun.com",
            "ntp3.aliyun.com"
    };

	// AndroidManifest.xml需要添加权限
    private static String[] networkPermissions = new String[]{
     
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE
    };

	// 运行在子线程
	@WorkerThread
    private static long getTimeFromNtpServer(String ntpHost) {
     
        SntpClient client = new SntpClient();
        boolean isSuccessful = client.requestTime(ntpHost, 3000);
        if (isSuccessful) {
     
            return client.getNtpTime();
        }
        return -1;
    }

	// 运行在子线程
	@WorkerThread
    public static long getTime() {
     
        for (String host : ntpServerHost) {
     
        	// 获取到当前时区时间的时间戳
        	// int diff = time - System.currentTimeMillis(); 缓存时间差
        	// long currTime = System.currentTimeMillis() + diff;  获取当前时间
            long time = getTimeFromNtpServer(host);  
            if (time != -1) {
     
                return time;
            }
        }
        return -1;
    }

	/**
     * 系统Setting是否打开网络获取时间开关
     */
    public static boolean isAutoTime(Context context) {
     
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
     
            try {
     
                return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AUTO_TIME) > 0;
            } catch (Settings.SettingNotFoundException e) {
     
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

	/**
     * 是否连接网络
     */
    public static boolean isNetworkActive(Context context) {
     
        for (String permission : networkPermissions) {
     
            if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED) {
     
                return false;
            }
        }

        ConnectivityManager cmm = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cmm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }

	/**
     * 系统Setting是否打开时间显示为24小时开关
     */
    public static boolean is24HourFormat(Context context) {
     
        return DateFormat.is24HourFormat(context);
    }
}

public class SntpClient {
     
    private static final String TAG = "SntpClient";

    private static final int REFERENCE_TIME_OFFSET = 16;
    private static final int ORIGINATE_TIME_OFFSET = 24;
    private static final int RECEIVE_TIME_OFFSET = 32;
    private static final int TRANSMIT_TIME_OFFSET = 40;
    private static final int NTP_PACKET_SIZE = 48;

    private static final int NTP_PORT = 123;
    private static final int NTP_MODE_CLIENT = 3;
    private static final int NTP_VERSION = 3;

    // Number of seconds between Jan 1, 1900 and Jan 1, 1970
    // 70 years plus 17 leap days
    private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

    // system time computed from NTP server response
    private long mNtpTime;

    // value of SystemClock.elapsedRealtime() corresponding to mNtpTime
    private long mNtpTimeReference;

    // round trip time in milliseconds
    private long mRoundTripTime;

    /**
     * Sends an SNTP request to the given host and processes the response.
     *
     * @param host host name of the server.
     * @param timeout network timeout in milliseconds.
     * @return true if the transaction was successful.
     */
    public boolean requestTime(String host, int timeout) {
     
        DatagramSocket socket = null;
        try {
     
            socket = new DatagramSocket();
            socket.setSoTimeout(timeout);
            InetAddress address = InetAddress.getByName(host);
            byte[] buffer = new byte[NTP_PACKET_SIZE];
            DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

            // set mode = 3 (client) and version = 3
            // mode is in low 3 bits of first byte
            // version is in bits 3-5 of first byte
            buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

            // get current time and write it to the request packet
            long requestTime = System.currentTimeMillis();
            long requestTicks = SystemClock.elapsedRealtime();
            writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);

            socket.send(request);

            // read the response
            DatagramPacket response = new DatagramPacket(buffer, buffer.length);
            socket.receive(response);
            long responseTicks = SystemClock.elapsedRealtime();
            long responseTime = requestTime + (responseTicks - requestTicks);

            // extract the results
            long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
            long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
            long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

            long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);

            long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;

            // save our results - use the times on this side of the network latency
            // (response rather than request time)
            mNtpTime = responseTime + clockOffset;
            mNtpTimeReference = responseTicks;
            mRoundTripTime = roundTripTime;
        } catch (Exception e) {
     
            Log.d(TAG, "request time failed: " + e);
            return false;
        } finally {
     
            if (socket != null) {
     
                socket.close();
            }
        }

        return true;
    }

    /**
     * Returns the time computed from the NTP transaction.
     *
     * @return time value computed from NTP server response.
     */
    public long getNtpTime() {
     
        return mNtpTime;
    }

    /**
     * Returns the reference clock value (value of SystemClock.elapsedRealtime())
     * corresponding to the NTP time.
     *
     * @return reference clock corresponding to the NTP time.
     */
    public long getNtpTimeReference() {
     
        return mNtpTimeReference;
    }

    /**
     * Returns the round trip time of the NTP transaction
     *
     * @return round trip time in milliseconds.
     */
    public long getRoundTripTime() {
     
        return mRoundTripTime;
    }

    /**
     * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
     */
    private long read32(byte[] buffer, int offset) {
     
        byte b0 = buffer[offset];
        byte b1 = buffer[offset+1];
        byte b2 = buffer[offset+2];
        byte b3 = buffer[offset+3];

        // convert signed bytes to unsigned values
        int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
        int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
        int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
        int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

        return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
    }

    /**
     * Reads the NTP time stamp at the given offset in the buffer and returns
     * it as a system time (milliseconds since January 1, 1970).
     */
    private long readTimeStamp(byte[] buffer, int offset) {
     
        long seconds = read32(buffer, offset);
        long fraction = read32(buffer, offset + 4);
        return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
    }

    /**
     * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
     * at the given offset in the buffer.
     */
    private void writeTimeStamp(byte[] buffer, int offset, long time) {
     
        long seconds = time / 1000L;
        long milliseconds = time - seconds * 1000L;
        seconds += OFFSET_1900_TO_1970;

        // write seconds in big endian format
        buffer[offset++] = (byte)(seconds >> 24);
        buffer[offset++] = (byte)(seconds >> 16);
        buffer[offset++] = (byte)(seconds >> 8);
        buffer[offset++] = (byte)(seconds >> 0);

        long fraction = milliseconds * 0x100000000L / 1000L;
        // write fraction in big endian format
        buffer[offset++] = (byte)(fraction >> 24);
        buffer[offset++] = (byte)(fraction >> 16);
        buffer[offset++] = (byte)(fraction >> 8);
        // low order bits should be random data
        buffer[offset++] = (byte)(Math.random() * 255.0);
    }
}

3 DrawableUtils

public class DrawableUtils {
     
	
	 private DrawableUtils() {
     
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    public static void updateLeftDrawable(Context context, 
    									  @NonNull TextView textView,
     									  @DrawableRes int drawableLeftRes) {
     
        updateDrawable(context, textView, drawableLeftRes, 0, 0, 0);
    }

    public static void updateLeftDrawable(@NonNull TextView textView, @NonNull Drawable leftDrawable) {
     
        textView.setCompoundDrawables(leftDrawable, null, null, null);
    }

    public static void updateTopDrawable(Context context, 
    									 @NonNull TextView textView, 
    									 @DrawableRes int drawableTopRes) {
     
        updateDrawable(context, textView, 0, drawableTopRes, 0, 0);
    }

    public static void updateTopDrawable(@NonNull TextView textView, @NonNull Drawable topDrawable) {
     
        textView.setCompoundDrawables(null, topDrawable, null, null);
    }

    public static void updateRightDrawable(Context context, 
    									   @NonNull TextView textView, 
    									   @DrawableRes int drawableRightRes) {
     
        updateDrawable(context, textView, 0, 0, drawableRightRes, 0);
    }

    public static void updateRightDrawable(@NonNull TextView textView, @NonNull Drawable rightDrawable) {
     
        textView.setCompoundDrawables(null, null, rightDrawable, null);
    }

    public static void updateBottomDrawable(Context context, 
    										@NonNull TextView textView, 
    										@DrawableRes int drawableBottomRes) {
     
        updateDrawable(context, textView, 0, 0, 0, drawableBottomRes);
    }

    public static void updateBottomDrawable(@NonNull TextView textView, @NonNull Drawable bottomDrawable) {
     
        textView.setCompoundDrawables(null, null, null, bottomDrawable);
    }

    public static void updateNonDrawable(Context context, @NonNull TextView textView) {
     
        updateDrawable(context, textView, 0, 0, 0, 0);
    }

    public static void updateDrawable(Context context, 
    								  TextView textView, 
    								  int drawableLeftRes, 
    								  int drawableTopRes, 
    								  int drawableRightRes, 
    								  int drawableBottomRes) {
     
        Drawable drawableLeft = null;
        Drawable drawableRight = null;
        Drawable drawableBottom = null;
        Drawable drawableTop = null;
        if (drawableLeftRes != 0) {
     
            drawableLeft = ContextCompat.getDrawable(context, drawableLeftRes);
            drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
        }
        if (drawableTopRes != 0) {
     
            drawableTop = ContextCompat.getDrawable(context, drawableTopRes);
            drawableTop.setBounds(0, 0, drawableTop.getMinimumWidth(), drawableTop.getMinimumHeight());
        }
        if (drawableRightRes != 0) {
     
            drawableRight = ContextCompat.getDrawable(context, drawableRightRes);
            drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(), drawableRight.getMinimumHeight());
        }
        if (drawableBottomRes != 0) {
     
            drawableBottom = ContextCompat.getDrawable(context, drawableBottomRes);
            drawableBottom.setBounds(0, 0, drawableBottom.getMinimumWidth(), drawableBottom.getMinimumHeight());
        }
        textView.setCompoundDrawables(drawableLeft, drawableTop, drawableRight, drawableBottom);
    }
}

4 DensityUtils

public class DensityUtils {
     

    private DensityUtils() {
     
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    public static int dp2px(Context context, float dpVal) {
     
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    public static int sp2px(Context context, float spVal) {
     
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    public static float px2dp(Context context, float pxVal) {
     
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    public static float px2sp(Context context, float pxVal) {
     
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }
}

5 SDcardUtils

public class SDCardUtils {
     

    private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";

    private SDCardUtils() {
     
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 判断SDCard是否可用
     *
     * @return
     */
    public static boolean isSDCardEnable() {
     
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取SD卡路径
     *
     * @return
     */
    public static String getSDCardPath() {
     
        return Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator;
    }

    /**
     * 获取系统存储路径
     *
     * @return
     */
    public static String getRootDirectoryPath() {
     
        return Environment.getRootDirectory().getAbsolutePath();
    }

    /**
     * 获取SD卡的剩余容量 单位byte
     *
     * @return
     */
    public static long getSDCardAllSize() {
     
        if (isSDCardEnable()) {
     
            StatFs stat = new StatFs(getSDCardPath());
            // 获取空闲的数据块的数量
            long availableBlocks = (long) stat.getAvailableBlocks() - 4;
            // 获取单个数据块的大小(byte)
            long freeBlocks = stat.getAvailableBlocks();
            return freeBlocks * availableBlocks;
        }
        return 0;
    }

    /**
     * 获取指定路径所在空间的剩余可用容量字节数,单位byte
     *
     * @param filePath
     * @return
     */
    public static long getFreeBytes(String filePath) {
     
        // 如果是sd卡的下的路径,则获取sd卡可用容量
        if (filePath.startsWith(getSDCardPath())) {
     
            filePath = getSDCardPath();
        } else {
     // 如果是内部存储的路径,则获取内存存储的可用容量
            filePath = Environment.getDataDirectory().getAbsolutePath();
        }
        StatFs stat = new StatFs(filePath);
        long availableBlocks = (long) stat.getAvailableBlocks() - 4;
        return stat.getBlockSize() * availableBlocks;
    }

    /**
     * 获取缓存目录
     *
     * @param context
     * @param dirName
     * @return
     */
    public static File getCacheDir(Context context, String dirName) {
     
        return getCacheDir(context, true, dirName);
    }

    private static File getCacheDir(Context context, boolean preferExternal, String dir) {
     
        File appCacheDir = null;
        if (preferExternal
                && MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                && hasExternalStoragePermission(context)) {
     
            appCacheDir = getExternalCacheDir(context, dir);
        }
        if (appCacheDir == null) {
     
            appCacheDir = context.getCacheDir();
        }
        if (appCacheDir == null) {
     
            String cacheDirPath = "/data/data/" + context.getPackageName()
                    + "/" + dir + "/";

            appCacheDir = new File(cacheDirPath);
        }
        return appCacheDir;
    }

    private static File getExternalCacheDir(Context context, String dir) {
     
        File dataDir = new File(new File(
                Environment.getExternalStorageDirectory(), "Android"), "data");
        File appCacheDir = new File(
                new File(dataDir, context.getPackageName()), dir);
        if (!appCacheDir.exists()) {
     
            if (!appCacheDir.mkdirs()) {
     
                return null;
            }
            try {
     
                new File(appCacheDir, ".nomedia").createNewFile();
            } catch (IOException e) {
     
                e.printStackTrace();
            }
        }
        return appCacheDir;
    }

    private static boolean hasExternalStoragePermission(Context context) {
     
        int perm = context
                .checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
        return perm == PackageManager.PERMISSION_GRANTED;
    }
}

6 JSONUtils

public class JSONUtils {
     

    public static String getString(JSONObject response, String key) {
     
        String value = response.optString(key, "");
        return value.equals("null") ? "" : value;
    }

    public static boolean isEmptyArray(JSONArray jsonArray) {
     
        return (jsonArray == null || jsonArray.length() == 0) ? true : false;
    }

    public static String[] decoding(JSONArray jsonArray) {
     
        if (isEmptyArray(jsonArray)) {
     
            return null;
        }

        int length = jsonArray.length();
        String[] values = new String[length];
        for (int i = 0; i < length; i++) {
     
            values[i] = jsonArray.optString(i);
        }
        return values;
    }

    public static JSONArray encoding(String[] values) {
     
        if (values == null) {
     
            return null;
        }

        int length = values.length;
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < length; i++) {
     
            try {
     
                jsonArray.put(i, values[i]);
            } catch (JSONException e) {
     
                e.printStackTrace();
            }
        }
        return jsonArray;
    }

    public static ArrayList<String> decodingList(JSONArray jsonArray) {
     
        if (isEmptyArray(jsonArray)) {
     
            return null;
        }

        ArrayList<String> list = new ArrayList<String>();

        int length = jsonArray.length();
        for (int i = 0; i < length; i++) {
     
            String tag = jsonArray.optString(i);
            if (!TextUtils.isEmpty(tag)) {
     
                list.add(tag);
            }
        }
        return list;
    }

    public static JSONArray encodingList(List<String> values) {
     
        if (values == null) {
     
            return null;
        }

        int size = values.size();
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < size; i++) {
     
            try {
     
                jsonArray.put(i, values.get(i));
            } catch (JSONException e) {
     
                e.printStackTrace();
            }
        }
        return jsonArray;
    }

    public static JSONArray encoding(List<Long> values) {
     
        if (values == null) {
     
            return null;
        }

        int size = values.size();
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < size; i++) {
     
            try {
     
                jsonArray.put(i, values.get(i));
            } catch (JSONException e) {
     
                e.printStackTrace();
            }
        }
        return jsonArray;
    }

    public static JSONObject getJSONObject(Context context, String assetsFile)
            throws JSONException {
     
        String text = readAssetRes(context, assetsFile);
        return new JSONObject(text);
    }

    public static String readAssetRes(Context context, String filepath) {
     
        InputStream is = null;
        try {
     
            is = context.getAssets().open(filepath);
            int size = is.available();

            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();

            String text = new String(buffer, "UTF-8");
            return text;
        } catch (IOException e) {
     
            e.printStackTrace();

            return "";
        } finally {
     
            closeSilently(is);
        }
    }

    private static void closeSilently(Closeable c) {
     
        if (c == null) {
     
            return;
        }
        try {
     
            c.close();
        } catch (Throwable t) {
     
        }
    }
}

7 KeyboardUtils

/**
 * 软键盘相关辅助类
 */
public class KeyBoardUtils {
     

    private KeyBoardUtils() {
     
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 隐藏输入盘
     *
     * @param activity
     */
    public static void collapseSoftInput(Activity activity) {
     
        InputMethodManager inputMethodManager = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive()) {
     
            if (activity.getCurrentFocus() != null) {
     
                inputMethodManager.hideSoftInputFromWindow(activity
                                .getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 显示输入盘
     *
     * @param context
     * @param inputText
     */
    public static void showSoftInput(Context context, EditText inputText) {
     
        if (inputText == null) {
     
            return;
        }

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(inputText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 隐藏输入盘
     *
     * @param context
     * @param inputText
     */
    public static void hideSoftInput(Context context, EditText inputText) {
     
        if (inputText == null) {
     
            return;
        }

        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(inputText.getWindowToken(), 0);
    }

    /**
     * 设置EditText的光标
     *
     * @param editText
     */
    public static void setFocus(EditText editText) {
     
        editText.requestFocus();

        CharSequence text = editText.getText();
        if (text instanceof Spannable) {
     
            Selection.setSelection((Spannable) text, text.length());
        }
    }

    /**
     * 设置EditText的光标并选择文字
     *
     * @param editText
     */
    public static void setFocusAndSelection(EditText editText) {
     
        editText.requestFocus();

        CharSequence text = editText.getText();
        if (text instanceof Spannable) {
     
            Selection.selectAll((Spannable) text);
        }
    }
}

8 ScreenUtils

/**
 * 获得屏幕相关的辅助类
 */
public class ScreenUtils {
     

    private ScreenUtils() {
     
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    public static int getDrawerWidth(Resources res) {
     
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
     

            if (res.getConfiguration().smallestScreenWidthDp >= 600 || res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
     
                // device is a tablet
                return (int) (320 * res.getDisplayMetrics().density);
            } else {
     
                return (int) (res.getDisplayMetrics().widthPixels - (70 * res.getDisplayMetrics().density));
            }
        } else {
      // for devices without smallestScreenWidthDp reference calculate if device screen is over 600 dp
            if ((res.getDisplayMetrics().widthPixels / res.getDisplayMetrics().density) >= 600 || res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
                return (int) (320 * res.getDisplayMetrics().density);
            else
                return (int) (res.getDisplayMetrics().widthPixels - (70 * res.getDisplayMetrics().density));
        }
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
     
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
     
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 设置Activity状态栏颜色
     *
     * @param activity
     * @param colorId
     */
    public static void setStatusBarColor(Activity activity, int colorId) {
     
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
     
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(ContextCompat.getColor(activity, colorId));
        }
    }

    /**
     * 获取ActionBar高度
     *
     * @param context
     * @return
     */
    @TargetApi(14)
    public static int getActionBarHeight(Context context) {
     
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
     
            TypedValue tv = new TypedValue();
            context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
            result = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
        }
        return result;
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
     
        return getInternalDimensionSize(context.getResources(), "status_bar_height");
    }

    private static int getInternalDimensionSize(Resources res, String key) {
     
        int result = 0;
        int resourceId = res.getIdentifier(key, "dimen", "android");
        if (resourceId > 0) {
     
            result = res.getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 获取当前屏幕截图,包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap snapShotWithStatusBar(Activity activity) {
     
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bitmap = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return bitmap;
    }

    /**
     * 获取当前屏幕截图,不包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap snapShotWithoutStatusBar(Activity activity) {
     
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bitmap = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return bitmap;
    }
}

你可能感兴趣的:(Android,Utils)