在开发中经常会反复用到一些功能,未节省时间,在此将常用到的一些工具进行总结:
一、Log日志打印
对于一个开发者来说,Log打印是必不可少的
/**
*
* 功能: 封装log ,以备发布Release时,关闭对应的 log 日志显示。只需调整LOG_LEVEL =0即可
* 使用:
*/
public class MyLog {
public static int LOG_LEVEL = 6;
public static int ERROR = 1;
public static int WARN = 2;
public static int INFO = 3;
public static int DEBUG = 4;
public static int VERBOS = 5;
public static void e(String tag,String msg){
if(LOG_LEVEL>ERROR)
Log.e(tag, msg);
}
public static void w(String tag,String msg){
if(LOG_LEVEL>WARN)
Log.w(tag, msg);
}
public static void i(String tag,String msg){
if(LOG_LEVEL>INFO)
Log.i(tag, msg);
}
public static void d(String tag,String msg){
if(LOG_LEVEL>DEBUG)
Log.d(tag, msg);
}
public static void v(String tag,String msg){
if(LOG_LEVEL>VERBOS)
Log.v(tag, msg);
}
}
二、网络判断
开发中,经常会用来进行判断网络连接状态
public static boolean isNetworkConnect(Context context) {
boolean isAvailable = false;
boolean isConnectedOrConnecting = false;
boolean isConnected = false;
Integer networkType = null;
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNet = connectivity.getActiveNetworkInfo();
if (null != activeNet) {
isAvailable = activeNet.isAvailable();
networkType = activeNet.getType(); // 获取网络类型 0-移动网络,1-wifi网络
isConnectedOrConnecting = activeNet.isConnectedOrConnecting();
isConnected = activeNet.isConnected();
}
String TAG = "isNetworkConnect";
MyLog.d(TAG, TAG + " Method isNetworkConnected() result:"
+ " networkType=" + networkType + ", isAvailable="
+ isAvailable + ", isConnectedOrConnecting="
+ isConnectedOrConnecting + ", isConnected=" + isConnected);
return isAvailable;
}
三、时间格式转换
时间的转换必不可少
/**
* 根据时间毫秒字符串,转换成对应的时间格式
* @param formatType
* <br> 默认是0
* <br> 0:使用你自己的格式;
* <br> 1: 2016年12月09日 22:05 星期二
* <br> 2: 2016-12-22
* <br> 3: 2016-12-22 12:12
* @param uDateFormat
* @param mills
* @return 有待于改进,返回一个 跟进时间进行显示的,当月显示当月时间,当天显示当天时间,非今年显示费今年时间
*/
public static String getFormatDate(String uDateFormat,Long mills,int formatType) {
try {
switch (formatType) {
case 1:
uDateFormat="yyyy年MM月dd日 HH:mm EEEE";
break;
case 2:
uDateFormat="yyyy-MM-dd";
break;
case 3:
uDateFormat="yyyy-MM-dd HH:mm";
break;
default:
if (TextUtils.isEmpty(uDateFormat)) {
return mills+"";
}
break;
}
Date date=new Date(mills);
SimpleDateFormat sdf=new SimpleDateFormat(uDateFormat);
return sdf.format(date);
} catch (Exception e) {
return mills+"";
}
}
四、版本信息获取
版本会一直处于迭代维护中,需不断更新,这里你需要用到之前版本号等相关信息
// 取得版本名称
public static String getVersionName(Context context) {
try {
PackageInfo manager = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return manager.versionName;
} catch (NameNotFoundException e) {
return "Unknown";
}
}
// 取得版本号
public static int getVersionCode(Context context) {
try {
PackageInfo manager = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return manager.versionCode;
} catch (NameNotFoundException e) {
return -1;
}
}
五、判断字符串是否为空
很简单的一个工具,但是开发中也是必不可少的
public static boolean isNullOrEmpty(String str) {
if (str == null || str.trim().length() == 0) {
return true;
}
return false;
}
六、汉字转换拼音
多用在通讯录通过首字母排序中
/**
* 方法名 :isSpecialChar
* <p>
* Description: 是否特殊字符
* <p>
*/
public static boolean isSpecialChar(String txt) {
Pattern p = Pattern.compile("[0-9]*");
Matcher m = p.matcher(txt);
if (m.matches()) {
return true;
}
p = Pattern.compile("[a-zA-Z]");
m = p.matcher(txt);
if (m.matches()) {
return false;
}
p = Pattern.compile("[\u4e00-\u9fa5]");
m = p.matcher(txt);
if (m.matches()) {
return false;
}
return true;
}
/**
* 将字符串中的中文转化为拼音,其他字符不变
*
* @param inputString
* @return
*/
public static String getPingYin(String inputString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] input = inputString.trim().toCharArray();
String output = "";
try {
for (int i = 0; i < input.length; i++) {
if (java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
output += temp[0];
}
else
output += java.lang.Character.toString(input[i]);
}
}
catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return output;
}
/**
* 获取汉字串拼音首字母,英文字符不变
*
* @param chinese
* 汉字串
* @return 汉语拼音首字母
*/
public static String getFirstSpell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
if (temp != null) {
pybf.append(temp[0].charAt(0));
}
}
catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}
else {
pybf.append(arr[i]);
}
}
return pybf.toString().replaceAll("\\W", "").trim();
}
/**
* 获取汉字串拼音,英文字符不变
*
* @param chinese
* 汉字串
* @return 汉语拼音
*/
public static String getFullSpell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (java.lang.Character.toString(arr[i]).matches("[\\u4E00-\\u9FA5]+")) { //if (arr[i] > 128) {
try {
pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
}
catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}
else {
pybf.append(arr[i]);
}
}
return pybf.toString();
}
七、短信验证码获取
现在账号注册,密码修改离不开的
/**
* 获取验证码
*
* @param handler
* 回调
* @param phone
* 手机号码
*/
public void getverifyCode(final Handler handler, String phone) {
HttpUtils http = new HttpUtils();
RequestParams params = new RequestParams("UTF-8");// 添加提交参数
params.addHeader("Content-Type", "application/json");
StringEntity enti;
try {
JSONObject jsonObj = new JSONObject();
jsonObj.put(MSISDN, phone);
String str = jsonObj.toString();
enti = new StringEntity(str, "UTF-8");
params.setBodyEntity(enti);
http.send(HttpRequest.HttpMethod.POST, URL + GETVERIFYCODE, params,
new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
Log.i("getverifyCode", "回调成功");
Log.i("getverifyCode", responseInfo.toString());
Message msg = handler.obtainMessage();
msg.what = NETSUCCESS_VERFICATION;
msg.obj = responseInfo;
handler.sendMessage(msg);
}
@Override
public void onFailure(HttpException error, String msg) {
Log.i("getverifyCode", "回调失败");
Log.i("getverifyCode", error.toString());
Message msgFail = handler.obtainMessage();
msgFail.what = NETFAIL_VERFICATION;
msgFail.obj = error;
handler.sendMessage(msgFail);
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* 验证验证码
*
* @param handler
* 回调
* @param phone
* 手机号码
* @param verifyCode
* 验证码
*/
public void verifyVerifyCode(final Handler handler, String phone,
String verifyCode) {
HttpUtils http = new HttpUtils();
RequestParams params = new RequestParams("UTF-8");// 添加提交参数
params.addHeader("Content-Type", "application/json");
StringEntity enti;
try {
JSONObject jsonObj = new JSONObject();
jsonObj.put(MSISDN, phone);
jsonObj.put(VERIFYCODE, verifyCode);
String str = jsonObj.toString();
enti = new StringEntity(str, "UTF-8");
params.setBodyEntity(enti);
http.send(HttpRequest.HttpMethod.POST, URL + VERIFYVERIFYCODE,
params, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
Log.i("verifyVerifyCode", "回调成功");
Log.i("verifyVerifyCode", responseInfo.toString());
String str = responseInfo.result;
try {
JSONObject jsonObj = new JSONObject(str);
String result = jsonObj.getString(RESULT);
Log.i("result", result);
if (result.equals("200")) {
Message msg = handler.obtainMessage();
msg.what = NETSUCCESS;
msg.obj = responseInfo;
handler.sendMessage(msg);
} else {
Message msgFail = handler.obtainMessage();
msgFail.what = NETFAIL;
msgFail.obj = result;
handler.sendMessage(msgFail);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(HttpException error, String msg) {
Log.i("verifyVerifyCode", "回调失败");
Log.i("verifyVerifyCode", error.toString());
Message msgFail = handler.obtainMessage();
msgFail.what = NETFAIL;
msgFail.obj = error.toString();
handler.sendMessage(msgFail);
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* 创建一个用户或者更改密码
*
* @param handler
* @param phone
* @param verifyCode
*/
public void createMobileinfo(final Handler handler, String phone,
String password) {
HttpUtils http = new HttpUtils();
RequestParams params = new RequestParams("UTF-8");// 添加提交参数
params.addHeader("Content-Type", "application/json");
StringEntity enti;
try {
JSONObject jsonObj = new JSONObject();
jsonObj.put(MSISDN, phone);
jsonObj.put(PASSWORD, password);
String str = jsonObj.toString();
enti = new StringEntity(str, "UTF-8");
params.setBodyEntity(enti);
http.send(HttpRequest.HttpMethod.POST, URL + CREATEUSER, params,
new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
Log.i("verifyVerifyCode", "回调成功");
Log.i("verifyVerifyCode", responseInfo.toString());
String str = responseInfo.result;
JSONObject jsonObj;
try {
jsonObj = new JSONObject(str);
String result = jsonObj.getString(RESULT);
Log.i("result", result);
if (result.equals("200")) {
Message msg = handler.obtainMessage();
msg.what = NETSUCCESS;
msg.obj = responseInfo;
handler.sendMessage(msg);
} else {
Message msgFail = handler.obtainMessage();
msgFail.what = NETFAIL;
msgFail.obj = result;
handler.sendMessage(msgFail);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(HttpException error, String msg) {
Log.i("verifyVerifyCode", "回调失败");
Log.i("verifyVerifyCode", error.toString());
Message msgFail = handler.obtainMessage();
msgFail.what = NETFAIL;
msgFail.obj = error.toString();
handler.sendMessage(msgFail);
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}