您的位置:首页 > 移动开发 > Android开发

Android开发中一些常用的工具类汇总

2017-06-02 09:36 429 查看

1、手机号匹配

/**
* 匹配手机
* @param number
* @return
*/
public static boolean isPhoneNumber(String number){
/*		三大运营商号段: 在百度百科上查询结果
中国移动号段:134、135、136、137、138、139、150、151、152、157、158、159、147、182、183、184、187、188、1705[1]  、178
中国联通号段:130、131、132、145(145属于联通无线上网卡号段)、155、156、185、186 、176、1709[1]  、176
中国电信号段:133 、153 、180 、181 、189、1700[1]  、177*/
Pattern p = Pattern.compile("^((1[358][0-9])|(14[57])|(17[0678]))\\d{8}$");
Matcher m = p.matcher(number);
return m.matches();
}

2、应用前后台的判断

            方法一:参照之前的一篇文章
            方法二:
/**
* 应用前后台的判断
* @param context
* @return
*/
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {

if (appProcess.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
CustomLog.d("处于后台" + appProcess.processName);
return true;
} else {
CustomLog.d("处于前台" + appProcess.processName);
return false;
}
}
}
return false;
}

3、网络相关的工具类

1、当前是否为wifi:
/**
* 当前是否wifi
* @param mcontext
* @return
* @author
* @data
*/
public static boolean isConnectWifi(Context mcontext) {
ConnectivityManager connMng = (ConnectivityManager) mcontext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInf = connMng.getActiveNetworkInfo();
return netInf != null && "WIFI".equalsIgnoreCase(netInf.getTypeName());
}
2、获取本机的IP地址
/**
* 获了本机的IP地址
* @param useIPv4
* @return
* @author
* @data
*/
public static String getIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress().toUpperCase();
boolean isIPv4 = addr instanceof Inet4Address;
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%');
return delim<0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}


3、判断网络是否可用及网络类型
/**
* 无网络联接
*/
public static final int NETWORK_ON = 0;
/**
* WIFI网络
*/
public static final int NETWORK_WIFI = 1;
/**
* 2G网络(包含:2.75G  2.5G 2G)
*/
public static final int NETWORK_EDGE = 2;
/**
* 3G网络(包含:3G  3.5G  3.75G)
*/
public static final int NETWORK_3G = 3;

/**
* 获取当前的网络类型
* @param mContext
* @author
* @data
*/
public static int getCurrentNetWorkType(Context mContext){
int currentNetWorkType = NETWORK_ON;
NetworkInfo activeNetInfo =  getNetworkInfo(mContext);
int netSubtype = -1;
if (activeNetInfo != null) {
netSubtype = activeNetInfo.getSubtype();
}
if (activeNetInfo != null && activeNetInfo.isConnected()) {
if ("WIFI".equalsIgnoreCase(activeNetInfo.getTypeName())) {
currentNetWorkType = NETWORK_WIFI;
} else if (activeNetInfo.getTypeName() != null
&& activeNetInfo.getTypeName().toLowerCase().contains("mobile")) {// 3g,双卡手机有时为mobile2
if (netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
|| netSubtype == TelephonyManager.NETWORK_TYPE_EVDO_0
|| netSubtype == TelephonyManager.NETWORK_TYPE_EVDO_A
|| netSubtype == TelephonyManager.NETWORK_TYPE_EVDO_B
|| netSubtype == TelephonyManager.NETWORK_TYPE_EHRPD
|| netSubtype == TelephonyManager.NETWORK_TYPE_HSDPA
|| netSubtype == TelephonyManager.NETWORK_TYPE_HSUPA
|| netSubtype == TelephonyManager.NETWORK_TYPE_HSPA
|| netSubtype == TelephonyManager.NETWORK_TYPE_LTE
// 4.0系统 H+网络为15 TelephonyManager.NETWORK_TYPE_HSPAP
|| netSubtype == 15
/** Current network is LTE_CA {@hide} */
|| netSubtype == 19 ) {
currentNetWorkType = NETWORK_3G;
}  else {
currentNetWorkType = NETWORK_EDGE;
}
}
}
return currentNetWorkType;
}

private static NetworkInfo getNetworkInfo(Context mContext){
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo();
}

public static boolean isNetWorkConnect(Context mContext){
NetworkInfo activeNetInfo =  getNetworkInfo(mContext);
return (activeNetInfo != null && activeNetInfo.isConnected());
}
  
  4、网络地址判断

