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

android编程中用到的小功能集合(持续更新)

2017-09-13 15:41 337 查看

在android编程过程中,有些实用的小功能会经常使用,一般统一放在一个或几个类里,这里就列举用到的一些小功能:

1.判断手机号码是否正确

public static boolean checkPhoneNumber(String mobiles) {
Pattern p = null;
Matcher m = null;
boolean b = false;
p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
m = p.matcher(mobiles);
b = m.matches();
return b;
}


2.判断字符串是否为空

public static boolean isEmpty(String str) {
if (str == null || str.length() == 0 || str.equalsIgnoreCase("null") || str.isEmpty() || str.equals("")) {
return true;
} else {
return false;
}
}


3.获取当前时间,格式可修改

public static String getNowDate()
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
return df.format(System.currentTimeMillis());
}


4.判断字符是否包含中文

public static boolean isContainChinese(String str) {

Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}


5.bytes字符串转换为Byte值

public static byte[] hexStr2Bytes(String src)
{
int m=0,n=0;
int l=src.length()/2;
System.out.println(l);
byte[] ret = new byte[l];
for (int i = 0; i < l; i++)
{
m=i*2+1;
n=m+1;

int intValue = Integer.decode("0x" + src.substring(i*2, m) + src.substring(m,n));
ret[i] = (byte) intValue;
}
return ret;
}


6.bytes转换成十六进制字符串 ,type控制是否插入空格

public static String byte2HexStr(byte[] b,int type)
{
String stmp="";
StringBuilder sb = new StringBuilder("");
for (int n=0;n<b.length;n++)
{
stmp = Integer.toHexString(b
& 0xFF);
sb.append((stmp.length()==1)? "0"+stmp : stmp);
if(type==1)
sb.append(" ");
}
return sb.toString().toUpperCase().trim();
}


7.异或校验,通过len可控制具体校验长度

public static byte xor(byte[] x, int len)
{
byte y = 0;
for (int idx = 0; idx < len; idx++)
{
y ^= x[idx];
}

return y;
}


8.判断是否联网

public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected())
{
// 当前网络是连接的
if (info.getState() == NetworkInfo.State.CONNECTED)
{
// 当前所连接的网络可用
return true;
}
}
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: