本人只是简单列举几种常用工具类,如果各位看客有更好的,请留下你们的足迹共同分享,在此先谢谢了!
也可以参考如下博客:
https://github.com/Trinea/android-common/tree/master/src/cn/trinea/android/common/util
https://github.com/litesuits/android-common/tree/master/app/src/main/java/com/litesuits/common/utils
工具类有:AppUtil、BitmapUtil、DateUtil、JsonUtil、LogUtil、MeasureUtil、NetWorkUtil、PreferencesUtil、ReflectUtil、SDCardUtil、ScreenUtil、XmlUtil、ColorUtil、ExitActivityUtil、FileUtil、HttpUtil、PhoneUtil、ShortCutUtil、
AppUtil工具类:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.net.Uri;
/**
* 常用APP的工具类,包含版本号、版本名称、安装的应用程序ICON
*/
public class AppUtil {
private AppUtil(){}
/**
* 获取包名
* @param context
* @return
*/
public static String getPackageName(Context context){
return context.getPackageName();
}
/**
* 获取VersionName(版本名称)
* @param context
* @return
* 失败时返回""
*/
public static String getVersionName(Context context){
PackageManager packageManager = getPackageManager(context);
try {
PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(context), 0);
return packageInfo.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取VersionCode(版本号)
* @param context
* @return
* 失败时返回-1
*/
public static int getVersionCode(Context context){
PackageManager packageManager = getPackageManager(context);
try {
PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(context), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return -1;
}
/**
* 获取所有安装的应用程序,不包含系统应用
* @param context
* @return
*/
public static List<PackageInfo> getInstalledPackages(Context context){
PackageManager packageManager = getPackageManager(context);
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
List<PackageInfo> packageInfoList = new ArrayList<PackageInfo>();
for(int i=0; i < packageInfos.size();i++){
if ((packageInfos.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
packageInfoList.add(packageInfos.get(i));
}
}
return packageInfoList;
}
/**
* 获取应用程序的icon图标
* @param context
* @return
* 当包名错误时,返回null
*/
public static Drawable getApplicationIcon(Context context){
PackageManager packageManager = getPackageManager(context);
try {
PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(context), 0);
return packageInfo.applicationInfo.loadIcon(packageManager);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* 启动安装应用程序
* @param activity
* @param path 应用程序路径
*/
public static void installApk(Activity activity, String path){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(path)),
"application/vnd.android.package-archive");
activity.startActivity(intent);
}
/**
* 获取PackageManager对象
* @param context
* @return
*/
private static PackageManager getPackageManager(Context context){
return context.getPackageManager();
}
}
BitmapUtil工具类:
import java.io.ByteArrayOutputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.text.TextUtils;
/**
* Bitmap工具类,获取Bitmap对象
*/
public class BitmapUtil {
private BitmapUtil(){}
/**
* 根据资源id获取指定大小的Bitmap对象
* @param context 应用程序上下文
* @param id 资源id
* @param height 高度
* @param width 宽度
* @return
*/
public static Bitmap getBitmapFromResource(Context context, int id, int height, int width){
Options options = new Options();
options.inJustDecodeBounds = true;//只读取图片,不加载到内存中
BitmapFactory.decodeResource(context.getResources(), id, options);
options.inSampleSize = calculateSampleSize(height, width, options);
options.inJustDecodeBounds = false;//加载到内存中
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
return bitmap;
}
/**
* 根据文件路径获取指定大小的Bitmap对象
* @param path 文件路径
* @param height 高度
* @param width 宽度
* @return
*/
public static Bitmap getBitmapFromFile(String path, int height, int width){
if (TextUtils.isEmpty(path)) {
throw new IllegalArgumentException("参数为空,请检查你选择的路径:" + path);
}
Options options = new Options();
options.inJustDecodeBounds = true;//只读取图片,不加载到内存中
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateSampleSize(height, width, options);
options.inJustDecodeBounds = false;//加载到内存中
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
return bitmap;
}
/**
* 获取指定大小的Bitmap对象
* @param bitmap Bitmap对象
* @param height 高度
* @param width 宽度
* @return
*/
public static Bitmap getThumbnailsBitmap(Bitmap bitmap, int height, int width){
if (bitmap == null) {
throw new IllegalArgumentException("图片为空,请检查你的参数");
}
return ThumbnailUtils.extractThumbnail(bitmap, width, height);
}
/**
* 将Bitmap对象转换成Drawable对象
* @param context 应用程序上下文
* @param bitmap Bitmap对象
* @return 返回转换后的Drawable对象
*/
public static Drawable bitmapToDrawable(Context context, Bitmap bitmap){
if (context == null || bitmap == null) {
throw new IllegalArgumentException("参数不合法,请检查你的参数");
}
Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
return drawable;
}
/**
* 将Drawable对象转换成Bitmap对象
* @param drawable Drawable对象
* @return 返回转换后的Bitmap对象
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable == null) {
throw new IllegalArgumentException("Drawable为空,请检查你的参数");
}
Bitmap bitmap =
Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
/**
* 将Bitmap对象转换为byte[]数组
* @param bitmap Bitmap对象
* @return 返回转换后的数组
*/
public static byte[] bitmapToByte(Bitmap bitmap){
if (bitmap == null) {
throw new IllegalArgumentException("Bitmap为空,请检查你的参数");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/**
* 计算所需图片的缩放比例
* @param height 高度
* @param width 宽度
* @param options options选项
* @return
*/
private static int calculateSampleSize(int height, int width, Options options){
int realHeight = options.outHeight;
int realWidth = options.outWidth;
int heigthScale = realHeight / height;
int widthScale = realWidth / width;
if(widthScale > heigthScale){
return widthScale;
}else{
return heigthScale;
}
}
}
DateUtil工具类:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class DateUtil {
private DateUtil(){}
/**
* 枚举日期格式
*/
public enum DatePattern{
/**
* 格式:"yyyy-MM-dd HH:mm:ss"
*/
ALL_TIME{public String getValue(){return "yyyy-MM-dd HH:mm:ss";}},
/**
* 格式:"yyyy-MM"
*/
ONLY_MONTH{public String getValue(){return "yyyy-MM";}},
/**
* 格式:"yyyy-MM-dd"
*/
ONLY_DAY{public String getValue(){return "yyyy-MM-dd";}},
/**
* 格式:"yyyy-MM-dd HH"
*/
ONLY_HOUR{public String getValue(){return "yyyy-MM-dd HH";}},
/**
* 格式:"yyyy-MM-dd HH:mm"
*/
ONLY_MINUTE{public String getValue(){return "yyyy-MM-dd HH:mm";}},
/**
* 格式:"MM-dd"
*/
ONLY_MONTH_DAY{public String getValue(){return "MM-dd";}},
/**
* 格式:"MM-dd HH:mm"
*/
ONLY_MONTH_SEC{public String getValue(){return "MM-dd HH:mm";}},
/**
* 格式:"HH:mm:ss"
*/
ONLY_TIME{public String getValue(){return "HH:mm:ss";}},
/**
* 格式:"HH:mm"
*/
ONLY_HOUR_MINUTE{public String getValue(){return "HH:mm";}};
public abstract String getValue();
}
/**
* 获取当前时间
* @return 返回当前时间,格式2017-05-04 10:54:21
*/
public static String getNowDate(DatePattern pattern){
String dateString = null;
Calendar calendar = Calendar.getInstance();
Date dateNow = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(),Locale.CHINA);
dateString = sdf.format(dateNow);
return dateString;
}
/**
* 将一个日期字符串转换成Data对象
* @param dateString 日期字符串
* @param pattern 转换格式
* @return 返回转换后的日期对象
*/
public static Date stringToDate(String dateString, DatePattern pattern){
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(),Locale.CHINA);
try {
date = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 将date转换成字符串
* @param date 日期
* @param pattern 日期的目标格式
* @return
*/
public static String dateToString(Date date, DatePattern pattern){
String string = "";
SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(), Locale.CHINA);
string = sdf.format(date);
return string;
}
/**
* 获取指定日期周几
* @param date 指定日期
* @return
* 返回值为: "周日", "周一", "周二", "周三", "周四", "周五", "周六"
*/
public static String getWeekOfDate(Date date){
String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (week < 0)
week = 0;
return weekDays[week];
}
/**
* 获取指定日期对应周几的序列
* @param date 指定日期
* @return 周一:1 周二:2 周三:3 周四:4 周五:5 周六:6 周日:7
*/
public static int getIndexWeekOfDate(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int index = calendar.get(Calendar.DAY_OF_WEEK);
if(index == 1){
return 7;
}else{
return --index;
}
}
/**
* 返回当前月份
* @return
*/
public static int getNowMonth(){
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 获取当前月号
* @return
*/
public static int getNowDay(){
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.DATE);
}
/**
* 获取当前年份
* @return
*/
public static int getNowYear(){
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.YEAR);
}
/**
* 获取本月份的天数
* @return
*/
public static int getNowDaysOfMonth(){
Calendar calendar = Calendar.getInstance();
return daysOfMonth(calendar.get(Calendar.YEAR),calendar.get(Calendar.DATE) + 1);
}
/**
* 获取指定月份的天数
* @param year 年份
* @param month 月份
* @return 对应天数
*/
public static int daysOfMonth(int year,int month){
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if((year % 4 ==0 && year % 100 == 0) || year % 400 != 0){
return 29;
}else{
return 28;
}
default:
return -1;
}
}
}
JsonUtil工具类:
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentValues;
import com.google.gson.Gson;
/**
* 常用的Json工具类,包含Json转换成实体、实体转json字符串、list集合转换成json、数组转换成json
*/
public class JsonUtil {
private JsonUtil(){}
private static Gson gson = new Gson();
/**
* 将一个对象转换成一个Json字符串
* @param t
* @return
*/
public static <T> String objectToJson(T t){
if (t instanceof String) {
return t.toString();
} else {
return gson.toJson(t);
}
}
/**
* 将Json字符串转换成对应对象
* @param jsonString Json字符串
* @param clazz 对应字节码文件.class
* @return
*/
@SuppressWarnings("unchecked")
public static<T> T jsonToObject(String jsonString, Class<T> clazz){
if (clazz == String.class) {
return (T) jsonString;
} else {
return (T)gson.fromJson(jsonString, clazz);
}
}
/**
* 将List集合转换为json字符串
* @param list List集合
* @return
*/
public static<T> String listToJson(List<T> list){
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
try {
for (int i = 0; i < list.size(); i++) {
jsonObject = new JSONObject(objectToJson(list.get(i)));
jsonArray.put(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (jsonObject != null) {
jsonObject = null;
}
}
return jsonArray.toString();
}
/**
* 将数组转换成json字符串
* @param array 数组
* @return
*/
public static<T> String arrayToJson(T[] array){
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
try {
for (int i = 0; i < array.length; i++) {
jsonObject = new JSONObject(objectToJson(array[i]));
jsonArray.put(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (jsonObject != null) {
jsonObject = null;
}
}
return jsonArray.toString();
}
/**
* 获取json字符串中的值
* @param json json字符串
* @param key 键值
* @param clazz 所取数据类型,例如:Integer.class,String.class,Double.class,JSONObject.class
* @return 存在则返回正确值,不存在返回null
*/
public static<T> T getJsonObjectValue(String json, String key, Class<T> clazz){
try {
return getJsonObjectValue(new JSONObject(json), key, clazz);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取jsonObject对象中的值
* @param jsonObject jsonObject对象
* @param key 键值
* @param clazz 所取数据类型,例如:Integer.class,String.class,Double.class,JSONObject.class
* @return 存在则返回正确值,不存在返回null
*/
@SuppressWarnings("unchecked")
public static<T> T getJsonObjectValue(JSONObject jsonObject, String key, Class<T> clazz){
T t = null;
try {
if (clazz == Integer.class) {
t = (T) Integer.valueOf(jsonObject.getInt(key));
}else if(clazz == Boolean.class){
t = (T) Boolean.valueOf(jsonObject.getBoolean(key));
}else if(clazz == String.class){
t = (T) String.valueOf(jsonObject.getString(key));
}else if(clazz == Double.class){
t = (T) Double.valueOf(jsonObject.getDouble(key));
}else if(clazz == JSONObject.class){
t = (T) jsonObject.getJSONObject(key);
}else if(clazz == JSONArray.class){
t = (T) jsonObject.getJSONArray(key);
}else if(clazz == Long.class){
t = (T) Long.valueOf(jsonObject.getLong(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
return t;
}
/**
* json字符串转换为ContentValues
* @param json json字符串
* @return
*/
@SuppressWarnings("rawtypes")
public static ContentValues jsonToContentValues(String json){
ContentValues contentValues = new ContentValues();
try {
JSONObject jsonObject = new JSONObject(json);
Iterator iterator = jsonObject.keys();
String key;
Object value;
while (iterator.hasNext()) {
key = iterator.next().toString();
value = jsonObject.get(key);
String valueString = value.toString();
if (value instanceof String) {
contentValues.put(key, valueString);
}else if(value instanceof Integer){
contentValues.put(key, Integer.valueOf(valueString));
}else if(value instanceof Long){
contentValues.put(key, Long.valueOf(valueString));
}else if(value instanceof Double){
contentValues.put(key, Double.valueOf(valueString));
}else if(value instanceof Float){
contentValues.put(key, Float.valueOf(valueString));
}else if(value instanceof Boolean){
contentValues.put(key, Boolean.valueOf(valueString));
}
}
} catch (JSONException e) {
e.printStackTrace();
throw new Error("Json字符串不合法:" + json);
}
return contentValues;
}
}
LogUtil工具类:
import android.util.Log;
/**
* Log日志工具类
*/
public class LogUtil {
private LogUtil(){}
/**
* 打印information日志
* @param tag 标签
* @param msg 日志信息
*/
public static void i(String tag,String msg){
Log.i(tag, msg);
}
/**
* 打印information日志
* @param tag 标签
* @param msg 日志信息
* @param throwable 异常
*/
public static void i(String tag, String msg, Throwable throwable){
Log.i(tag,msg,throwable);
}
/**
* 打印verbose日志
* @param tag 标签
* @param msg 日志信息
*/
public static void v(String tag, String msg){
Log.v(tag, msg);
}
/**
* 打印verbose日志
* @param tag 标签
* @param msg 日志信息
* @param throwable 异常
*/
public static void v(String tag, String msg, Throwable throwable){
Log.v(tag, msg, throwable);
}
/**
* 打印debug信息
* @param tag 标签信息
* @param msg 日志信息
*/
public static void d(String tag, String msg){
Log.d(tag, msg);
}
/**
* 打印debug日志
* @param tag 标签信息
* @param msg 日志信息
* @param throwable 异常
*/
public static void d(String tag, String msg, Throwable throwable){
Log.d(tag, msg, throwable);
}
/**
* 打印warn日志
* @param tag 标签信息
* @param msg 日志信息
*/
public static void w(String tag, String msg){
Log.w(tag, msg);
}
/**
* 打印warn日志
* @param tag 标签信息
* @param msg 日志信息
* @param throwable 异常
*/
public static void w(String tag, String msg, Throwable throwable){
Log.w(tag, msg, throwable);
}
/**
* 打印error日志
* @param tag 标签
* @param msg 日志信息
*/
public static void e(String tag, String msg){
Log.e(tag, msg);
}
/**
* 打印error日志
* @param tag 标签
* @param msg 日志信息
* @param throwable 异常
*/
public static void e(String tag, String msg, Throwable throwable){
Log.e(tag, msg, throwable);
}
}
MeasureUtil工具类:
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.GridView;
import android.widget.ListView;
/**
* 常用的测量功能
*/
public class MeasureUtil {
private MeasureUtil(){}
/**
* 获取控件的测量高度
* @param view 控件
* @return 返回测量高度(MeasuredHeight)
*/
public static int getMeasuredHeight(View view) {
if (view == null) {
throw new IllegalArgumentException("view is null");
}
view.measure(0, 0);
return view.getMeasuredHeight();
}
/**
* 控件的高度
* @param view 控件View
* @return 返回控件的高度
*/
public static int getHeight(View view){
if(view == null){
throw new IllegalArgumentException("view is null");
}
view.measure(0, 0);
return view.getHeight();
}
/**
* 获取控件的测量宽度
* @param view 控件
* @return 返回控件的测量宽度
*/
public static int getMeasuredWidth(View view){
if(view == null){
throw new IllegalArgumentException("view is null");
}
view.measure(0, 0);
return view.getMeasuredWidth();
}
/**
* 获取控件的宽度
* @param view 控件
* @return 返回控件的宽度
*/
public static int getWidth(View view){
if(view == null){
throw new IllegalArgumentException("view is null");
}
view.measure(0, 0);
return view.getWidth();
}
/**
* 设置高度
* @param view 控件
* @param height 高度
*/
public static void setHeight(View view, int height) {
if (view == null || view.getLayoutParams() == null) {
throw new IllegalArgumentException("View LayoutParams is null");
}
ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = height;
view.setLayoutParams(params);
}
/**
* 设置View的宽度
* @param view view
* @param width 宽度
*/
public static void setWidth(View view, int width){
if(view == null || view.getLayoutParams() == null){
throw new IllegalArgumentException("View LayoutParams is null");
}
ViewGroup.LayoutParams params = view.getLayoutParams();
params.width = width;
view.setLayoutParams(params);
}
/**
* 设置ListView的实际高度
* @param listView ListView控件
*/
public static void setListHeight(ListView listView) {
if (listView == null) {
throw new IllegalArgumentException("ListView is null");
}
Adapter adapter = listView.getAdapter();
if (adapter == null) {
return;
}
int totalHeight = 0;
int size = adapter.getCount();
for (int i = 0; i < size; i++) {
View listItem = adapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (size - 1));
LogUtil.d("MeasureUtil", "listview-height--" + params.height);
listView.setLayoutParams(params);
}
/**
* 设置GridView的高度,
* @param context 应用程序上下文
* @param gv GridView控件
* @param n 行数
* @param m 列数
*/
public static void setGridViewHeight(Context context, GridView gv, int n, int m) {
if(gv == null){
throw new IllegalArgumentException("GridView is null");
}
Adapter adapter = gv.getAdapter();
if (adapter == null) {
return;
}
int totalHeight = 0;
int size = adapter.getCount();
for (int i = 0; i < size; i++) {
View listItem = adapter.getView(i, null, gv);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight() + ScreenUtil.dp2px(context, m);
}
ViewGroup.LayoutParams params = gv.getLayoutParams();
params.height = totalHeight + gv.getPaddingTop() + gv.getPaddingBottom() + 2;
LogUtil.d("MeasureUtil", "gridview-height--" + params.height);
gv.setLayoutParams(params);
}
}
NetWorkUtil工具类:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
/**
* 网络工具类,包含网络的判断、跳转到设置页面
*/
public class NetWorkUtil {
/**
* 判断当前是否有网络连接
* @param context
* @return 有网络返回true;无网络返回false
*/
@SuppressWarnings("null")
public static boolean isNetWorkEnable(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null || networkInfo.isConnected()) {
if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
/**
* 判断当前网络是否为wifi
* @param context
* @return 如果为wifi返回true;否则返回false
*/
@SuppressWarnings("static-access")
public static boolean isWiFiConnected(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo.getType() == manager.TYPE_WIFI ? true : false;
}
/**
* 判断MOBILE网络是否可用
* @param context
* @return
* @throws Exception
*/
public static boolean isMobileDataEnable(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isMobileDataEnable = false;
isMobileDataEnable = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
return isMobileDataEnable;
}
/**
* 判断wifi 是否可用
* @param context
* @return
* @throws Exception
*/
public static boolean isWifiDataEnable(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isWifiDataEnable = false;
isWifiDataEnable = manager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
return isWifiDataEnable;
}
/**
* 跳转到网络设置页面
* @param activity
*/
public static void GoSetting(Activity activity){
Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
activity.startActivity(intent);
}
/**
* 打开网络设置界面
*/
public static void openSetting(Activity activity) {
Intent intent = new Intent("/");
ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(cn);
intent.setAction("android.intent.action.VIEW");
activity.startActivityForResult(intent, 0);
}
}
PreferencesUtil工具类:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* SharedPreferences工具类,包含常用的数值获取和存储
*/
public class PreferencesUtil {
private PreferencesUtil(){}
/**
* 默认的SharePreference名称
*/
private static final String SHARED_NAME = "SharedPreferences";
/**
* 查询某个key是否已经存在
* @param context 应用程序上下文
* @param key key关键字
* @return 包含返回true;反之返回false
*/
public static boolean containsKey(Context context, String key){
SharedPreferences sp = getSharedPreferences(context);
return sp.contains(key);
}
/**
* 返回所有的键值对
* @param context 应用程序上下文
* @return
*/
public static Map<String, ?> getAll(Context context) {
SharedPreferences sp = getSharedPreferences(context);
return sp.getAll();
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
* @param context 应用程序上下文
* @param key key关键字
* @param defValue 默认值
* @return 返回获取的String值
*/
public static Object get(Context context, String key, Object defaultObject){
SharedPreferences sp = getSharedPreferences(context);
if (defaultObject instanceof String) {
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
/**
* 获取Set<String> 集合
* @param context 应用程序上下文
* @param key key关键字
* @param defValues 默认值
* @return 返回Set<String>值
*/
public static Set<String> getStringSet(Context context, String key, Set<String> defValues){
SharedPreferences sp = getSharedPreferences(context);
return sp.getStringSet(key, defValues);
}
/**
* 保存Set<String>集合的值
* @param context 应用程序上下文
* @param key key关键字
* @param value 对应值
* @return 成功返回true,失败返回false
*/
public static boolean putStringSet(Context context, String key, Set<String> value){
return getEditor(context).putStringSet(key, value).commit();
}
/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
* @param context 应用程序上下文
* @param key key关键字
* @param object 对应值
* @return 成功返回true,失败返回false
*/
public static void put(Context context, String key, Object object){
if (object instanceof String) {
getEditor(context).putString(key, (String) object);
} else if (object instanceof Integer) {
getEditor(context).putInt(key, (Integer) object);
} else if (object instanceof Boolean) {
getEditor(context).putBoolean(key, (Boolean) object);
} else if (object instanceof Float) {
getEditor(context).putFloat(key, (Float) object);
} else if (object instanceof Long) {
getEditor(context).putLong(key, (Long) object);
} else {
getEditor(context).putString(key, object.toString());
}
SharedPreferencesCompat.apply(getEditor(context));
}
/**
* 删除关键字key对应的值
* @param context 应用程序上下文
* @param key 关键字key
*/
public static void removeKey(Context context, String key){
getEditor(context).remove(key);
SharedPreferencesCompat.apply(getEditor(context));
}
/**
* 清除所有的关键字对应的值
* @param context 应用程序上下文
*/
public static void clearValues(Context context){
getEditor(context).clear();
SharedPreferencesCompat.apply(getEditor(context));
}
/**
* 获取SharedPreferences对象
* @param context 应用程序上下文
* @return 返回SharedPreferences对象
*/
private static SharedPreferences getSharedPreferences(Context context){
return context.getSharedPreferences(SHARED_NAME, Context.MODE_PRIVATE);
}
/**
* 获取Editor对象
* @param context 应用程序上下文
* @return 返回Editor对象
*/
private static Editor getEditor(Context context){
return getSharedPreferences(context).edit();
}
/**
* 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
*/
private static class SharedPreferencesCompat {
private static final Method sApplyMethod = findApplyMethod();
/**
* 反射查找apply的方法
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Method findApplyMethod() {
try {
Class clz = SharedPreferences.Editor.class;
return clz.getMethod("apply");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
/**
* 如果找到则使用apply执行,否则使用commit
* @param editor
*/
public static void apply(SharedPreferences.Editor editor) {
try {
if (sApplyMethod != null) {
sApplyMethod.invoke(editor);
return;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
editor.commit();
}
}
}
ReflectUtil工具类:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import android.text.TextUtils;
/**
* 反射工具类
*/
public class ReflectUtil {
private ReflectUtil(){}
/**
* 设置字段值
* @param t 对应实体
* @param field 字段
* @param fieldName 字段名称
* @param value 字段值
*/
public static<T> void setFieldValue(T t,Field field, String fieldName, String value){
String name = field.getName();
//判断该字段是否和目标字段相同
if (!fieldName.equals(name)) {
return;
}
//获取字段的类型
Type type = field.getType();
//获取字段的修饰符号码
int typeCode = field.getModifiers();
//获取字段类型的名称
String typeName = type.toString();
try {
switch (typeName) {
case "class java.lang.String":
if (Modifier.isPublic(typeCode)) {
field.set(t, value);
} else {
Method method = t.getClass().getMethod("set" + getMethodName(fieldName), String.class);
method.invoke(t, value);
}
break;
case "double":
if(Modifier.isPublic(typeCode)){
field.setDouble(t, Double.valueOf(value));
}else{
Method method = t.getClass().getMethod("set" + getMethodName(fieldName),double.class);
method.invoke(t, Double.valueOf(value));
}
break;
case "int":
if(Modifier.isPublic(typeCode)){
field.setInt(t, Integer.valueOf(value));
}else{
Method method = t.getClass().getMethod("set" + getMethodName(fieldName),int.class);
method.invoke(t, Integer.valueOf(value));
}
break;
case "float":
if(Modifier.isPublic(typeCode)){
field.setFloat(t, Float.valueOf(value));
}else{
Method method = t.getClass().getMethod("set" + getMethodName(fieldName), float.class);
method.invoke(t, Float.valueOf(value));
}
break;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 把字段名称第一个字母换成大写
* @param fieldName 字段名称
* @return
* @throws Exception 异常处理
*/
private static String getMethodName(String fieldName) throws Exception{
byte[] items = fieldName.getBytes();
items[0] = (byte) ((char)items[0] - 'a' + 'A');
return new String(items);
}
/**
* 根据字段名称获取指定Field字段
* @param clazz 实体的字节码文件
* @param filedName 字段的名称
* @return 返回对应的字符按Field或者返回null
*/
public static Field getField(Class<?> clazz, String filedName){
if (clazz == null || TextUtils.isEmpty(filedName)) {
throw new IllegalArgumentException("params is illegal");
}
Field[] fields = clazz.getDeclaredFields();
return getFieldByName(fields, filedName);
}
/**
* 根据字段名称获取指定的Field
* @param fields 字段集合
* @param fieldName 字段名称
* @return 返回对应的Field字段或者返回null
*/
public static Field getFieldByName(Field[] fields, String fieldName){
if (fields == null || fields.length == 0 || TextUtils.isEmpty(fieldName)) {
throw new IllegalArgumentException("params is illegal");
}
for (Field field : fields) {
String name = field.getName();
//判断该字段是否和目标字段相同
if (fieldName.equals(name)) {
return field;
}
}
return null;
}
/**
* 判断该字段是否为FieldName对应字段
* @param field Field字段
* @param fieldName 目标字段
* @return 是,返回true;否,返回false
*/
public static boolean isFiledWithName(Field field, String fieldName){
if(field == null || TextUtils.isEmpty(fieldName)){
throw new IllegalArgumentException("params is illegal");
}
if (fieldName.equals(field.getName())) {
return true;
}
return false;
}
}
SDCardUtil工具类:
import java.io.File;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
/**
* SD卡工具类,包含SD卡状态、路径、容量大小
*/
public class SDCardUtil {
private SDCardUtil(){}
/**
* 判断SD卡是否可用
* @return
* ture:可用;false:不可用
*/
public static boolean isSDCardEnable(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/**
* 获取SD卡路径
* @return
* SD卡存在返回正常路径;SD卡不存在返回""
*/
public static String getSDCradPath(){
if (isSDCardEnable()) {
return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
} else {
return "";
}
}
/**
* 获取SD卡路径文件
* @return
* SD卡存在返回正常路径;SD卡不存在返回null
*/
public static File getSDCardFile(){
if(isSDCardEnable()){
return Environment.getExternalStorageDirectory();
}else{
return null;
}
}
/**
* 获取SD卡DownloadCache路径
* @return
* SD卡存在返回正常路径;SD卡不存在返回""
*/
public static String getSDCardDownloadCachePath(){
if(isSDCardEnable()){
return Environment.getDownloadCacheDirectory().getAbsolutePath() + File.separator;
}else{
return "";
}
}
/**
* 获取SD卡DownloadCache路径文件
* @return
* SD卡存在返回正常路径;SD卡不存在返回null
*/
public static File getSDCardDownloadCacheFile(){
if(isSDCardEnable()){
return Environment.getDownloadCacheDirectory();
}else{
return null;
}
}
/**
* 获取系统存储路径
* @return
* SD卡存在返回正常路径;SD卡不存在返回""
*/
public static String getSDCardRootPath(){
if(isSDCardEnable()){
return Environment.getRootDirectory().getAbsolutePath() + File.separator;
}else{
return "";
}
}
/**
* 获取系统存储路径文件
* @return
* SD卡存在返回正常路径;SD卡不存在返回null
*/
public static File getSDCardRootFile(){
if(isSDCardEnable()){
return Environment.getRootDirectory();
}else{
return null;
}
}
/**
* 获取应用程序的/data/data目录
* @param context
* @return
*/
public static String getDataFilePath(Context context){
return context.getFilesDir().getAbsolutePath() + File.separator;
}
/**
* /data/data/PackageName/cache的路径
* @param context
* @return
*/
public static String getDataCachePath(Context context){
return context.getCacheDir().getAbsolutePath() + File.separator;
}
/**
* 获取SD卡大小
* @return
* SD卡存在返回大小;SD卡不存在返回-1
*/
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static long getSDCardSize(){
if (isSDCardEnable()) {
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
if (android.os.Build.VERSION.SDK_INT < 18) {
int blockSize = statFs.getBlockSize();
int blockCount = statFs.getBlockCount();
return blockSize * blockCount;
} else {
long blockSize = statFs.getBlockSizeLong();
long blockCount = statFs.getBlockCountLong();
return blockSize * blockCount;
}
}
return -1;
}
/**
* 获取SD卡可用大小
* @return
* SD卡存在返回大小;SD卡不存在返回-1
*/
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static long getSDCardAvailableSize(){
if (isSDCardEnable()) {
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
if (android.os.Build.VERSION.SDK_INT < 18) {
int blockSize = statFs.getBlockSize();
int blockCount = statFs.getAvailableBlocks();
return blockSize * blockCount;
} else {
long blockSize = statFs.getBlockSizeLong();
long blockCount = statFs.getAvailableBlocksLong();
return blockSize * blockCount;
}
}
return -1;
}
/**
* 获得手机内存总大小
* @return
*/
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public long getRomTotalSize() {
File path = Environment.getDataDirectory();
StatFs statFs = new StatFs(path.getPath());
if (android.os.Build.VERSION.SDK_INT < 18) {
int blockSize = statFs.getBlockSize();
int blockCount = statFs.getBlockCount();
return blockSize * blockCount;
} else {
long blockSize = statFs.getBlockSizeLong();
long blockCount = statFs.getBlockCountLong();
return blockSize * blockCount;
}
}
/**
* 获得手机可用内存
* @return
*/
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public long getRomAvailableSize() {
File path = Environment.getDataDirectory();
StatFs statFs = new StatFs(path.getPath());
if (android.os.Build.VERSION.SDK_INT < 18) {
int blockSize = statFs.getBlockSize();
int blockCount = statFs.getAvailableBlocks();
return blockSize * blockCount;
} else {
long blockSize = statFs.getBlockSizeLong();
long blockCount = statFs.getAvailableBlocksLong();
return blockSize * blockCount;
}
}
}
ScreenUtil工具类:
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
/**
* 屏幕工具类,涉及到屏幕宽度、高度、密度比、(像素、dp、sp)之间的转换等。
*/
public class ScreenUtil {
private ScreenUtil(){}
/**
* 获取屏幕宽度,单位为px
* @param context 应用程序上下文
* @return 屏幕宽度,单位px
*/
public static int getScreenWidth(Context context){
return getDisplayMetrics(context).widthPixels;
}
/**
* 获取屏幕高度,单位为px
* @param context 应用程序上下文
* @return 屏幕高度,单位px
*/
public static int getScreenHeight(Context context){
return getDisplayMetrics(context).heightPixels;
}
/**
* 获取系统dp尺寸密度值
* @param context 应用程序上下文
* @return
*/
public static float getDensity(Context context){
return getDisplayMetrics(context).density;
}
/**
* 获取系统字体sp密度值
* @param context 应用程序上下文
* @return
*/
public static float getScaledDensity(Context context){
return getDisplayMetrics(context).scaledDensity;
}
/**
* dip转换为px大小
* @param context 应用程序上下文
* @param dpValue dp值
* @return 转换后的px值
*/
public static int dp2px(Context context, int dpValue){
return (int) (dpValue * getDensity(context) + 0.5f);
}
/**
* px转换为dp值
* @param context 应用程序上下文
* @param pxValue px值
* @return 转换后的dp值
*/
public static int px2dp(Context context, int pxValue){
return (int) (pxValue / getDensity(context) + 0.5f);
}
/**
* sp转换为px
* @param context 应用程序上下文
* @param spValue sp值
* @return 转换后的px值
*/
public static int sp2px(Context context, int spValue){
return (int) (spValue * getScaledDensity(context) + 0.5f);
}
/**
* px转换为sp
* @param context 应用程序上下文
* @param pxValue px值
* @return 转换后的sp值
*/
public static int px2sp(Context context, int pxValue){
return (int) (pxValue / getScaledDensity(context) + 0.5f);
}
/**
* 获得状态栏的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context){
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 获取当前屏幕截图,包含状态栏
* @param activity
* @return
*/
public static Bitmap snapShotWithStatusBar(Activity activity){
View decorView = activity.getWindow().getDecorView();
decorView.setDrawingCacheEnabled(true);
decorView.buildDrawingCache();
Bitmap bmp = decorView.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bitmap = null;
bitmap = Bitmap.createBitmap(bmp, 0, 0, width, height);
decorView.destroyDrawingCache();
return bitmap;
}
/**
* 获取当前屏幕截图,不包含状态栏
* @param activity
* @return
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity){
View decorView = activity.getWindow().getDecorView();
decorView.setDrawingCacheEnabled(true);
decorView.buildDrawingCache();
Bitmap bmp = decorView.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusHeight = frame.top;
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bitmap = null;
bitmap = Bitmap.createBitmap(bmp, 0, statusHeight, width, height - statusHeight);
decorView.destroyDrawingCache();
return bitmap;
}
/**
* 获取DisplayMetrics对象
* @param context 应用程序上下文
* @return
*/
public static DisplayMetrics getDisplayMetrics(Context context){
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
return metrics;
}
}
XmlUtil工具类:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.text.TextUtils;
import android.util.Xml;
/**
* XML文件工具类,包含:将xml文件解析成实体集合、获取xml标签值、将标签值解析成实体集合
*/
public class XMLUtil {
private XMLUtil(){}
/*-
* XML文件解析成实体,不涉及到标签的属性值。
* @param xml xml字符串文件
* @param clazz 对应实体的class文件
* @param tagEntity
* 开始解析实体的标签,例如下面的实例中就是student<br>
* < person ><br>
* < student ><br>
* < name >Lucy< /name ><br>
* < age >21< /age ><br>
* < /student ><br>
* < /person ><br>
* @return 返回解析的对应实体文件
*/
public static<T> List<T> xmlToObject(String xml, Class<T> clazz, String tagEntity){
List<T> list = null;
XmlPullParser xmlPullParser = Xml.newPullParser();
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
try {
xmlPullParser.setInput(inputStream, "utf-8");
Field[] fields = clazz.getDeclaredFields();
int type = xmlPullParser.getEventType();
String lastTag = "";
T t = null;
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<T>();
break;
case XmlPullParser.START_TAG:
String tagName = xmlPullParser.getName();
if(tagEntity.equals(tagName)){
t = clazz.newInstance();
lastTag = tagEntity;
}else if(tagEntity.equals(lastTag)){
String textValue = xmlPullParser.nextText();
String fieldName = xmlPullParser.getName();
for(Field field : fields){
ReflectUtil.setFieldValue(t,field,fieldName,textValue);
}
}
break;
case XmlPullParser.END_TAG:
tagName = xmlPullParser.getName();
if(tagEntity.equals(tagName)){
list.add(t);
lastTag = "";
}
break;
case XmlPullParser.END_DOCUMENT:
break;
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 获取xml字符串标签中的属性值
* @param xml xml字符串
* @param clazz 转换成对应的实体
* @param tagName 实体对应xml字符串的起始标签,如下面实例中的person标签<br>
* < person name="Lucy" age="12"><br>
* < student ><br>
* < name >Lucy< /name ><br>
* < age >21< /age ><br>
* < /student ><br>
* < /person ><br>
* @return 返回属性值组成的List对象集合。
*/
public static<T> List<T> attributeToObject(String xml, Class<T> clazz, String tagName){
if(TextUtils.isEmpty(tagName))return null;
List<T> list = null;
XmlPullParser xmlPullParser = Xml.newPullParser();
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
try {
xmlPullParser.setInput(inputStream, "utf-8");
int type = xmlPullParser.getEventType();
T t = null;
while(type != XmlPullParser.END_DOCUMENT){
switch(type){
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<T>();
break;
case XmlPullParser.START_TAG:
if(tagName.equals(xmlPullParser.getName())){
t = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for(Field field : fields){
String fieldName = field.getName();
for(int index = 0;index < xmlPullParser.getAttributeCount();index++){
if(fieldName.equals(xmlPullParser.getAttributeName(index))){
ReflectUtil.setFieldValue(t,field,fieldName,xmlPullParser.getAttributeValue(index));
}
}
}
}
break;
case XmlPullParser.END_TAG:
if(tagName.equals(xmlPullParser.getName())){
list.add(t);
}
break;
case XmlPullParser.END_DOCUMENT:
break;
}
type = xmlPullParser.next();
}
}catch(Exception ex){
ex.printStackTrace();
}
return list;
}
/**
* 获取Xml文件中的属性值
* @param xml xml文件字符串
* @param tagName 标签名称
* @param attributeName 属性名称
* @return 返回获取的值,或者null
*/
public static String getTagAttribute(String xml, String tagName, String attributeName){
if(TextUtils.isEmpty(tagName) || TextUtils.isEmpty(attributeName)){
throw new IllegalArgumentException("请填写标签名称或属性名称");
}
XmlPullParser xmlPullParser = Xml.newPullParser();
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
try {
xmlPullParser.setInput(inputStream, "utf-8");
int type = xmlPullParser.getEventType();
while(type != XmlPullParser.END_DOCUMENT){
switch(type){
case XmlPullParser.START_TAG:
if(tagName.equals(xmlPullParser.getName())){
for(int i=0; i < xmlPullParser.getAttributeCount();i++){
if(attributeName.equals(xmlPullParser.getAttributeName(i))){
return xmlPullParser.getAttributeValue(i);
}
}
}
break;
}
type = xmlPullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
ColorUtil工具类:
public class ColorsUtil {
private ColorsUtil() {
throw new Error("Do not need instantiate!");
}
/**
* 白色
*/
public static final int WHITE = 0xffffffff;
/**
* 白色 - 半透明
*/
public static final int WHITE_TRANSLUCENT = 0x80ffffff;
/**
* 黑色
*/
public static final int BLACK = 0xff000000;
/**
* 黑色 - 半透明
*/
public static final int BLACK_TRANSLUCENT = 0x80000000;
/**
* 透明
*/
public static final int TRANSPARENT = 0x00000000;
/**
* 红色
*/
public static final int RED = 0xffff0000;
/**
* 红色 - 半透明
*/
public static final int RED_TRANSLUCENT = 0x80ff0000;
/**
* 红色 - 深的
*/
public static final int RED_DARK = 0xff8b0000;
/**
* 红色 - 深的 - 半透明
*/
public static final int RED_DARK_TRANSLUCENT = 0x808b0000;
/**
* 绿色
*/
public static final int GREEN = 0xff00ff00;
/**
* 绿色 - 半透明
*/
public static final int GREEN_TRANSLUCENT = 0x8000ff00;
/**
* 绿色 - 深的
*/
public static final int GREEN_DARK = 0xff003300;
/**
* 绿色 - 深的 - 半透明
*/
public static final int GREEN_DARK_TRANSLUCENT = 0x80003300;
/**
* 绿色 - 浅的
*/
public static final int GREEN_LIGHT = 0xffccffcc;
/**
* 绿色 - 浅的 - 半透明
*/
public static final int GREEN_LIGHT_TRANSLUCENT = 0x80ccffcc;
/**
* 蓝色
*/
public static final int BLUE = 0xff0000ff;
/**
* 蓝色 - 半透明
*/
public static final int BLUE_TRANSLUCENT = 0x800000ff;
/**
* 蓝色 - 深的
*/
public static final int BLUE_DARK = 0xff00008b;
/**
* 蓝色 - 深的 - 半透明
*/
public static final int BLUE_DARK_TRANSLUCENT = 0x8000008b;
/**
* 蓝色 - 浅的
*/
public static final int BLUE_LIGHT = 0xff36a5E3;
/**
* 蓝色 - 浅的 - 半透明
*/
public static final int BLUE_LIGHT_TRANSLUCENT = 0x8036a5E3;
/**
* 天蓝
*/
public static final int SKYBLUE = 0xff87ceeb;
/**
* 天蓝 - 半透明
*/
public static final int SKYBLUE_TRANSLUCENT = 0x8087ceeb;
/**
* 天蓝 - 深的
*/
public static final int SKYBLUE_DARK = 0xff00bfff;
/**
* 天蓝 - 深的 - 半透明
*/
public static final int SKYBLUE_DARK_TRANSLUCENT = 0x8000bfff;
/**
* 天蓝 - 浅的
*/
public static final int SKYBLUE_LIGHT = 0xff87cefa;
/**
* 天蓝 - 浅的 - 半透明
*/
public static final int SKYBLUE_LIGHT_TRANSLUCENT = 0x8087cefa;
/**
* 灰色
*/
public static final int GRAY = 0xff969696;
/**
* 灰色 - 半透明
*/
public static final int GRAY_TRANSLUCENT = 0x80969696;
/**
* 灰色 - 深的
*/
public static final int GRAY_DARK = 0xffa9a9a9;
/**
* 灰色 - 深的 - 半透明
*/
public static final int GRAY_DARK_TRANSLUCENT = 0x80a9a9a9;
/**
* 灰色 - 暗的
*/
public static final int GRAY_DIM = 0xff696969;
/**
* 灰色 - 暗的 - 半透明
*/
public static final int GRAY_DIM_TRANSLUCENT = 0x80696969;
/**
* 灰色 - 浅的
*/
public static final int GRAY_LIGHT = 0xffd3d3d3;
/**
* 灰色 - 浅的 - 半透明
*/
public static final int GRAY_LIGHT_TRANSLUCENT = 0x80d3d3d3;
/**
* 橙色
*/
public static final int ORANGE = 0xffffa500;
/**
* 橙色 - 半透明
*/
public static final int ORANGE_TRANSLUCENT = 0x80ffa500;
/**
* 橙色 - 深的
*/
public static final int ORANGE_DARK = 0xffff8800;
/**
* 橙色 - 深的 - 半透明
*/
public static final int ORANGE_DARK_TRANSLUCENT = 0x80ff8800;
/**
* 橙色 - 浅的
*/
public static final int ORANGE_LIGHT = 0xffffbb33;
/**
* 橙色 - 浅的 - 半透明
*/
public static final int ORANGE_LIGHT_TRANSLUCENT = 0x80ffbb33;
/**
* 金色
*/
public static final int GOLD = 0xffffd700;
/**
* 金色 - 半透明
*/
public static final int GOLD_TRANSLUCENT = 0x80ffd700;
/**
* 粉色
*/
public static final int PINK = 0xffffc0cb;
/**
* 粉色 - 半透明
*/
public static final int PINK_TRANSLUCENT = 0x80ffc0cb;
/**
* 紫红色
*/
public static final int FUCHSIA = 0xffff00ff;
/**
* 紫红色 - 半透明
*/
public static final int FUCHSIA_TRANSLUCENT = 0x80ff00ff;
/**
* 灰白色
*/
public static final int GRAYWHITE = 0xfff2f2f2;
/**
* 灰白色 - 半透明
*/
public static final int GRAYWHITE_TRANSLUCENT = 0x80f2f2f2;
/**
* 紫色
*/
public static final int PURPLE = 0xff800080;
/**
* 紫色 - 半透明
*/
public static final int PURPLE_TRANSLUCENT = 0x80800080;
/**
* 青色
*/
public static final int CYAN = 0xff00ffff;
/**
* 青色 - 半透明
*/
public static final int CYAN_TRANSLUCENT = 0x8000ffff;
/**
* 青色 - 深的
*/
public static final int CYAN_DARK = 0xff008b8b;
/**
* 青色 - 深的 - 半透明
*/
public static final int CYAN_DARK_TRANSLUCENT = 0x80008b8b;
/**
* 黄色
*/
public static final int YELLOW = 0xffffff00;
/**
* 黄色 - 半透明
*/
public static final int YELLOW_TRANSLUCENT = 0x80ffff00;
/**
* 黄色 - 浅的
*/
public static final int YELLOW_LIGHT = 0xffffffe0;
/**
* 黄色 - 浅的 - 半透明
*/
public static final int YELLOW_LIGHT_TRANSLUCENT = 0x80ffffe0;
/**
* 巧克力色
*/
public static final int CHOCOLATE = 0xffd2691e;
/**
* 巧克力色 - 半透明
*/
public static final int CHOCOLATE_TRANSLUCENT = 0x80d2691e;
/**
* 番茄色
*/
public static final int TOMATO = 0xffff6347;
/**
* 番茄色 - 半透明
*/
public static final int TOMATO_TRANSLUCENT = 0x80ff6347;
/**
* 橙红色
*/
public static final int ORANGERED = 0xffff4500;
/**
* 橙红色 - 半透明
*/
public static final int ORANGERED_TRANSLUCENT = 0x80ff4500;
/**
* 银白色
*/
public static final int SILVER = 0xffc0c0c0;
/**
* 银白色 - 半透明
*/
public static final int SILVER_TRANSLUCENT = 0x80c0c0c0;
/**
* 高光
*/
public static final int HIGHLIGHT = 0x33ffffff;
/**
* 低光
*/
public static final int LOWLIGHT = 0x33000000;
}
ExitActivityUtil工具类:
import android.app.Activity;
import android.view.KeyEvent;
import android.widget.Toast;
public class ExitActivityUtil extends Activity{
private long exitTime = 0;
/*
* 重写onKeyDown方法
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//2s之内按返回键就会推出
if((System.currentTimeMillis() - exitTime) > 2000){
Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
}
FileUtil工具类:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 文件操作工具类
*/
public class FileUtil {
/**
* 在指定的位置创建指定的文件
* @param filePath 完整的文件路径
* @param mkdir 是否创建相关的文件夹
* @throws IOException
*/
public static void mkFile(String filePath, boolean mkdir) throws IOException{
File file = new File(filePath);
/**
* mkdirs()创建多层目录,mkdir()创建单层目录
* writeObject时才创建磁盘文件。
* 若不创建文件,readObject出错。
*/
file.getParentFile().mkdirs();
file.createNewFile();
file = null;
}
/**
* 在指定的位置创建文件夹
* @param dirPath 文件夹路径
* @return 若创建成功,则返回True;反之,则返回False
*/
public static boolean mkDir(String dirPath) {
return new File(dirPath).mkdirs();
}
/**
* 删除指定的文件
* @param filePath 文件路径
* @return 若删除成功,则返回True;反之,则返回False
*/
public static boolean delFile(String filePath) {
return new File(filePath).delete();
}
/**
* 删除指定的文件夹
* @param dirPath 文件夹路径
* @param delFile 文件夹中是否包含文件
* @return 若删除成功,则返回True;反之,则返回False
*/
public static boolean delDir(String dirPath, boolean delFile) {
if (delFile) {
File file = new File(dirPath);
if (file.isFile()) {
return file.delete();
} else if (file.isDirectory()) {
if (file.listFiles().length == 0) {
return file.delete();
} else {
int zFiles = file.listFiles().length;
File[] delfile = file.listFiles();
for (int i = 0; i < zFiles; i++) {
if (delfile[i].isDirectory()) {
delDir(delfile[i].getAbsolutePath(), true);
}
delfile[i].delete();
}
return file.delete();
}
} else {
return false;
}
} else {
return new File(dirPath).delete();
}
}
/**
* 复制文件/文件夹 若要进行文件夹复制,请勿将目标文件夹置于源文件夹中
* @param source 源文件(夹)
* @param target 目标文件(夹)
* @param isFolder 若进行文件夹复制,则为True;反之为False
* @throws IOException
*/
public static void copy(String source, String target, boolean isFolder) throws IOException{
if (isFolder) {
new File(target).mkdirs();
File a = new File(source);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (source.endsWith(File.separator)) {
temp = new File(source + file[i]);
} else {
temp = new File(source + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(target + File.separator + temp.getName().toString());
byte[] b = new byte[1024];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
} if (temp.isDirectory()) {
copy(source + File.separator + file[i], target + File.separator + file[i], true);
}
}
} else {
int byteread = 0;
File oldfile = new File(source);
if (oldfile.exists()) {
InputStream inputStream = new FileInputStream(source);
File file = new File(target);
file.getParentFile().mkdirs();
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
while ((byteread = inputStream.read(buffer)) != -1){
outputStream.write(buffer, 0, byteread);
}
inputStream.close();
outputStream.close();
}
}
}
}
HttpUtil工具类:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Http请求的相关工具类
*/
public class HttpUtil {
private static final int TIMEOUT_IN_MILLIONS = 5000;
public interface CallBack {
void onRequestComplete(String requst);
}
/**
* 异步的Get请求
* @param urlStr
* @param callBack
*/
public static void doGetAsyn(final String urlStr, final CallBack callBack) {
new Thread(new Runnable() {
@Override
public void run() {
try {
String result = doGet(urlStr);
if (callBack != null) {
callBack.onRequestComplete(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
/**
* 异步的Post请求
* @param urlStr
* @param params
* @param callBack
* @throws Exception
*/
public static void doPostAsyn(final String urlStr, final String params,
final CallBack callBack) {
new Thread(new Runnable() {
@Override
public void run() {
try {
String result = doPost(urlStr, params);
if (callBack != null) {
callBack.onRequestComplete(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
/**
* Get请求,获得返回数据
*
* @param urlStr
* @return
* @throws Exception
*/
public static String doGet(String urlStr) {
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestMethod("GET");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[1024];
while ((len = is.read()) != -1) {
baos.write(buf, 0, len);
}
baos.flush();
return baos.toString();
} else {
throw new RuntimeException(" responseCode is not 200 ... ");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (baos != null)
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
}
return null;
}
/**
* 向指定 URL 发送POST方法的请求
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
* @throws Exception
*/
public static String doPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestMethod("POST");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setUseCaches(false);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
if (param != null && !param.trim().equals("")) {
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
PhoneUtil工具类:
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
/**
* 手机组件调用工具类
*/
public class PhoneUtil {
private static long lastClickTime;
private PhoneUtil() {
throw new Error("Do not need instantiate!");
}
/**
* 调用系统发短信界面
* @param activity Activity
* @param phoneNumber 手机号码
* @param smsContent 短信内容
*/
public static void sendMessage(Context activity, String phoneNumber, String smsContent) {
if (smsContent == null || phoneNumber.length() < 4) {
return;
}
Uri uri = Uri.parse("smsto:" + phoneNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsContent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
/**
* 判断是否为连击
* @return boolean
*/
public static boolean isFastDoubleClick() {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if (0 < timeD && timeD < 500) {
return true;
}
lastClickTime = time;
return false;
}
/**
* 获取手机型号
* @param context 上下文
* @return String
*/
public static String getMobileModel(Context context) {
try {
String model = android.os.Build.MODEL;
return model;
} catch (Exception e) {
return "未知!";
}
}
/**
* 获取手机品牌
* @param context 上下文
* @return String
*/
public static String getMobileBrand(Context context) {
try {
// android系统版本号
String brand = android.os.Build.BRAND;
return brand;
} catch (Exception e) {
return "未知";
}
}
/**
*拍照打开照相机!
* @param requestcode 返回值
* @param activity 上下文
* @param fileName 生成的图片文件的路径
*/
public static void toTakePhoto(int requestcode, Activity activity,String fileName) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("camerasensortype", 2);// 调用前置摄像头
intent.putExtra("autofocus", true);// 自动对焦
intent.putExtra("fullScreen", false);// 全屏
intent.putExtra("showActionIcons", false);
try {
//创建一个当前任务id的文件,然后里面存放任务的照片和路径!这主文件的名字是用uuid到时候再用任务id去查路径!
File file = new File(fileName);
//如果这个文件不存在就创建一个文件夹!
if (!file.exists()) {
file.mkdirs();
}
Uri uri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
activity.startActivityForResult(intent, requestcode);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*打开相册
* @param requestcode 响应码
* @param activity 上下文
*/
public static void toTakePicture(int requestcode, Activity activity){
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
activity.startActivityForResult(intent, requestcode);
}
}
ShortCutUtil工具类:
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
/**
* 创建删除快捷图标
* 需要权限: com.android.launcher.permission.INSTALL_SHORTCUT
* com.android.launcher.permission.UNINSTALL_SHORTCUT
*/
public class ShortCutUtil {
private ShortCutUtil() {
throw new Error("Do not need instantiate!");
}
/**
* 检测是否存在快捷键
* @param activity Activity
* @return 是否存在桌面图标
*/
public static boolean hasShortcut(Activity activity) {
boolean isInstallShortcut = false;
ContentResolver cr = activity.getContentResolver();
String AUTHORITY = "com.android.launcher.settings";
Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/favorites?notify=true");
Cursor c = cr.query(CONTENT_URI,
new String[]{"title", "iconResource"}, "title=?",
new String[]{activity.getString(R.string.app_name).trim()},
null);
if (c != null && c.getCount() > 0) {
isInstallShortcut = true;
}
return isInstallShortcut;
}
/**
* 为程序创建桌面快捷方式
* @param activity Activity
* @param res res
*/
public static void addShortcut(Activity activity,int res) {
Intent shortcut = new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT");
//快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
activity.getString(R.string.app_name));
//不允许重复创建
shortcut.putExtra("duplicate", false);
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(activity, activity.getClass().getName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
//快捷方式的图标
Intent.ShortcutIconResource iconRes =
Intent.ShortcutIconResource.fromContext(activity, res);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
activity.sendBroadcast(shortcut);
}
/**
* 删除程序的快捷方式
* @param activity Activity
*/
public static void delShortcut(Activity activity) {
Intent shortcut = new Intent(
"com.android.launcher.action.UNINSTALL_SHORTCUT");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
activity.getString(R.string.app_name));
String appClass = activity.getPackageName() + "."
+ activity.getLocalClassName();
ComponentName cn = new ComponentName(activity.getPackageName(), appClass);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(
Intent.ACTION_MAIN).setComponent(cn));
activity.sendBroadcast(shortcut);
}
}
StringUtil工具类:
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类,提供一些字符串相关的便捷方法
*/
public class StringUtil {
private StringUtil() {
throw new AssertionError();
}
/**
* <pre>
* isBlank(null) = true;
* isBlank("") = true;
* isBlank(" ") = true;
* isBlank("a") = false;
* isBlank("a ") = false;
* isBlank(" a") = false;
* isBlank("a b") = false;
* </pre>
*
* @param str 字符串
* @return 如果字符串为空或者长度为0,返回true,否则返回false
*/
public static boolean isBlank(String str) {
return (str == null || str.trim().length() == 0);
}
/**
* <pre>
* isEmpty(null) = true;
* isEmpty("") = true;
* isEmpty(" ") = false;
* </pre>
*
* @param c 字符序列
* @return 如果字符序列为空或者长度为0,返回true,否则返回false
*/
public static boolean isEmpty(CharSequence c) {
return (c == null || c.length() == 0);
}
/**
* 获取字符序列的长度
* <pre>
* length(null) = 0;
* length(\"\") = 0;
* length(\"abc\") = 3;
* </pre>
*
* @param c 字符序列
* @return 如果字符序列为空,返回0,否则返回字符序列的长度
*/
public static int length(CharSequence c) {
return c == null ? 0 : c.length();
}
/**
* null Object to empty string
* 空对象转化成空字符串
* <pre>
* nullStrToEmpty(null) = "";
* nullStrToEmpty("") = "";
* nullStrToEmpty("aa") = "aa";
* </pre>
*
* @param object 对象
* @return String
*/
public static String nullStrToEmpty(Object object) {
return object == null ?
"" : (object instanceof String ? (String)object : object.toString());
}
/**
* @param str str
* @return String
*/
public static String capitalizeFirstLetter(String str) {
if (isEmpty(str)) {
return str;
}
char c = str.charAt(0);
return (!Character.isLetter(c) || Character.isUpperCase(c))
? str
: new StringBuilder(str.length()).append(
Character.toUpperCase(c))
.append(str.substring(1))
.toString();
}
/**
* 用utf-8编码
* @param str 字符串
* @return 返回一个utf8的字符串
*/
public static String utf8Encode(String str) {
if (!isEmpty(str) || str.getBytes().length != str.length()) {
try {
return URLEncoder.encode(str, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(
"UnsupportedEncodingException occurred. ", e);
}
}
return str;
}
/**
* @param href 字符串
* @return 返回一个html
*/
public static String getHrefInnerHtml(String href) {
if (isEmpty(href)) {
return "";
}
String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);
Matcher hrefMatcher = hrefPattern.matcher(href);
if (hrefMatcher.matches()) {
return hrefMatcher.group(1);
}
return href;
}
/**
* @param source 字符串
* @return 返回htmL到字符串
*/
public static String htmlEscapeCharsToString(String source) {
return StringUtil.isEmpty(source)
? source
: source.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("&", "&")
.replaceAll(""", "\"");
}
/**
* @param s 字符串
* @return String
*/
public static String fullWidthToHalfWidth(String s) {
if (isEmpty(s)) {
return s;
}
char[] source = s.toCharArray();
for (int i = 0; i < source.length; i++) {
if (source[i] == 12288) {
source[i] = ' ';
// } else if (source[i] == 12290) {
// source[i] = '.';
}
else if (source[i] >= 65281 && source[i] <= 65374) {
source[i] = (char) (source[i] - 65248);
}
else {
source[i] = source[i];
}
}
return new String(source);
}
/**
* @param s 字符串
* @return 返回的数值
*/
public static String halfWidthToFullWidth(String s) {
if (isEmpty(s)) {
return s;
}
char[] source = s.toCharArray();
for (int i = 0; i < source.length; i++) {
if (source[i] == ' ') {
source[i] = (char) 12288;
// } else if (source[i] == '.') {
// source[i] = (char)12290;
}
else if (source[i] >= 33 && source[i] <= 126) {
source[i] = (char) (source[i] + 65248);
}
else {
source[i] = source[i];
}
}
return new String(source);
}
/**
* @param str 资源
* @return 特殊字符串切换
*/
public static String replaceBlanktihuan(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
/**
* 判断给定的字符串是否为null或者是空的
* @param string 给定的字符串
*/
public static boolean isEmpty(String string) {
return string == null || "".equals(string.trim());
}
/**
* 判断给定的字符串是否不为null且不为空
* @param string 给定的字符串
*/
public static boolean isNotEmpty(String string) {
return !isEmpty(string);
}
/**
* 判断给定的字符串数组中的所有字符串是否都为null或者是空的
* @param strings 给定的字符串
*/
public static boolean isEmpty(String... strings) {
boolean result = true;
for (String string : strings) {
if (isNotEmpty(string)) {
result = false;
break;
}
}
return result;
}
/**
* 判断给定的字符串数组中是否全部都不为null且不为空
*
* @param strings 给定的字符串数组
* @return 是否全部都不为null且不为空
*/
public static boolean isNotEmpty(String... strings) {
boolean result = true;
for (String string : strings) {
if (isEmpty(string)) {
result = false;
break;
}
}
return result;
}
/**
* 如果字符串是null或者空就返回""
*/
public static String filterEmpty(String string) {
return StringUtil.isNotEmpty(string) ? string : "";
}
/**
* 在给定的字符串中,用新的字符替换所有旧的字符
* @param string 给定的字符串
* @param oldchar 旧的字符
* @param newchar 新的字符
* @return 替换后的字符串
*/
public static String replace(String string, char oldchar, char newchar) {
char chars[] = string.toCharArray();
for (int w = 0; w < chars.length; w++) {
if (chars[w] == oldchar) {
chars[w] = newchar;
break;
}
}
return new String(chars);
}
/**
* 把给定的字符串用给定的字符分割
* @param string 给定的字符串
* @param ch 给定的字符
* @return 分割后的字符串数组
*/
public static String[] split(String string, char ch) {
ArrayList<String> stringList = new ArrayList<String>();
char chars[] = string.toCharArray();
int nextStart = 0;
for (int w = 0; w < chars.length; w++) {
if (ch == chars[w]) {
stringList.add(new String(chars, nextStart, w - nextStart));
nextStart = w + 1;
if (nextStart ==
chars.length) { //当最后一位是分割符的话,就再添加一个空的字符串到分割数组中去
stringList.add("");
}
}
}
if (nextStart <
chars.length) { //如果最后一位不是分隔符的话,就将最后一个分割符到最后一个字符中间的左右字符串作为一个字符串添加到分割数组中去
stringList.add(new String(chars, nextStart,
chars.length - 1 - nextStart + 1));
}
return stringList.toArray(new String[stringList.size()]);
}
/**
* 计算给定的字符串的长度,计算规则是:一个汉字的长度为2,一个字符的长度为1
*
* @param string 给定的字符串
* @return 长度
*/
public static int countLength(String string) {
int length = 0;
char[] chars = string.toCharArray();
for (int w = 0; w < string.length(); w++) {
char ch = chars[w];
if (ch >= '\u0391' && ch <= '\uFFE5') {
length++;
length++;
}
else {
length++;
}
}
return length;
}
private static char[] getChars(char[] chars, int startIndex) {
int endIndex = startIndex + 1;
//如果第一个是数字
if (Character.isDigit(chars[startIndex])) {
//如果下一个是数字
while (endIndex < chars.length &&
Character.isDigit(chars[endIndex])) {
endIndex++;
}
}
char[] resultChars = new char[endIndex - startIndex];
System.arraycopy(chars, startIndex, resultChars, 0, resultChars.length);
return resultChars;
}
/**
* 是否全是数字
*/
public static boolean isAllDigital(char[] chars) {
boolean result = true;
for (int w = 0; w < chars.length; w++) {
if (!Character.isDigit(chars[w])) {
result = false;
break;
}
}
return result;
}
/**
* 删除给定字符串中所有的旧的字符
*
* @param string 源字符串
* @param ch 要删除的字符
* @return 删除后的字符串
*/
public static String removeChar(String string, char ch) {
StringBuffer sb = new StringBuffer();
for (char cha : string.toCharArray()) {
if (cha != '-') {
sb.append(cha);
}
}
return sb.toString();
}
/**
* 删除给定字符串中给定位置处的字符
*
* @param string 给定字符串
* @param index 给定位置
*/
public static String removeChar(String string, int index) {
String result = null;
char[] chars = string.toCharArray();
if (index == 0) {
result = new String(chars, 1, chars.length - 1);
}
else if (index == chars.length - 1) {
result = new String(chars, 0, chars.length - 1);
}
else {
result = new String(chars, 0, index) +
new String(chars, index + 1, chars.length - index);
;
}
return result;
}
/**
* 删除给定字符串中给定位置处的字符
*
* @param string 给定字符串
* @param index 给定位置
* @param ch 如果同给定位置处的字符相同,则将给定位置处的字符删除
*/
public static String removeChar(String string, int index, char ch) {
String result = null;
char[] chars = string.toCharArray();
if (chars.length > 0 && chars[index] == ch) {
if (index == 0) {
result = new String(chars, 1, chars.length - 1);
}
else if (index == chars.length - 1) {
result = new String(chars, 0, chars.length - 1);
}
else {
result = new String(chars, 0, index) +
new String(chars, index + 1, chars.length - index);
;
}
}
else {
result = string;
}
return result;
}
/**
* 对给定的字符串进行空白过滤
*
* @param string 给定的字符串
* @return 如果给定的字符串是一个空白字符串,那么返回null;否则返回本身。
*/
public static String filterBlank(String string) {
if ("".equals(string)) {
return null;
}
else {
return string;
}
}
/**
* 将给定字符串中给定的区域的字符转换成小写
*
* @param str 给定字符串中
* @param beginIndex 开始索引(包括)
* @param endIndex 结束索引(不包括)
* @return 新的字符串
*/
public static String toLowerCase(String str, int beginIndex, int endIndex) {
return str.replaceFirst(str.substring(beginIndex, endIndex),
str.substring(beginIndex, endIndex)
.toLowerCase(Locale.getDefault()));
}
/**
* 将给定字符串中给定的区域的字符转换成大写
*
* @param str 给定字符串中
* @param beginIndex 开始索引(包括)
* @param endIndex 结束索引(不包括)
* @return 新的字符串
*/
public static String toUpperCase(String str, int beginIndex, int endIndex) {
return str.replaceFirst(str.substring(beginIndex, endIndex),
str.substring(beginIndex, endIndex)
.toUpperCase(Locale.getDefault()));
}
/**
* 将给定字符串的首字母转为小写
*
* @param str 给定字符串
* @return 新的字符串
*/
public static String firstLetterToLowerCase(String str) {
return toLowerCase(str, 0, 1);
}
/**
* 将给定字符串的首字母转为大写
*
* @param str 给定字符串
* @return 新的字符串
*/
public static String firstLetterToUpperCase(String str) {
return toUpperCase(str, 0, 1);
}
/**
* 将给定的字符串MD5加密
*
* @param string 给定的字符串
* @return MD5加密后生成的字符串
*/
public static String MD5(String string) {
String result = null;
try {
char[] charArray = string.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++) {
byteArray[i] = (byte) charArray[i];
}
StringBuffer hexValue = new StringBuffer();
byte[] md5Bytes = MessageDigest.getInstance("MD5")
.digest(byteArray);
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
result = hexValue.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 判断给定的字符串是否以一个特定的字符串开头,忽略大小写
*
* @param sourceString 给定的字符串
* @param newString 一个特定的字符串
*/
public static boolean startsWithIgnoreCase(String sourceString, String newString) {
int newLength = newString.length();
int sourceLength = sourceString.length();
if (newLength == sourceLength) {
return newString.equalsIgnoreCase(sourceString);
}
else if (newLength < sourceLength) {
char[] newChars = new char[newLength];
sourceString.getChars(0, newLength, newChars, 0);
return newString.equalsIgnoreCase(String.valueOf(newChars));
}
else {
return false;
}
}
/**
* 判断给定的字符串是否以一个特定的字符串结尾,忽略大小写
*
* @param sourceString 给定的字符串
* @param newString 一个特定的字符串
*/
public static boolean endsWithIgnoreCase(String sourceString, String newString) {
int newLength = newString.length();
int sourceLength = sourceString.length();
if (newLength == sourceLength) {
return newString.equalsIgnoreCase(sourceString);
}
else if (newLength < sourceLength) {
char[] newChars = new char[newLength];
sourceString.getChars(sourceLength - newLength, sourceLength,
newChars, 0);
return newString.equalsIgnoreCase(String.valueOf(newChars));
}
else {
return false;
}
}
/**
* 检查字符串长度,如果字符串的长度超过maxLength,就截取前maxLength个字符串并在末尾拼上appendString
*/
public static String checkLength(String string, int maxLength, String appendString) {
if (string.length() > maxLength) {
string = string.substring(0, maxLength);
if (appendString != null) {
string += appendString;
}
}
return string;
}
/**
* 检查字符串长度,如果字符串的长度超过maxLength,就截取前maxLength个字符串并在末尾拼上…
*/
public static String checkLength(String string, int maxLength) {
return checkLength(string, maxLength, "…");
}
}