/**
* 是否是网络地址
* @param address 网络地址字符串
* @return true:匹配正确,false:匹配错误
*/
public static boolean isNetAddress(String address){
Pattern pattern = Pattern.compile("^[[a-z0-9]{1,}//.]{1}[[a-z0-9]{1,}//.]{1,}[a-z0-9]{1,}$");
Matcher matcher = pattern.matcher(address);
if(matcher.matches()){
//继续匹配
pattern = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$");
matcher = pattern.matcher(address);
while(matcher.find()){
if(Integer.parseInt(matcher.group(1)) > 255 || Integer.parseInt(matcher.group(2)) > 255
|| Integer.parseInt(matcher.group(3)) > 255 || Integer.parseInt(matcher.group(4)) > 255){
return false;
}
}
return true;
}else{
return false;
}
}

/**
* 是否是Int类型的数字
* @param port 端口号
* @return true:匹配正确,false:匹配错误
*/
public static boolean isPort(String port){
Pattern pattern = Pattern.compile("^[1-9]{1}[0-9]+$");
Matcher matcher = pattern.matcher(port);
return matcher.matches();
}


4、用MD5生成的文件名

/**
* @Title Md5FileNameGenerator
* @Description Md5文件名生成器
* @author
* @date
*/
public class Md5FileNameGenerator {

private static final String HASH_ALGORITHM = "MD5";
private static final int RADIX = 10 + 26; // 10 digits + 26 letters

public static String generate(String imageUri) {
byte[] md5 = getMD5(imageUri.getBytes());
BigInteger bi = new BigInteger(md5).abs();
return bi.toString(RADIX);
}

private static byte[] getMD5(byte[] data) {
byte[] hash = null;
try {
MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
digest.update(data);
hash = digest.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hash;
}

}

5、判断CPU类型

private static final String CPU_ARCHITECTURE_KEY_64 = "ro.product.cpu.abilist64";
private static final String PROC_CPU_INFO_PATH = "/proc/cpuinfo";

/**
* @return
* @descript:判断CPU是否是64位
*/
public static boolean isCPU64Bit() {
if (TextUtils.isEmpty(getSystemProperty(CPU_ARCHITECTURE_KEY_64, ""))) {
if (isCPUInfo64()) {
CustomLog.d("64bit cpu");
return true;
} else {
CustomLog.d("32bit cpu");
return false;
}
} else {
CustomLog.d("64bit cpu");
return true;
}
}

/**
* @param key 属性KEY值
* @param defaultValue 默认值
* @return
* @descript:获取系统属性
*/
private static String getSystemProperty(String key, String defaultValue) {
boolean LOGENABLE = true;
String value = defaultValue;
try {
Class<?> clazz = Class.forName("android.os.SystemProperties");
Method get = clazz.getMethod("get", String.class, String.class);
value = (String) (get.invoke(clazz, key, ""));
} catch (Exception e) {
if (LOGENABLE) {
Log.d("getSystemProperty",
"key = " + key + ", error = " + e.getMessage());
}
}

if (LOGENABLE) {
Log.d("getSystemProperty", key + " = " + value);
}
return value;
}

/**
* @return
* @descript:判断CPU信息文件里是否包含arch64
*/
private static boolean isCPUInfo64() {
File cpuInfo = new File(PROC_CPU_INFO_PATH);
if (cpuInfo != null && cpuInfo.exists()) {
InputStream inputStream = null;
BufferedReader bufferedReader = null;
try {
inputStream = new FileInputStream(cpuInfo);
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream), 512);
String line = bufferedReader.readLine();
if (line != null && line.length() > 0
&& line.toLowerCase(Locale.US).contains("arch64")) {

return true;
}
} catch (Throwable t) {

} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}

try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return false;
}

6、获取最新图片路径

/**
* 获取最新的图片
* @param context
* @param uri
* @return
*/
public static String getImagPath(Context context){
//只查询jpeg和png的图片  ,最新的图片
Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver mContentResolver = context.getContentResolver();

//只查询jpeg和png的图片
Cursor mCursor = mContentResolver.query(mImageUri, null,
MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=?",
new String[] { "image/jpeg", "image/png" }, MediaStore.Images.Media.DATE_MODIFIED+" desc");

if(mCursor == null){
return "";
}
String filePath = "";
if(mCursor != null && mCursor.moveToFirst()){
if (mCursor.getColumnIndex(MediaStore.Images.Media.DATA) > -1) {
int column_index = mCursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
filePath = mCursor.getString(column_index);
}
mCursor.close();
}
return filePath;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: