Android开发中一些通用工具代码

82 阅读1分钟

在android中有一些通用的代码转换可以方便地应用到编码中提升开发效率。

public class SomeUtils {
    private static final float epsilon = 0.00001f;
    public static boolean checkFloatIsEqual(float f1, float f2) {
        return Math.abs(f1 - f2) <= epsilon;
    }
    public static boolean checkDoubleIsEqual(double f1, double f2) {
        return Math.abs(f1 - f2) <= epsilon;
    }

    //℉ to ℃
    public static double fahrenheitToCelsius(double fahrenheit) {
        return (5.0 / 9.0) * (fahrenheit - 32);
    }

    //℃ to ℉
    public static double celsiusToFahrenheit(double celsius) {
        return celsius * (9.0 / 5.0) + 32;
    }

	public static String findOne(String regex, String content) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(content);
		boolean haveResult = matcher.find();
		if (!haveResult) {
			return "";
		}
		return matcher.group(1);
	}
	
	public static List<String> findAll(String regex, String content) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(content);
		List<String> r = new ArrayList<String>();
		while (matcher.find()) {
			r.add(matcher.group(1));
		}
		return Collections.unmodifiableList(r);
	}
	
	public static int formatTimestampToSeconds(String durationAsString) {
		if(!durationAsString.isEmpty()) {
			String[] parts = durationAsString.split(":");
			return Integer.parseInt(parts[0]) * 3600 + Integer.parseInt(parts[1]) * 60 + Integer.parseInt(parts[2]);
		}else {
			return 0;
		}
	}
	
	@SuppressLint("DefaultLocale")
	public static String secondsToFormatTimestamp(int seconds) {
		int hours =  seconds / 3600;
		int minutes = (seconds % 3600) / 60;
		int secs = seconds % 60;
		return String.format("%02d:%02d:%02d", hours,minutes,secs);
	}
	
	public static boolean checkNetworkIsConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }
	
	public static String getLocalIpv4Address() {
        try {
            for (Enumeration<NetworkInterface> enume = NetworkInterface.getNetworkInterfaces(); enume.hasMoreElements();) {
                NetworkInterface nwi = enume.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = nwi.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(TAG, "getLocalIpv4Address...socketException:" + ex);
        }
        return null;
    }
	
	public static boolean isIPv4Address(String input) {
        String ipv4Pattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
        return input.matches(ipv4Pattern);
    }
	
	float density = Resources.getSystem().getDisplayMetrics().density;
	
	public static int dp2px(float dpValue) {
        return (int) (0.5f + dpValue * Resources.getSystem().getDisplayMetrics().density);
    }

    public static float px2dp(int pxValue) {
        return (pxValue / Resources.getSystem().getDisplayMetrics().density);
    }

    public static int sp2px(Context context, float spValue) {
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        return Math.round((float)spValue * scaledDensity);
    }

}