当前位置:网站首页>Framework tool class obtained by chance for self use
Framework tool class obtained by chance for self use
2022-06-24 09:09:00 【Simon66991】
/* * framework Tool class */
public class Utils {
/** tag */
private static final String TAG = "Utils";
/** * Install an application * * @param context * @param apkFile * @return */
public static boolean installApp(Context context, File apkFile) {
try {
context.startActivity(getInstallAppIntent(apkFile));
return true;
} catch (Exception e) {
Log.w(TAG, e);
}
return false;
}
/** * Get the Intent * * @param apkFile * @return */
public static Intent getInstallAppIntent(File apkFile) {
if (apkFile == null || !apkFile.exists()) {
return null;
}
Utils.chmod("777", apkFile.getAbsolutePath());
Uri uri = Uri.fromFile(apkFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
return intent;
}
/** * Check the... Of a package name App Has it been installed? * * @param context * @param packageName * @return */
public static boolean hasAppInstalled(Context context, String packageName) {
try {
PackageManager packageManager = context.getPackageManager();
packageManager.getPackageInfo(packageName,
PackageManager.GET_ACTIVITIES);
} catch (Exception e) {
return false;
}
return true;
}
/** * Start the third party according to the package name App * * @param context * @param packageName * @return */
public static boolean launchAppByPackageName(Context context,
String packageName) {
if (TextUtils.isEmpty(packageName)) {
return false;
}
try {
Intent intent = context.getPackageManager()
.getLaunchIntentForPackage(packageName);
if (intent != null) {
context.startActivity(intent);
return true;
}
} catch (Exception e) {
Log.w(TAG, e);
}
return false;
}
public static String getAssetsFie(Context context, String name)
throws IOException {
InputStream is = context.getAssets().open(name);
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String content = new String(buffer, "UTF-8");
return content;
}
/** * Is it wifi Connection status * * @param context * @return */
public static boolean isWifiConnect(Context context) {
ConnectivityManager connectivitymanager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
if (networkinfo != null) {
if ("wifi".equals(networkinfo.getTypeName().toLowerCase(Locale.US))) {
return true;
}
}
return false;
}
/** * Is there a network connection * * @param context * @return */
public static boolean isNetConnect(Context context) {
ConnectivityManager connectivitymanager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
return networkinfo != null;
}
/** * Access permissions * * @param permission jurisdiction * @param path File path */
public static void chmod(String permission, String path) {
try {
String command = "chmod " + permission + " " + path;
Runtime runtime = Runtime.getRuntime();
runtime.exec(command);
} catch (IOException e) {
Log.e(TAG, "chmod", e);
}
}
/** * Is... Installed sdcard * * @return true Express ,false It means that there is no */
public static boolean haveSDCard() {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
}
/** * Get the internal free space of the system * * @return available size */
public static long getSystemAvailableSize() {
File root = Environment.getRootDirectory();
StatFs sf = new StatFs(root.getPath());
long blockSize = sf.getBlockSize();
long availCount = sf.getAvailableBlocks();
return availCount * blockSize;
}
/** * obtain sd Card free space size * * @return available size */
public static long getSDCardAvailableSize() {
long available = 0;
if (haveSDCard()) {
File path = Environment.getExternalStorageDirectory();
StatFs statfs = new StatFs(path.getPath());
long blocSize = statfs.getBlockSize();
long availaBlock = statfs.getAvailableBlocks();
available = availaBlock * blocSize;
} else {
available = -1;
}
return available;
}
/** * obtain application Hierarchical metadata * * @param context * @param key * @return */
public static String getApplicationMetaData(Context context, String key) {
try {
Object metaObj = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA).metaData
.get(key);
if (metaObj instanceof String) {
return metaObj.toString();
} else if (metaObj instanceof Integer) {
return ((Integer) metaObj).intValue() + "";
} else if (metaObj instanceof Boolean) {
return ((Boolean) metaObj).booleanValue() + "";
}
} catch (NameNotFoundException e) {
Log.w(TAG, e);
}
return "";
}
/** * Get version * * @param context * @return */
public static String getVersionName(Context context) {
try {
return context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
Log.w(TAG, e);
}
return null;
}
/** * Get version * * @param context * @return */
public static int getVersionCode(Context context) {
try {
return context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
Log.w(TAG, e);
}
return 0;
}
/** * take px Value to dip or dp value , Make sure the size doesn't change * * @param pxValue * @param scale (DisplayMetrics Class density) * @return */
public static int px2dip(Context context, float pxValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/** * take dip or dp Value to px value , Make sure the size doesn't change * * @param dipValue * @param scale (DisplayMetrics Class density) * @return */
public static int dip2px(Context context, float dipValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
/** * take px Value to sp value , Keep the text size constant * * @param pxValue * @param fontScale (DisplayMetrics Class scaledDensity) * @return */
public static int px2sp(Context context, float pxValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/** * take sp Value to px value , Keep the text size constant * * @param spValue * @param fontScale (DisplayMetrics Class scaledDensity) * @return */
public static int sp2px(Context context, float spValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
/** * Hidden keyboard * * @param activity activity */
public static void hideInputMethod(Activity activity) {
hideInputMethod(activity, activity.getCurrentFocus());
}
/** * Hidden keyboard * * @param context context * @param view The currently focused view */
public static void hideInputMethod(Context context, View view) {
if (context == null || view == null) {
return;
}
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/** * Display the input keyboard * * @param context context * @param view The currently focused view, which would like to receive soft keyboard input */
public static void showInputMethod(Context context, View view) {
if (context == null || view == null) {
return;
}
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(view, 0);
}
}
/** * Bitmap The zoom , Pay attention to the source Bitmap It will be recycled after zooming * * @param origin * @param width * @param height * @return */
public static Bitmap getScaleBitmap(Bitmap origin, int width, int height) {
float originWidth = origin.getWidth();
float originHeight = origin.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width) / originWidth;
float scaleHeight = ((float) height) / originHeight;
matrix.postScale(scaleWidth, scaleHeight);
Bitmap scale = Bitmap.createBitmap(origin, 0, 0, (int) originWidth,
(int) originHeight, matrix, true);
origin.recycle();
return scale;
}
/** * A text prompt for calculating the interval between a certain time and the present time */
public static String countTimeIntervalText(long time) {
long dTime = System.currentTimeMillis() - time;
// 15 minute
if (dTime < 15 * 60 * 1000) {
return " just ";
} else if (dTime < 60 * 60 * 1000) {
// An hour
return " An hour ";
} else if (dTime < 24 * 60 * 60 * 1000) {
return (int) (dTime / (60 * 60 * 1000)) + " Hours ";
} else {
return DateFormat.format("MM-dd kk:mm", System.currentTimeMillis())
.toString();
}
}
/** * Get notification bar height * * @param context * @return */
public static int getStatusBarHeight(Context context) {
int x = 0, statusBarHeight = 0;
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
}
/** * Get title bar height * * @param context * @return */
public static int getTitleBarHeight(Activity context) {
int contentTop = context.getWindow()
.findViewById(Window.ID_ANDROID_CONTENT).getTop();
return contentTop - getStatusBarHeight(context);
}
/** * Get screen width ,px * * @param context * @return */
public static float getScreenWidth(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return dm.widthPixels;
}
/** * Get screen height ,px * * @param context * @return */
public static float getScreenHeight(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return dm.heightPixels;
}
/** * Gets the screen pixel density * * @param context * @return */
public static float getDensity(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return dm.density;
}
/** * obtain scaledDensity * * @param context * @return */
public static float getScaledDensity(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return dm.scaledDensity;
}
/** * Get the current hour and minute /24 Hours * * @return */
public static String getTime24Hours() {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.CHINA);
Date curDate = new Date(System.currentTimeMillis());// Get the current time
return formatter.format(curDate);
}
/** * Get the battery power ,0~1 * * @param context * @return */
@SuppressWarnings("unused")
public static float getBattery(Context context) {
Intent batteryInfoIntent = context.getApplicationContext()
.registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int status = batteryInfoIntent.getIntExtra("status", 0);
int health = batteryInfoIntent.getIntExtra("health", 1);
boolean present = batteryInfoIntent.getBooleanExtra("present", false);
int level = batteryInfoIntent.getIntExtra("level", 0);
int scale = batteryInfoIntent.getIntExtra("scale", 0);
int plugged = batteryInfoIntent.getIntExtra("plugged", 0);
int voltage = batteryInfoIntent.getIntExtra("voltage", 0);
int temperature = batteryInfoIntent.getIntExtra("temperature", 0); // The unit of temperature is 10`
String technology = batteryInfoIntent.getStringExtra("technology");
return ((float) level) / scale;
}
/** * Get the phone name * * @return */
public static String getMobileName() {
return android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL;
}
/** * Is... Installed sdcard * * @return true Express ,false It means that there is no */
public static boolean hasSDCard() {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
}
/** * obtain sd Card free space * * @return available size */
public static long getAvailableExternalSize() {
long available = 0;
if (hasSDCard()) {
File path = Environment.getExternalStorageDirectory();
StatFs statfs = new StatFs(path.getPath());
long blocSize = statfs.getBlockSize();
long availaBlock = statfs.getAvailableBlocks();
available = availaBlock * blocSize;
} else {
available = -1;
}
return available;
}
/** * Get memory free space * * @return available size */
public static long getAvailableInternalSize() {
long available = 0;
if (hasSDCard()) {
File path = Environment.getRootDirectory();
StatFs statfs = new StatFs(path.getPath());
long blocSize = statfs.getBlockSize();
long availaBlock = statfs.getAvailableBlocks();
available = availaBlock * blocSize;
} else {
available = -1;
}
return available;
}
/* * Version control section */
/** * Whether it is 2.2 Version and above * * @return */
public static boolean hasFroyo() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}
/** * Whether it is 2.3 Version and above * * @return */
public static boolean hasGingerbread() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
/** * Whether it is ?3.0 Version and above * * @return */
public static boolean hasHoneycomb() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
/** * Whether it is 3.1 Version and above * * @return */
public static boolean hasHoneycombMR1() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
}
/** * Whether it is 4.1 Version and above * * @return */
public static boolean hasJellyBean() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}
public static String getPhoneType() {
String phoneType = android.os.Build.MODEL;
Log.d(TAG, "phoneType is : " + phoneType);
return phoneType;
}
/** * Get system version * * @return */
public static String getOsVersion() {
String osversion;
int osversion_int = getOsVersionInt();
osversion = osversion_int + "";
return osversion;
}
/** * Get system version * * @return */
public static int getOsVersionInt() {
return Build.VERSION.SDK_INT;
}
/** * obtain ip Address * * @return */
public static String getHostIp() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& InetAddressUtils.isIPv4Address(inetAddress
.getHostAddress())) {
if (!inetAddress.getHostAddress().toString()
.equals("null")
&& inetAddress.getHostAddress() != null) {
return inetAddress.getHostAddress().toString()
.trim();
}
}
}
}
} catch (Exception ex) {
Log.e("WifiPreference IpAddress", ex.toString());
}
return "";
}
/** * Get cell phone number , It is almost impossible to obtain * * @param context * @return */
public static String getPhoneNum(Context context) {
TelephonyManager mTelephonyMgr = (TelephonyManager) context
.getApplicationContext().getSystemService(
Context.TELEPHONY_SERVICE);
String phoneNum = mTelephonyMgr.getLine1Number();
return TextUtils.isEmpty(phoneNum) ? "" : phoneNum;
}
/** * obtain imei * * @param context * @return */
public static String getPhoneImei(Context context) {
TelephonyManager mTelephonyMgr = (TelephonyManager) context
.getApplicationContext().getSystemService(
Context.TELEPHONY_SERVICE);
String phoneImei = mTelephonyMgr.getDeviceId();
Log.d(TAG, "IMEI is : " + phoneImei);
return TextUtils.isEmpty(phoneImei) ? "" : phoneImei;
}
/** * obtain imsi * * @param context * @return */
public static String getPhoneImsi(Context context) {
TelephonyManager mTelephonyMgr = (TelephonyManager) context
.getApplicationContext().getSystemService(
Context.TELEPHONY_SERVICE);
String phoneImsi = mTelephonyMgr.getSubscriberId();
Log.d(TAG, "IMSI is : " + phoneImsi);
return TextUtils.isEmpty(phoneImsi) ? "" : phoneImsi;
}
/** * obtain mac Address * * @return */
public static String getLocalMacAddress() {
String Mac = null;
try {
String path = "sys/class/net/wlan0/address";
if ((new File(path)).exists()) {
FileInputStream fis = new FileInputStream(path);
byte[] buffer = new byte[8192];
int byteCount = fis.read(buffer);
if (byteCount > 0) {
Mac = new String(buffer, 0, byteCount, "utf-8");
}
fis.close();
}
if (Mac == null || Mac.length() == 0) {
path = "sys/class/net/eth0/address";
FileInputStream fis = new FileInputStream(path);
byte[] buffer_name = new byte[8192];
int byteCount_name = fis.read(buffer_name);
if (byteCount_name > 0) {
Mac = new String(buffer_name, 0, byteCount_name, "utf-8");
}
fis.close();
}
if (Mac == null || Mac.length() == 0) {
return "";
} else if (Mac.endsWith("\n")) {
Mac = Mac.substring(0, Mac.length() - 1);
}
} catch (Exception io) {
Log.w(TAG, "Exception", io);
}
return TextUtils.isEmpty(Mac) ? "" : Mac;
}
/** * Get the number of duplicate field names * * @param s * @return */
public static int getRepeatTimes(String s) {
if (TextUtils.isEmpty(s)) {
return 0;
}
int mCount = 0;
char[] mChars = s.toCharArray();
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < mChars.length; i++) {
char key = mChars[i];
Integer value = map.get(key);
int count = value == null ? 0 : value.intValue();
map.put(key, ++count);
if (mCount < count) {
mCount = count;
}
}
return mCount;
}
/** * Determine whether it is a mobile phone number * * @param num * @return */
public static boolean isPhoneNum(String num) {
// Make sure every digit is a number
return !TextUtils.isEmpty(num) && num.matches("1[0-9]{10}")
&& !isRepeatedStr(num) && !isContinuousNum(num);
}
/** * Determine whether 400 Service code * * @param num * @return */
public static boolean is400or800(String num) {
return !TextUtils.isEmpty(num)
&& (num.startsWith("400") || num.startsWith("800"))
&& num.length() == 10;
}
/** * Determine whether the area number * * @param num * @return */
public static boolean isAdCode(String num) {
return !TextUtils.isEmpty(num) && num.matches("[0]{1}[0-9]{2,3}")
&& !isRepeatedStr(num);
}
/** * Determine whether the landline number * * @param num * @return */
public static boolean isPhoneHome(String num) {
return !TextUtils.isEmpty(num) && num.matches("[0-9]{7,8}")
&& !isRepeatedStr(num);
}
/** * Determine whether it is a duplicate string * * @param str String to check */
public static boolean isRepeatedStr(String str) {
if (TextUtils.isEmpty(str)) {
return false;
}
int len = str.length();
if (len <= 1) {
return false;
} else {
char firstChar = str.charAt(0);// First character
for (int i = 1; i < len; i++) {
char nextChar = str.charAt(i);// The first i Characters
if (firstChar != nextChar) {
return false;
}
}
return true;
}
}
/** * Determine whether the string is a continuous number */
public static boolean isContinuousNum(String str) {
if (TextUtils.isEmpty(str))
return false;
if (!isNumbericString(str))
return true;
int len = str.length();
for (int i = 0; i < len - 1; i++) {
char curChar = str.charAt(i);
char verifyChar = (char) (curChar + 1);
if (curChar == '9')
verifyChar = '0';
char nextChar = str.charAt(i + 1);
if (nextChar != verifyChar) {
return false;
}
}
return true;
}
/** * Determine whether the string is a continuous letter */
public static boolean isContinuousWord(String str) {
if (TextUtils.isEmpty(str))
return false;
if (!isAlphaBetaString(str))
return true;
int len = str.length();
String local = str.toLowerCase();
for (int i = 0; i < len - 1; i++) {
char curChar = local.charAt(i);
char verifyChar = (char) (curChar + 1);
if (curChar == 'z')
verifyChar = 'a';
char nextChar = local.charAt(i + 1);
if (nextChar != verifyChar) {
return false;
}
}
return true;
}
/** * Judge whether it is a pure number * * @param str String to check */
public static boolean isNumbericString(String str) {
if (TextUtils.isEmpty(str)) {
return false;
}
Pattern p = Pattern.compile("^[0-9]+$");// The beginning to the end must be all numbers
Matcher m = p.matcher(str);
return m.find();
}
/** * Determine whether it is a pure letter * * @param str * @return */
public static boolean isAlphaBetaString(String str) {
if (TextUtils.isEmpty(str)) {
return false;
}
Pattern p = Pattern.compile("^[a-zA-Z]+$");// It must be all letters or numbers from the beginning to the end
Matcher m = p.matcher(str);
return m.find();
}
/** * Judge whether it is pure letters or numbers * * @param str * @return */
public static boolean isAlphaBetaNumbericString(String str) {
if (TextUtils.isEmpty(str)) {
return false;
}
Pattern p = Pattern.compile("^[a-zA-Z0-9]+$");// It must be all letters or numbers from the beginning to the end
Matcher m = p.matcher(str);
return m.find();
}
private static String regEx = "[\u4e00-\u9fa5]";
private static Pattern pat = Pattern.compile(regEx);
/** * Judge whether it contains Chinese * * @param str * @return */
public static boolean isContainsChinese(String str) {
return pat.matcher(str).find();
}
public static boolean patternMatcher(String pattern, String input) {
if (TextUtils.isEmpty(pattern) || TextUtils.isEmpty(input)) {
return false;
}
Pattern pat = Pattern.compile(pattern);
Matcher matcher = pat.matcher(input);
return matcher.find();
}
/****************************************************************************/
// import PPutils
private static int id = 1;
public static int getNextId() {
return id++;
}
/** * Flow the input into a byte array * * @param inStream * @return * @throws Exception */
public static byte[] read2Byte(InputStream inStream) throws Exception {
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
/** * Determine whether the expiration time rules of month and year are met * * @param date * @return */
public static boolean isMMYY(String date) {
try {
if (!TextUtils.isEmpty(date) && date.length() == 4) {
int mm = Integer.parseInt(date.substring(0, 2));
return mm > 0 && mm < 13;
}
} catch (Exception e) {
Log.e(TAG, "Exception", e);
}
return false;
}
/** * 20120506 There are eight , The top four - year , Two in the middle - month , The last two - Japan * * @param date * @return */
public static boolean isRealDate(String date, int yearlen) {
// if(yearlen != 2 && yearlen != 4)
// return false;
int len = 4 + yearlen;
if (date == null || date.length() != len)
return false;
if (!date.matches("[0-9]+"))
return false;
int year = Integer.parseInt(date.substring(0, yearlen));
int month = Integer.parseInt(date.substring(yearlen, yearlen + 2));
int day = Integer.parseInt(date.substring(yearlen + 2, yearlen + 4));
if (year <= 0)
return false;
if (month <= 0 || month > 12)
return false;
if (day <= 0 || day > 31)
return false;
switch (month) {
case 4:
case 6:
case 9:
case 11:
return day > 30 ? false : true;
case 2:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
return day > 29 ? false : true;
return day > 28 ? false : true;
default:
return true;
}
}
/** * Determine whether the string is a continuous character abcdef 456789 */
public static boolean isContinuousStr(String str) {
if (TextUtils.isEmpty(str))
return false;
int len = str.length();
for (int i = 0; i < len; i++) {
char curChar = str.charAt(i);
char nextChar = (char) (curChar + 1);
if (i + 1 < len) {
nextChar = str.charAt(i + 1);
}
if (nextChar != (curChar + 1)) {
return false;
}
}
return true;
}
public static final String REGULAR_NUMBER = "(-?[0-9]+)(,[0-9]+)*(\\.[0-9]+)?";
/** * Color the numbers in the string * * @param str Strings to be processed * @param color Color to be dyed * @return */
public static SpannableString setDigitalColor(String str, int color) {
if (str == null)
return null;
SpannableString span = new SpannableString(str);
Pattern p = Pattern.compile(REGULAR_NUMBER);
Matcher m = p.matcher(str);
while (m.find()) {
int start = m.start();
int end = start + m.group().length();
span.setSpan(new ForegroundColorSpan(color), start, end,
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
return span;
}
public static boolean isChineseByREG(String str) {
if (str == null) {
return false;
}
Pattern pattern = Pattern.compile("[\\u4E00-\\u9FBF]+");
return pattern.matcher(str.trim()).find();
}
public static String getFixedNumber(String str, int length) {
if (str == null || length <= 0 || str.length() < length) {
return null;
}
Log.d(TAG, "getFixedNumber, str is : " + str);
Pattern p = Pattern.compile("\\d{" + length + "}");
Matcher m = p.matcher(str);
String result = null;
if (m.find()) {
int start = m.start();
int end = start + m.group().length();
result = str.substring(start, end);
}
return result;
}
public static int getLengthWithoutSpace(CharSequence s) {
int len = s.length();
int rlen = 0;
for (int i = 0; i < len; i++) {
if (s.charAt(i) != ' ')
rlen++;
}
return rlen;
}
/** * Gets the width of the control , If the height obtained is 0, Then recalculate the dimension and return to the height * * @param view * @return */
public static int getViewMeasuredWidth(TextView view) {
// int height = view.getMeasuredHeight();
// if(0 < height){
// return height;
// }
calcViewMeasure(view);
return view.getMeasuredWidth();
}
/** * Gets the height of the control , If the height obtained is 0, Then recalculate the dimension and return to the height * * @param view * @return */
public static int getViewMeasuredHeight(TextView view) {
// int height = view.getMeasuredHeight();
// if(0 < height){
// return height;
// }
calcViewMeasure(view);
return view.getMeasuredHeight();
}
/** * Measure the size of the control * * @param view */
public static void calcViewMeasure(View view) {
// int width =
// View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
// int height =
// View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
// view.measure(width,height);
int width = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
int expandSpec = View.MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
view.measure(width, expandSpec);
}
public static String getDisDsrc(float dis) {
if (dis <= 0) {
return "";
}
String disStr = null;
if (dis > 1000) {
disStr = (float) Math.round(dis / 1000 * 10) / 10 + "km";
} else {
disStr = dis + "m";
}
return disStr;
}
public static boolean isValidDate(String str) {
boolean convertSuccess = true;
// The specified date format is a four digit year / Two months / Two dates , Be careful yyyy/MM/dd Case sensitive ;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
try {
// Set up lenient by false.
// otherwise SimpleDateFormat Will be more relaxed to verify the date , such as 2007/02/29 Will be accepted , And converted to 2007/03/01
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
// If throw java.text.ParseException or NullPointerException, It means that the format is not correct
convertSuccess = false;
}
return convertSuccess;
}
}
边栏推荐
- [e325: attention] VIM editing error
- Data middle office: middle office architecture and overview
- Prompt code when MySQL inserts Chinese data due to character set problems: 1366
- MBA-day25 最值问题-应用题
- 12、 Demonstration of all function realization effects
- 什么是图神经网络?图神经网络有什么用?
- The printed object is [object object]. Solution
- pm2 部署 nuxt3.js 项目
- 数云发布2022美妆行业全域消费者数字化经营白皮书:全域增长破解营销难题
- Linux MySQL installation
猜你喜欢

关于 GIN 的路由树
![[noi Simulation Competition] send (tree DP)](/img/5b/3beb9f5fdad00b6d5dc789e88c6e98.png)
[noi Simulation Competition] send (tree DP)
![[quantitative investment] discrete Fourier transform to calculate array period](/img/0d/aac02463ff403fb1ff871af5ff91fa.png)
[quantitative investment] discrete Fourier transform to calculate array period

What is graph neural network? Figure what is the use of neural networks?

嵌入式 | 硬件转软件的几条建议

cookie加密 4 rpc方法确定cookie加密

Data middle office: detailed explanation of technical architecture of data middle office

【Redis實現秒殺業務①】秒殺流程概述|基本業務實現
![The printed object is [object object]. Solution](/img/fc/9199e26b827a1c6304fcd250f2301e.png)
The printed object is [object object]. Solution

uniapp 开发多端项目如何配置环境变量以及区分环境打包
随机推荐
Prompt code when MySQL inserts Chinese data due to character set problems: 1366
China chip Unicorn Corporation
玄铁E906移植----番外0:玄铁C906仿真环境搭建
Lu Qi: I am most optimistic about these four major technology trends
当程序员被问会不会修电脑时… | 每日趣闻
"Unusual proxy initial value setting is not supported", causes and Solutions
Opencv maximum filtering (not limited to images)
【LeetCode】541. 反转字符串 II
Applet cloud data, data request a method to collect data
Huawei Router: IPSec Technology
Data midrange: analysis of full stack technical architecture of data midrange, with industry solutions
12、 Demonstration of all function realization effects
What is graph neural network? Figure what is the use of neural networks?
leetcode——错误的集合
Double pointer analog
tcpdump抓包实现过程
关于 GIN 的路由树
MySQL | view notes on Master Kong MySQL from introduction to advanced
What is SRE? A detailed explanation of SRE operation and maintenance system
荐书丨《好奇心的秘密》:一个针尖上可以站多少跳舞的小天使?