五、PhoneUtils
public final class PhoneUtils {
private PhoneUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Return whether the device is phone.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isPhone() {
TelephonyManager tm = getTelephonyManager();
return tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
}
/**
* Return the unique device id.
* <p>Must hold {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
*
* @return the unique device id
*/
@SuppressLint("MissingPermission")
@RequiresPermission(READ_PHONE_STATE)
public static String getDeviceId() {
TelephonyManager tm = getTelephonyManager();
String deviceId = tm.getDeviceId();
if (!TextUtils.isEmpty(deviceId)) return deviceId;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String imei = tm.getImei();
if (!TextUtils.isEmpty(imei)) return imei;
String meid = tm.getMeid();
return TextUtils.isEmpty(meid) ? "" : meid;
}
return "";
}
/**
* Return the serial of device.
*
* @return the serial of device
*/
@SuppressLint("MissingPermission")
@RequiresPermission(READ_PHONE_STATE)
public static String getSerial() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? Build.getSerial() : Build.SERIAL;
}
/**
* Return the IMEI.
* <p>Must hold {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
*
* @return the IMEI
*/
@SuppressLint("MissingPermission")
@RequiresPermission(READ_PHONE_STATE)
public static String getIMEI() {
TelephonyManager tm = getTelephonyManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return tm.getImei();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
Class clazz = tm.getClass();
//noinspection unchecked
Method getImeiMethod = clazz.getDeclaredMethod("getImei");
getImeiMethod.setAccessible(true);
String imei = (String) getImeiMethod.invoke(tm);
if (imei != null) return imei;
} catch (Exception e) {
Log.e("PhoneUtils", "getIMEI: ", e);
}
}
String imei = tm.getDeviceId();
if (imei != null && imei.length() == 15) {
return imei;
}
return "";
}
/**
* Return the IMEI.
* <p>Must hold {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
*
* @param slotId of which deviceID is returned
* @return the IMEI
*/
@SuppressLint("MissingPermission")
@RequiresPermission(READ_PHONE_STATE)
public static String getIMEI(int slotId) {
TelephonyManager tm = getTelephonyManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return tm.getImei(slotId);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
Class clazz = tm.getClass();
//noinspection unchecked
Method getImeiMethod = clazz.getDeclaredMethod("getImei", int.class);
getImeiMethod.setAccessible(true);
String imei = (String) getImeiMethod.invoke(tm, slotId);
if (imei != null) return imei;
} catch (Exception e) {
Log.e("PhoneUtils", "getIMEI: ", e);
}
}
return getIMEI();
}
/**
* Return the MEID.
* <p>Must hold {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
*
* @return the MEID
*/
@SuppressLint("MissingPermission")
@RequiresPermission(READ_PHONE_STATE)
public static String getMEID() {
TelephonyManager tm = getTelephonyManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return tm.getMeid();
}
return tm.getDeviceId();
}
/**
* Return the MEID.
* <p>Must hold {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
*
* @return the MEID
*/
@SuppressLint("MissingPermission")
@RequiresPermission(READ_PHONE_STATE)
public static String getMEID(final int slotId) {
TelephonyManager tm = getTelephonyManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return tm.getMeid(slotId);
}
return getMEID();
}
/**
* Return the IMSI.
* <p>Must hold {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
*
* @return the IMSI
*/
@SuppressLint("MissingPermission")
@RequiresPermission(READ_PHONE_STATE)
public static String getIMSI() {
TelephonyManager tm = getTelephonyManager();
return tm.getSubscriberId();
}
/**
* Returns the current phone type.
*
* @return the current phone type
* <ul>
* <li>{@link TelephonyManager#PHONE_TYPE_NONE}</li>
* <li>{@link TelephonyManager#PHONE_TYPE_GSM }</li>
* <li>{@link TelephonyManager#PHONE_TYPE_CDMA}</li>
* <li>{@link TelephonyManager#PHONE_TYPE_SIP }</li>
* </ul>
*/
public static int getPhoneType() {
TelephonyManager tm = getTelephonyManager();
return tm.getPhoneType();
}
/**
* Return whether sim card state is ready.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isSimCardReady() {
TelephonyManager tm = getTelephonyManager();
return tm.getSimState() == TelephonyManager.SIM_STATE_READY;
}
/**
* Return the sim operator name.
*
* @return the sim operator name
*/
public static String getSimOperatorName() {
TelephonyManager tm = getTelephonyManager();
return tm.getSimOperatorName();
}
/**
* Return the sim operator using mnc.
*
* @return the sim operator
*/
public static String getSimOperatorByMnc() {
TelephonyManager tm = getTelephonyManager();
String operator = tm.getSimOperator();
if (operator == null) return "";
switch (operator) {
case "46000":
case "46002":
case "46007":
case "46020":
return "中国移动";
case "46001":
case "46006":
case "46009":
return "中国联通";
case "46003":
case "46005":
case "46011":
return "中国电信";
default:
return operator;
}
}
/**
* Return the phone status.
* <p>Must hold {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
*
* @return DeviceId = 99000311726612<br>
* DeviceSoftwareVersion = 00<br>
* Line1Number =<br>
* NetworkCountryIso = cn<br>
* NetworkOperator = 46003<br>
* NetworkOperatorName = 中国电信<br>
* NetworkType = 6<br>
* PhoneType = 2<br>
* SimCountryIso = cn<br>
* SimOperator = 46003<br>
* SimOperatorName = 中国电信<br>
* SimSerialNumber = 89860315045710604022<br>
* SimState = 5<br>
* SubscriberId(IMSI) = 460030419724900<br>
* VoiceMailNumber = *86<br>
*/
@SuppressLint("MissingPermission")
@RequiresPermission(READ_PHONE_STATE)
public static String getPhoneStatus() {
TelephonyManager tm = getTelephonyManager();
String str = "";
//noinspection ConstantConditions
str += "DeviceId(IMEI) = " + tm.getDeviceId() + "\n";
str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + "\n";
str += "Line1Number = " + tm.getLine1Number() + "\n";
str += "NetworkCountryIso = " + tm.getNetworkCountryIso() + "\n";
str += "NetworkOperator = " + tm.getNetworkOperator() + "\n";
str += "NetworkOperatorName = " + tm.getNetworkOperatorName() + "\n";
str += "NetworkType = " + tm.getNetworkType() + "\n";
str += "PhoneType = " + tm.getPhoneType() + "\n";
str += "SimCountryIso = " + tm.getSimCountryIso() + "\n";
str += "SimOperator = " + tm.getSimOperator() + "\n";
str += "SimOperatorName = " + tm.getSimOperatorName() + "\n";
str += "SimSerialNumber = " + tm.getSimSerialNumber() + "\n";
str += "SimState = " + tm.getSimState() + "\n";
str += "SubscriberId(IMSI) = " + tm.getSubscriberId() + "\n";
str += "VoiceMailNumber = " + tm.getVoiceMailNumber();
return str;
}
/**
* Skip to dial.
*
* @param phoneNumber The phone number.
* @return {@code true}: operate successfully<br>{@code false}: otherwise
*/
public static boolean dial(final String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
if (isIntentAvailable(intent)) {
SReminderApp.getInstance().startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
return true;
}
return false;
}
/**
* Make a phone call.
* <p>Must hold {@code <uses-permission android:name="android.permission.CALL_PHONE" />}</p>
*
* @param phoneNumber The phone number.
* @return {@code true}: operate successfully<br>{@code false}: otherwise
*/
@RequiresPermission(CALL_PHONE)
public static boolean call(final String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
if (isIntentAvailable(intent)) {
SReminderApp.getInstance().startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
return true;
}
return false;
}
/**
* Send sms.
*
* @param phoneNumber The phone number.
* @param content The content.
* @return {@code true}: operate successfully<br>{@code false}: otherwise
*/
public static boolean sendSms(final String phoneNumber, final String content) {
Uri uri = Uri.parse("smsto:" + phoneNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
if (isIntentAvailable(intent)) {
intent.putExtra("sms_body", content);
SReminderApp.getInstance().startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
return true;
}
return false;
}
/**
* Send sms silently.
* <p>Must hold {@code <uses-permission android:name="android.permission.SEND_SMS" />}</p>
*
* @param phoneNumber The phone number.
* @param content The content.
*/
@RequiresPermission(SEND_SMS)
public static void sendSmsSilent(final String phoneNumber, final String content) {
if (TextUtils.isEmpty(content)) return;
PendingIntent sentIntent = PendingIntent.getBroadcast(SReminderApp.getInstance(), 0, new Intent("send"), 0);
SmsManager smsManager = SmsManager.getDefault();
if (content.length() >= 70) {
List<String> ms = smsManager.divideMessage(content);
for (String str : ms) {
smsManager.sendTextMessage(phoneNumber, null, str, sentIntent, null);
}
} else {
smsManager.sendTextMessage(phoneNumber, null, content, sentIntent, null);
}
}
private static TelephonyManager getTelephonyManager() {
return (TelephonyManager) SReminderApp.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
}
public static boolean isIntentAvailable(final Intent intent) {
return SReminderApp.getInstance()
.getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
.size() > 0;
}
public static String getIPAddress() {
String ipAddressStr = "";
InetAddress inetAddress = getLocalInetAddress();
if (inetAddress != null){
ipAddressStr = inetAddress.getHostAddress();
}
return ipAddressStr;
}
public static InetAddress getLocalInetAddress(){
InetAddress inetAddress = null;
try {
Enumeration<NetworkInterface> networkInterfaceEnum =
NetworkInterface.getNetworkInterfaces();
while (networkInterfaceEnum.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaceEnum.nextElement();
Enumeration<InetAddress> enumIpAddress =
networkInterface.getInetAddresses();
while (enumIpAddress.hasMoreElements()) {
InetAddress inetAdd = enumIpAddress.nextElement();
if (!inetAdd.isLoopbackAddress() && inetAdd instanceof Inet4Address) {
inetAddress = inetAdd;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return inetAddress;
}
public static String getMACAddress(){
String macAddressStr = "";
try {
List<NetworkInterface> networkInterfaceList =
Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface netInterface : networkInterfaceList){
if (!netInterface.getName().equalsIgnoreCase("wlan0")){
continue;
}
byte[] macBytes = netInterface.getHardwareAddress();
if (macBytes == null) {
return macAddressStr;
}
StringBuilder stringBuilder = new StringBuilder();
for (byte b: macBytes){
stringBuilder.append(String.format("%02x:" , b));
}
if (stringBuilder.length() > 0){
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
macAddressStr = stringBuilder.toString().toUpperCase();
}
} catch (SocketException e) {
e.printStackTrace();
}
return macAddressStr;
}
}
六、RegexUtils
public final class RegexUtils {
private final static SimpleArrayMap<String, String> CITY_MAP = new SimpleArrayMap<>();
private RegexUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Return whether input matches regex of simple mobile.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isMobileSimple(final CharSequence input) {
return isMatch(RegexConstants.REGEX_MOBILE_SIMPLE, input);
}
/**
* Return whether input matches regex of exact mobile.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isMobileExact(final CharSequence input) {
return isMatch(RegexConstants.REGEX_MOBILE_EXACT, input);
}
/**
* Return whether input matches regex of telephone number.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isTel(final CharSequence input) {
return isMatch(RegexConstants.REGEX_TEL, input);
}
/**
* Return whether input matches regex of id card number which length is 15.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isIDCard15(final CharSequence input) {
return isMatch(RegexConstants.REGEX_ID_CARD15, input);
}
/**
* Return whether input matches regex of id card number which length is 18.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isIDCard18(final CharSequence input) {
return isMatch(RegexConstants.REGEX_ID_CARD18, input);
}
/**
* Return whether input matches regex of exact id card number which length is 18.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isIDCard18Exact(final CharSequence input) {
if (isIDCard18(input)) {
int[] factor = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
char[] suffix = new char[]{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
if (CITY_MAP.isEmpty()) {
CITY_MAP.put("11", "北京");
CITY_MAP.put("12", "天津");
CITY_MAP.put("13", "河北");
CITY_MAP.put("14", "山西");
CITY_MAP.put("15", "内蒙古");
CITY_MAP.put("21", "辽宁");
CITY_MAP.put("22", "吉林");
CITY_MAP.put("23", "黑龙江");
CITY_MAP.put("31", "上海");
CITY_MAP.put("32", "江苏");
CITY_MAP.put("33", "浙江");
CITY_MAP.put("34", "安徽");
CITY_MAP.put("35", "福建");
CITY_MAP.put("36", "江西");
CITY_MAP.put("37", "山东");
CITY_MAP.put("41", "河南");
CITY_MAP.put("42", "湖北");
CITY_MAP.put("43", "湖南");
CITY_MAP.put("44", "广东");
CITY_MAP.put("45", "广西");
CITY_MAP.put("46", "海南");
CITY_MAP.put("50", "重庆");
CITY_MAP.put("51", "四川");
CITY_MAP.put("52", "贵州");
CITY_MAP.put("53", "云南");
CITY_MAP.put("54", "西藏");
CITY_MAP.put("61", "陕西");
CITY_MAP.put("62", "甘肃");
CITY_MAP.put("63", "青海");
CITY_MAP.put("64", "宁夏");
CITY_MAP.put("65", "新疆");
CITY_MAP.put("71", "台湾");
CITY_MAP.put("81", "香港");
CITY_MAP.put("82", "澳门");
CITY_MAP.put("91", "国外");
}
if (CITY_MAP.get(input.subSequence(0, 2).toString()) != null) {
int weightSum = 0;
for (int i = 0; i < 17; ++i) {
weightSum += (input.charAt(i) - '0') * factor[i];
}
int idCardMod = weightSum % 11;
char idCardLast = input.charAt(17);
return idCardLast == suffix[idCardMod];
}
}
return false;
}
/**
* Return whether input matches regex of email.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isEmail(final CharSequence input) {
return isMatch(RegexConstants.REGEX_EMAIL, input);
}
/**
* Return whether input matches regex of url.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isURL(final CharSequence input) {
return isMatch(RegexConstants.REGEX_URL, input);
}
/**
* Return whether input matches regex of Chinese character.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isZh(final CharSequence input) {
return isMatch(RegexConstants.REGEX_ZH, input);
}
/**
* Return whether input matches regex of username.
* <p>scope for "a-z", "A-Z", "0-9", "_", "Chinese character"</p>
* <p>can't end with "_"</p>
* <p>length is between 6 to 20</p>.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isUsername(final CharSequence input) {
return isMatch(RegexConstants.REGEX_USERNAME, input);
}
/**
* Return whether input matches regex of date which pattern is "yyyy-MM-dd".
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isDate(final CharSequence input) {
return isMatch(RegexConstants.REGEX_DATE, input);
}
/**
* Return whether input matches regex of ip address.
*
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isIP(final CharSequence input) {
return isMatch(RegexConstants.REGEX_IP, input);
}
/**
* Return whether input matches the regex.
*
* @param regex The regex.
* @param input The input.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isMatch(final String regex, final CharSequence input) {
return input != null && input.length() > 0 && Pattern.matches(regex, input);
}
/**
* Return the list of input matches the regex.
*
* @param regex The regex.
* @param input The input.
* @return the list of input matches the regex
*/
public static List<String> getMatches(final String regex, final CharSequence input) {
if (input == null) return Collections.emptyList();
List<String> matches = new ArrayList<>();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
matches.add(matcher.group());
}
return matches;
}
/**
* Splits input around matches of the regex.
*
* @param input The input.
* @param regex The regex.
* @return the array of strings computed by splitting input around matches of regex
*/
public static String[] getSplits(final String input, final String regex) {
if (input == null) return new String[0];
return input.split(regex);
}
/**
* Replace the first subsequence of the input sequence that matches the
* regex with the given replacement string.
*
* @param input The input.
* @param regex The regex.
* @param replacement The replacement string.
* @return the string constructed by replacing the first matching
* subsequence by the replacement string, substituting captured
* subsequences as needed
*/
public static String getReplaceFirst(final String input,
final String regex,
final String replacement) {
if (input == null) return "";
return Pattern.compile(regex).matcher(input).replaceFirst(replacement);
}
/**
* Replace every subsequence of the input sequence that matches the
* pattern with the given replacement string.
*
* @param input The input.
* @param regex The regex.
* @param replacement The replacement string.
* @return the string constructed by replacing each matching subsequence
* by the replacement string, substituting captured subsequences
* as needed
*/
public static String getReplaceAll(final String input,
final String regex,
final String replacement) {
if (input == null) return "";
return Pattern.compile(regex).matcher(input).replaceAll(replacement);
}
}
public final class RegexConstants {
/**
* Regex of simple mobile.
*/
public static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$";
/**
* Regex of exact mobile.
* <p>china mobile: 134(0-8), 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 178, 182, 183, 184, 187, 188, 198</p>
* <p>china unicom: 130, 131, 132, 145, 155, 156, 166, 171, 175, 176, 185, 186</p>
* <p>china telecom: 133, 153, 173, 177, 180, 181, 189, 199</p>
* <p>global star: 1349</p>
* <p>virtual operator: 170</p>
*/
public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(16[6])|(17[0,1,3,5-8])|(18[0-9])|(19[8,9]))\\d{8}$";
/**
* Regex of telephone number.
*/
public static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";
/**
* Regex of id card number which length is 15.
*/
public static final String REGEX_ID_CARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
/**
* Regex of id card number which length is 18.
*/
public static final String REGEX_ID_CARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$";
/**
* Regex of email.
*/
public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
/**
* Regex of url.
*/
public static final String REGEX_URL = "[a-zA-z]+://[^\\s]*";
/**
* Regex of Chinese character.
*/
public static final String REGEX_ZH = "^[\\u4e00-\\u9fa5]+$";
/**
* Regex of username.
* <p>scope for "a-z", "A-Z", "0-9", "_", "Chinese character"</p>
* <p>can't end with "_"</p>
* <p>length is between 6 to 20</p>
*/
public static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$";
/**
* Regex of date which pattern is "yyyy-MM-dd".
*/
public static final String REGEX_DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
/**
* Regex of ip address.
*/
public static final String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
///////////////////////////////////////////////////////////////////////////
// The following come from http://tool.oschina.net/regex
///////////////////////////////////////////////////////////////////////////
/**
* Regex of double-byte characters.
*/
public static final String REGEX_DOUBLE_BYTE_CHAR = "[^\\x00-\\xff]";
/**
* Regex of blank line.
*/
public static final String REGEX_BLANK_LINE = "\\n\\s*\\r";
/**
* Regex of QQ number.
*/
public static final String REGEX_QQ_NUM = "[1-9][0-9]{4,}";
/**
* Regex of postal code in China.
*/
public static final String REGEX_CHINA_POSTAL_CODE = "[1-9]\\d{5}(?!\\d)";
/**
* Regex of positive integer.
*/
public static final String REGEX_POSITIVE_INTEGER = "^[1-9]\\d*$";
/**
* Regex of negative integer.
*/
public static final String REGEX_NEGATIVE_INTEGER = "^-[1-9]\\d*$";
/**
* Regex of integer.
*/
public static final String REGEX_INTEGER = "^-?[1-9]\\d*$";
/**
* Regex of non-negative integer.
*/
public static final String REGEX_NOT_NEGATIVE_INTEGER = "^[1-9]\\d*|0$";
/**
* Regex of non-positive integer.
*/
public static final String REGEX_NOT_POSITIVE_INTEGER = "^-[1-9]\\d*|0$";
/**
* Regex of positive float.
*/
public static final String REGEX_POSITIVE_FLOAT = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$";
/**
* Regex of negative float.
*/
public static final String REGEX_NEGATIVE_FLOAT = "^-[1-9]\\d*\\.\\d*|-0\\.\\d*[1-9]\\d*$";
///////////////////////////////////////////////////////////////////////////
// If u want more please visit http://toutiao.com/i6231678548520731137
///////////////////////////////////////////////////////////////////////////
}
七、ScreenUtils
public final class ScreenUtils {
private ScreenUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Return the width of screen, in pixel.
*
* @return the width of screen, in pixel
*/
public static int getScreenWidth() {
WindowManager wm = (WindowManager) SReminderApp.getInstance().getSystemService(Context.WINDOW_SERVICE);
Point point = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//noinspection ConstantConditions
wm.getDefaultDisplay().getRealSize(point);
} else {
//noinspection ConstantConditions
wm.getDefaultDisplay().getSize(point);
}
return point.x;
}
/**
* Return the height of screen excluding cutout , in pixel.
*
* @return the height of screen excluding cutout, in pixel
*/
public static int getScreenHeightExcludeCutout(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
/**
* Return the real height of screen, in pixel.
*
* @return the height of screen, in pixel
*/
public static int getScreenHeight() {
WindowManager wm = (WindowManager) SReminderApp.getInstance().getSystemService(Context.WINDOW_SERVICE);
Point point = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//noinspection ConstantConditions
wm.getDefaultDisplay().getRealSize(point);
} else {
//noinspection ConstantConditions
wm.getDefaultDisplay().getSize(point);
}
return point.y;
}
/**
* Return the density of screen.
*
* @return the density of screen
*/
public static float getScreenDensity() {
return Resources.getSystem().getDisplayMetrics().density;
}
/**
* Return the screen density expressed as dots-per-inch.
*
* @return the screen density expressed as dots-per-inch
*/
public static int getScreenDensityDpi() {
return Resources.getSystem().getDisplayMetrics().densityDpi;
}
/**
* Set full screen.
*
* @param activity The activity.
*/
public static void setFullScreen(@NonNull final Activity activity) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
/**
* Set non full screen.
*
* @param activity The activity.
*/
public static void setNonFullScreen(@NonNull final Activity activity) {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
/**
* Toggle full screen.
*
* @param activity The activity.
*/
public static void toggleFullScreen(@NonNull final Activity activity) {
int fullScreenFlag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
Window window = activity.getWindow();
if ((window.getAttributes().flags & fullScreenFlag) == fullScreenFlag) {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
/**
* Return whether screen is full.
*
* @param activity The activity.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isFullScreen(@NonNull final Activity activity) {
int fullScreenFlag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
return (activity.getWindow().getAttributes().flags & fullScreenFlag) == fullScreenFlag;
}
/**
* Set the screen to landscape.
*
* @param activity The activity.
*/
public static void setLandscape(@NonNull final Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
/**
* Set the screen to portrait.
*
* @param activity The activity.
*/
public static void setPortrait(@NonNull final Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
/**
* Return whether screen is landscape.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isLandscape() {
return SReminderApp.getInstance().getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
}
/**
* Return whether screen is portrait.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isPortrait() {
return SReminderApp.getInstance().getResources().getConfiguration().orientation
== Configuration.ORIENTATION_PORTRAIT;
}
/**
* Return the rotation of screen.
*
* @param activity The activity.
* @return the rotation of screen
*/
public static int getScreenRotation(@NonNull final Activity activity) {
switch (activity.getWindowManager().getDefaultDisplay().getRotation()) {
case Surface.ROTATION_0:
return 0;
case Surface.ROTATION_90:
return 90;
case Surface.ROTATION_180:
return 180;
case Surface.ROTATION_270:
return 270;
default:
return 0;
}
}
/**
* Return the bitmap of screen.
*
* @param activity The activity.
* @return the bitmap of screen
*/
public static Bitmap screenShot(@NonNull final Activity activity) {
return screenShot(activity, false);
}
/**
* Return the bitmap of screen.
*
* @param activity The activity.
* @param isDeleteStatusBar True to delete status bar, false otherwise.
* @return the bitmap of screen
*/
public static Bitmap screenShot(@NonNull final Activity activity, boolean isDeleteStatusBar) {
View decorView = activity.getWindow().getDecorView();
decorView.setDrawingCacheEnabled(true);
decorView.setWillNotCacheDrawing(false);
Bitmap bmp = decorView.getDrawingCache();
if (bmp == null) return null;
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
Bitmap ret;
if (isDeleteStatusBar) {
Resources resources = activity.getResources();
int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
int statusBarHeight = resources.getDimensionPixelSize(resourceId);
ret = Bitmap.createBitmap(
bmp,
0,
statusBarHeight,
dm.widthPixels,
dm.heightPixels - statusBarHeight
);
} else {
ret = Bitmap.createBitmap(bmp, 0, 0, dm.widthPixels, dm.heightPixels);
}
decorView.destroyDrawingCache();
return ret;
}
/**
* Return whether screen is locked.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isScreenLock() {
KeyguardManager km =
(KeyguardManager) SReminderApp.getInstance().getSystemService(Context.KEYGUARD_SERVICE);
//noinspection ConstantConditions
return km.inKeyguardRestrictedInputMode();
}
/**
* Set the duration of sleep.
* <p>Must hold {@code <uses-permission android:name="android.permission.WRITE_SETTINGS" />}</p>
*
* @param duration The duration.
*/
@RequiresPermission(WRITE_SETTINGS)
public static void setSleepDuration(final int duration) {
Settings.System.putInt(
SReminderApp.getInstance().getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT,
duration
);
}
/**
* Return the duration of sleep.
*
* @return the duration of sleep.
*/
public static int getSleepDuration() {
try {
return Settings.System.getInt(
SReminderApp.getInstance().getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT
);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return -123;
}
}
/**
* Return whether device is tablet.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isTablet() {
return (SReminderApp.getInstance().getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
/**
* Request to dismiss the lock screen.
*
* @param activity The activity which request to unlock the screen
* @param callback The callback to be called if the request to dismiss Keyguard was successful
* or null if the caller isn't interested in knowing the result. The callback
* will not be invoked if the activity was destroyed before the callback was
* received.
* @Attention before this function, you should check the status of lock screen by yourself (use isScreenLock() above)
*/
public static void requestDismissLockScreen(Activity activity, KeyguardManager.KeyguardDismissCallback callback) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || callback == null) {
return;
}
KeyguardManager keyguardManager = (KeyguardManager) SReminderApp.getInstance().getSystemService(Context.KEYGUARD_SERVICE);
if (keyguardManager == null) {
callback.onDismissError();
return;
}
keyguardManager.requestDismissKeyguard(activity, callback);
}
}
网友评论