Android开发常用工具类

博客源址:http://blog.csdn.net/dimudan2015/article/details/71158332

工具类有:AppUtil、BitmapUtil、DateUtil、JsonUtil、LogUtil、MeasureUtil、NetWorkUtil、PreferencesUtil、ReflectUtil、SDCardUtil、ScreenUtil、XmlUtil、ColorUtil、ExitActivityUtil、FileUtil、HttpUtil、PhoneUtil、ShortCutUtil、


AppUtil工具类:

  1. import java.io.File;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4.   
  5. import android.app.Activity;  
  6. import android.content.Context;  
  7. import android.content.Intent;  
  8. import android.content.pm.ApplicationInfo;  
  9. import android.content.pm.PackageInfo;  
  10. import android.content.pm.PackageManager;  
  11. import android.content.pm.PackageManager.NameNotFoundException;  
  12. import android.graphics.drawable.Drawable;  
  13. import android.net.Uri;  
  14.   
  15. /** 
  16.  * 常用APP的工具类,包含版本号、版本名称、安装的应用程序ICON 
  17.  */  
  18. public class AppUtil {  
  19.     private AppUtil(){}  
  20.   
  21.     /** 
  22.      * 获取包名 
  23.      * @param context 
  24.      * @return 
  25.      */  
  26.     public static String getPackageName(Context context){  
  27.         return context.getPackageName();  
  28.     }  
  29.       
  30.     /** 
  31.      * 获取VersionName(版本名称) 
  32.      * @param context 
  33.      * @return 
  34.      * 失败时返回"" 
  35.      */  
  36.     public static String getVersionName(Context context){  
  37.         PackageManager packageManager = getPackageManager(context);  
  38.         try {  
  39.             PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(context), 0);  
  40.             return packageInfo.versionName;  
  41.         } catch (NameNotFoundException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.         return "";  
  45.     }  
  46.       
  47.     /** 
  48.      * 获取VersionCode(版本号) 
  49.      * @param context 
  50.      * @return 
  51.      * 失败时返回-1 
  52.      */  
  53.     public static int getVersionCode(Context context){  
  54.         PackageManager packageManager = getPackageManager(context);  
  55.         try {  
  56.             PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(context), 0);  
  57.             return packageInfo.versionCode;  
  58.         } catch (NameNotFoundException e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.         return -1;  
  62.     }  
  63.       
  64.     /** 
  65.      * 获取所有安装的应用程序,不包含系统应用 
  66.      * @param context 
  67.      * @return 
  68.      */  
  69.     public static List<PackageInfo> getInstalledPackages(Context context){  
  70.         PackageManager packageManager = getPackageManager(context);  
  71.         List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);  
  72.         List<PackageInfo> packageInfoList  = new ArrayList<PackageInfo>();  
  73.         for(int i=0; i < packageInfos.size();i++){  
  74.             if ((packageInfos.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {  
  75.                 packageInfoList.add(packageInfos.get(i));  
  76.             }  
  77.         }  
  78.         return packageInfoList;  
  79.     }  
  80.       
  81.     /** 
  82.      * 获取应用程序的icon图标 
  83.      * @param context 
  84.      * @return 
  85.      * 当包名错误时,返回null 
  86.      */  
  87.     public static Drawable getApplicationIcon(Context context){  
  88.         PackageManager packageManager = getPackageManager(context);  
  89.         try {  
  90.             PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(context), 0);  
  91.             return packageInfo.applicationInfo.loadIcon(packageManager);  
  92.         } catch (NameNotFoundException e) {  
  93.             e.printStackTrace();  
  94.         }  
  95.         return null;  
  96.     }  
  97.       
  98.     /** 
  99.      * 启动安装应用程序 
  100.      * @param activity 
  101.      * @param path  应用程序路径 
  102.      */  
  103.     public static void installApk(Activity activity, String path){  
  104.         Intent intent = new Intent(Intent.ACTION_VIEW);  
  105.         intent.setDataAndType(Uri.fromFile(new File(path)),  
  106.                 "application/vnd.android.package-archive");  
  107.         activity.startActivity(intent);  
  108.     }  
  109.       
  110.     /** 
  111.      * 获取PackageManager对象 
  112.      * @param context 
  113.      * @return 
  114.      */  
  115.     private static PackageManager getPackageManager(Context context){  
  116.         return context.getPackageManager();  
  117.     }  
  118. }  
BitmapUtil工具类:

  1. import java.io.ByteArrayOutputStream;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Bitmap;  
  5. import android.graphics.Bitmap.CompressFormat;  
  6. import android.graphics.BitmapFactory;  
  7. import android.graphics.BitmapFactory.Options;  
  8. import android.graphics.Canvas;  
  9. import android.graphics.PixelFormat;  
  10. import android.graphics.drawable.BitmapDrawable;  
  11. import android.graphics.drawable.Drawable;  
  12. import android.media.ThumbnailUtils;  
  13. import android.text.TextUtils;  
  14.   
  15. /** 
  16.  * Bitmap工具类,获取Bitmap对象 
  17.  */  
  18. public class BitmapUtil {  
  19.       
  20.     private BitmapUtil(){}  
  21.       
  22.     /** 
  23.      * 根据资源id获取指定大小的Bitmap对象 
  24.      * @param context   应用程序上下文 
  25.      * @param id        资源id 
  26.      * @param height    高度 
  27.      * @param width     宽度 
  28.      * @return 
  29.      */  
  30.     public static Bitmap getBitmapFromResource(Context context, int id, int height, int width){  
  31.         Options options = new Options();  
  32.         options.inJustDecodeBounds = true;//只读取图片,不加载到内存中  
  33.         BitmapFactory.decodeResource(context.getResources(), id, options);  
  34.         options.inSampleSize = calculateSampleSize(height, width, options);  
  35.         options.inJustDecodeBounds = false;//加载到内存中  
  36.         Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);  
  37.         return bitmap;  
  38.     }  
  39.       
  40.     /** 
  41.      * 根据文件路径获取指定大小的Bitmap对象 
  42.      * @param path      文件路径 
  43.      * @param height    高度 
  44.      * @param width     宽度 
  45.      * @return 
  46.      */  
  47.     public static Bitmap getBitmapFromFile(String path, int height, int width){  
  48.         if (TextUtils.isEmpty(path)) {  
  49.             throw new IllegalArgumentException("参数为空,请检查你选择的路径:" + path);  
  50.         }  
  51.         Options options = new Options();  
  52.         options.inJustDecodeBounds = true;//只读取图片,不加载到内存中  
  53.         BitmapFactory.decodeFile(path, options);  
  54.         options.inSampleSize = calculateSampleSize(height, width, options);  
  55.         options.inJustDecodeBounds = false;//加载到内存中  
  56.         Bitmap bitmap = BitmapFactory.decodeFile(path, options);  
  57.         return bitmap;  
  58.     }  
  59.       
  60.     /** 
  61.      * 获取指定大小的Bitmap对象 
  62.      * @param bitmap    Bitmap对象 
  63.      * @param height    高度 
  64.      * @param width     宽度 
  65.      * @return 
  66.      */  
  67.     public static Bitmap getThumbnailsBitmap(Bitmap bitmap, int height, int width){  
  68.         if (bitmap == null) {  
  69.             throw new IllegalArgumentException("图片为空,请检查你的参数");  
  70.         }  
  71.         return ThumbnailUtils.extractThumbnail(bitmap, width, height);  
  72.     }  
  73.       
  74.     /** 
  75.      * 将Bitmap对象转换成Drawable对象 
  76.      * @param context   应用程序上下文 
  77.      * @param bitmap    Bitmap对象 
  78.      * @return  返回转换后的Drawable对象 
  79.      */  
  80.     public static Drawable bitmapToDrawable(Context context, Bitmap bitmap){  
  81.         if (context == null || bitmap == null) {  
  82.             throw new IllegalArgumentException("参数不合法,请检查你的参数");  
  83.         }  
  84.         Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);  
  85.         return drawable;  
  86.     }  
  87.       
  88.     /** 
  89.      * 将Drawable对象转换成Bitmap对象 
  90.      * @param drawable  Drawable对象 
  91.      * @return  返回转换后的Bitmap对象 
  92.      */  
  93.     public static Bitmap drawableToBitmap(Drawable drawable) {  
  94.         if (drawable == null) {  
  95.             throw new IllegalArgumentException("Drawable为空,请检查你的参数");  
  96.         }  
  97.         Bitmap bitmap =   
  98.                 Bitmap.createBitmap(drawable.getIntrinsicWidth(),   
  99.                         drawable.getIntrinsicHeight(),   
  100.                         drawable.getOpacity() != PixelFormat.OPAQUE? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);  
  101.         Canvas canvas = new Canvas(bitmap);  
  102.         drawable.setBounds(00, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  
  103.         drawable.draw(canvas);  
  104.         return bitmap;  
  105.     }  
  106.       
  107.     /** 
  108.      * 将Bitmap对象转换为byte[]数组 
  109.      * @param bitmap    Bitmap对象 
  110.      * @return      返回转换后的数组 
  111.      */  
  112.     public static byte[] bitmapToByte(Bitmap bitmap){  
  113.         if (bitmap == null) {  
  114.             throw new IllegalArgumentException("Bitmap为空,请检查你的参数");  
  115.         }  
  116.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  117.         bitmap.compress(CompressFormat.PNG, 100, baos);  
  118.         return baos.toByteArray();  
  119.     }  
  120.       
  121.     /** 
  122.      * 计算所需图片的缩放比例 
  123.      * @param height    高度 
  124.      * @param width     宽度 
  125.      * @param options   options选项 
  126.      * @return 
  127.      */  
  128.     private static int calculateSampleSize(int height, int width, Options options){  
  129.         int realHeight = options.outHeight;  
  130.         int realWidth = options.outWidth;  
  131.         int heigthScale = realHeight / height;  
  132.         int widthScale = realWidth / width;  
  133.         if(widthScale > heigthScale){  
  134.             return widthScale;  
  135.         }else{  
  136.             return heigthScale;  
  137.         }  
  138.     }  
  139. }  
DateUtil工具类:

  1. import java.text.ParseException;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.Calendar;  
  4. import java.util.Date;  
  5. import java.util.Locale;  
  6.   
  7. public class DateUtil {  
  8.   
  9.     private DateUtil(){}  
  10.       
  11.     /** 
  12.      * 枚举日期格式 
  13.      */  
  14.     public enum DatePattern{  
  15.         /** 
  16.          * 格式:"yyyy-MM-dd HH:mm:ss" 
  17.          */  
  18.         ALL_TIME{public String getValue(){return "yyyy-MM-dd HH:mm:ss";}},  
  19.         /** 
  20.          * 格式:"yyyy-MM" 
  21.          */  
  22.         ONLY_MONTH{public String getValue(){return "yyyy-MM";}},  
  23.         /** 
  24.          * 格式:"yyyy-MM-dd" 
  25.          */  
  26.         ONLY_DAY{public String getValue(){return "yyyy-MM-dd";}},  
  27.         /** 
  28.          * 格式:"yyyy-MM-dd HH" 
  29.          */  
  30.         ONLY_HOUR{public String getValue(){return "yyyy-MM-dd HH";}},  
  31.         /** 
  32.          * 格式:"yyyy-MM-dd HH:mm" 
  33.          */  
  34.         ONLY_MINUTE{public String getValue(){return "yyyy-MM-dd HH:mm";}},  
  35.         /** 
  36.          * 格式:"MM-dd" 
  37.          */  
  38.         ONLY_MONTH_DAY{public String getValue(){return "MM-dd";}},  
  39.         /** 
  40.          * 格式:"MM-dd HH:mm" 
  41.          */  
  42.         ONLY_MONTH_SEC{public String getValue(){return "MM-dd HH:mm";}},  
  43.         /** 
  44.          * 格式:"HH:mm:ss" 
  45.          */  
  46.         ONLY_TIME{public String getValue(){return "HH:mm:ss";}},  
  47.         /** 
  48.          * 格式:"HH:mm" 
  49.          */  
  50.         ONLY_HOUR_MINUTE{public String getValue(){return "HH:mm";}};  
  51.         public abstract String getValue();  
  52.     }  
  53.       
  54.     /** 
  55.      * 获取当前时间 
  56.      * @return  返回当前时间,格式2017-05-04 10:54:21 
  57.      */  
  58.     public static String getNowDate(DatePattern pattern){  
  59.         String dateString = null;  
  60.         Calendar calendar = Calendar.getInstance();  
  61.         Date dateNow = calendar.getTime();  
  62.         SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(),Locale.CHINA);  
  63.         dateString = sdf.format(dateNow);  
  64.         return dateString;  
  65.     }  
  66.       
  67.     /** 
  68.      * 将一个日期字符串转换成Data对象 
  69.      * @param dateString    日期字符串 
  70.      * @param pattern       转换格式 
  71.      * @return  返回转换后的日期对象 
  72.      */  
  73.     public static Date stringToDate(String dateString, DatePattern pattern){  
  74.         Date date = null;  
  75.         SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(),Locale.CHINA);  
  76.         try {  
  77.             date = sdf.parse(dateString);  
  78.         } catch (ParseException e) {  
  79.             e.printStackTrace();  
  80.         }  
  81.         return date;  
  82.     }  
  83.       
  84.     /** 
  85.      * 将date转换成字符串 
  86.      * @param date  日期 
  87.      * @param pattern   日期的目标格式 
  88.      * @return 
  89.      */  
  90.     public static String dateToString(Date date, DatePattern pattern){  
  91.         String string = "";  
  92.         SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(), Locale.CHINA);  
  93.         string = sdf.format(date);  
  94.         return string;  
  95.     }  
  96.       
  97.     /** 
  98.      * 获取指定日期周几 
  99.      * @param date  指定日期 
  100.      * @return 
  101.      * 返回值为: "周日", "周一", "周二", "周三", "周四", "周五", "周六"  
  102.      */  
  103.     public static String getWeekOfDate(Date date){  
  104.         String[] weekDays = { "周日""周一""周二""周三""周四""周五""周六" };  
  105.         Calendar calendar = Calendar.getInstance();  
  106.         calendar.setTime(date);  
  107.         int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;  
  108.         if (week < 0)  
  109.             week = 0;  
  110.         return weekDays[week];  
  111.     }  
  112.       
  113.     /** 
  114.      * 获取指定日期对应周几的序列 
  115.      * @param date  指定日期 
  116.      * @return  周一:1    周二:2    周三:3    周四:4    周五:5    周六:6    周日:7 
  117.      */  
  118.     public static int getIndexWeekOfDate(Date date){  
  119.         Calendar calendar = Calendar.getInstance();  
  120.         calendar.setTime(date);  
  121.         int index = calendar.get(Calendar.DAY_OF_WEEK);  
  122.         if(index == 1){  
  123.             return 7;  
  124.         }else{  
  125.             return --index;  
  126.         }  
  127.     }  
  128.       
  129.     /** 
  130.      * 返回当前月份 
  131.      * @return 
  132.      */  
  133.     public static int getNowMonth(){  
  134.         Calendar calendar = Calendar.getInstance();  
  135.         return calendar.get(Calendar.MONTH) + 1;  
  136.     }  
  137.       
  138.     /** 
  139.      * 获取当前月号 
  140.      * @return 
  141.      */  
  142.     public static int getNowDay(){  
  143.         Calendar calendar = Calendar.getInstance();  
  144.         return calendar.get(Calendar.DATE);  
  145.     }  
  146.       
  147.     /** 
  148.      * 获取当前年份 
  149.      * @return 
  150.      */  
  151.     public static int getNowYear(){  
  152.         Calendar calendar = Calendar.getInstance();  
  153.         return calendar.get(Calendar.YEAR);  
  154.     }  
  155.       
  156.     /** 
  157.      * 获取本月份的天数 
  158.      * @return 
  159.      */  
  160.     public static int getNowDaysOfMonth(){  
  161.         Calendar calendar = Calendar.getInstance();  
  162.         return daysOfMonth(calendar.get(Calendar.YEAR),calendar.get(Calendar.DATE) + 1);  
  163.     }  
  164.       
  165.     /** 
  166.      * 获取指定月份的天数 
  167.      * @param year  年份 
  168.      * @param month 月份 
  169.      * @return  对应天数 
  170.      */  
  171.     public static int daysOfMonth(int year,int month){  
  172.         switch(month){  
  173.         case 1:  
  174.         case 3:  
  175.         case 5:  
  176.         case 7:  
  177.         case 8:  
  178.         case 10:  
  179.         case 12:  
  180.             return 31;  
  181.         case 4:  
  182.         case 6:  
  183.         case 9:  
  184.         case 11:  
  185.             return 30;  
  186.         case 2:  
  187.             if((year % 4 ==0 && year % 100 == 0) || year % 400 != 0){  
  188.                 return 29;  
  189.             }else{  
  190.                 return 28;  
  191.             }  
  192.         default:  
  193.                 return -1;  
  194.         }  
  195.     }  
  196. }  
JsonUtil工具类:

  1. import java.util.Iterator;  
  2. import java.util.List;  
  3.   
  4. import org.json.JSONArray;  
  5. import org.json.JSONException;  
  6. import org.json.JSONObject;  
  7.   
  8. import android.content.ContentValues;  
  9.   
  10. import com.google.gson.Gson;  
  11.   
  12. /** 
  13.  * 常用的Json工具类,包含Json转换成实体、实体转json字符串、list集合转换成json、数组转换成json 
  14.  */  
  15. public class JsonUtil {  
  16.       
  17.     private JsonUtil(){}  
  18.       
  19.     private static Gson gson = new Gson();  
  20.       
  21.     /** 
  22.      * 将一个对象转换成一个Json字符串 
  23.      * @param t 
  24.      * @return 
  25.      */  
  26.     public static <T> String objectToJson(T t){  
  27.         if (t instanceof String) {  
  28.             return t.toString();  
  29.         } else {  
  30.             return gson.toJson(t);  
  31.         }  
  32.     }  
  33.       
  34.     /** 
  35.      * 将Json字符串转换成对应对象 
  36.      * @param jsonString    Json字符串 
  37.      * @param clazz     对应字节码文件.class 
  38.      * @return 
  39.      */  
  40.     @SuppressWarnings("unchecked")  
  41.     public static<T> T jsonToObject(String jsonString, Class<T> clazz){  
  42.         if (clazz == String.class) {  
  43.             return (T) jsonString;  
  44.         } else {  
  45.             return (T)gson.fromJson(jsonString, clazz);  
  46.         }  
  47.     }  
  48.       
  49.     /** 
  50.      * 将List集合转换为json字符串 
  51.      * @param list  List集合 
  52.      * @return 
  53.      */  
  54.     public static<T> String listToJson(List<T> list){  
  55.         JSONArray jsonArray = new JSONArray();  
  56.         JSONObject jsonObject = null;  
  57.         try {  
  58.             for (int i = 0; i < list.size(); i++) {  
  59.                 jsonObject = new JSONObject(objectToJson(list.get(i)));  
  60.                 jsonArray.put(jsonObject);  
  61.             }  
  62.         } catch (JSONException e) {  
  63.             e.printStackTrace();  
  64.         } finally {  
  65.             if (jsonObject != null) {  
  66.                 jsonObject = null;  
  67.             }  
  68.         }  
  69.         return jsonArray.toString();  
  70.     }  
  71.       
  72.     /** 
  73.      * 将数组转换成json字符串 
  74.      * @param array     数组 
  75.      * @return 
  76.      */  
  77.     public static<T> String arrayToJson(T[] array){  
  78.         JSONArray jsonArray = new JSONArray();  
  79.         JSONObject jsonObject = null;  
  80.         try {  
  81.             for (int i = 0; i < array.length; i++) {  
  82.                 jsonObject = new JSONObject(objectToJson(array[i]));  
  83.                 jsonArray.put(jsonObject);  
  84.             }  
  85.         } catch (JSONException e) {  
  86.             e.printStackTrace();  
  87.         } finally {  
  88.             if (jsonObject != null) {  
  89.                 jsonObject = null;  
  90.             }  
  91.         }  
  92.         return jsonArray.toString();  
  93.     }  
  94.       
  95.     /** 
  96.      * 获取json字符串中的值 
  97.      * @param json  json字符串 
  98.      * @param key   键值 
  99.      * @param clazz 所取数据类型,例如:Integer.class,String.class,Double.class,JSONObject.class 
  100.      * @return  存在则返回正确值,不存在返回null 
  101.      */  
  102.     public static<T> T getJsonObjectValue(String json, String key, Class<T> clazz){  
  103.         try {  
  104.             return getJsonObjectValue(new JSONObject(json), key, clazz);  
  105.         } catch (JSONException e) {  
  106.             e.printStackTrace();  
  107.         }  
  108.         return null;  
  109.     }  
  110.       
  111.     /** 
  112.      * 获取jsonObject对象中的值 
  113.      * @param jsonObject    jsonObject对象 
  114.      * @param key   键值 
  115.      * @param clazz 所取数据类型,例如:Integer.class,String.class,Double.class,JSONObject.class 
  116.      * @return  存在则返回正确值,不存在返回null 
  117.      */  
  118.     @SuppressWarnings("unchecked")  
  119.     public static<T> T getJsonObjectValue(JSONObject jsonObject, String key, Class<T> clazz){  
  120.         T t = null;  
  121.         try {  
  122.             if (clazz == Integer.class) {  
  123.                 t = (T) Integer.valueOf(jsonObject.getInt(key));  
  124.             }else if(clazz == Boolean.class){  
  125.                 t = (T) Boolean.valueOf(jsonObject.getBoolean(key));  
  126.             }else if(clazz == String.class){  
  127.                 t = (T) String.valueOf(jsonObject.getString(key));  
  128.             }else if(clazz == Double.class){  
  129.                 t = (T) Double.valueOf(jsonObject.getDouble(key));  
  130.             }else if(clazz == JSONObject.class){  
  131.                 t = (T) jsonObject.getJSONObject(key);  
  132.             }else if(clazz == JSONArray.class){  
  133.                 t = (T) jsonObject.getJSONArray(key);  
  134.             }else if(clazz == Long.class){  
  135.                 t = (T) Long.valueOf(jsonObject.getLong(key));  
  136.             }  
  137.         } catch (JSONException e) {  
  138.             e.printStackTrace();  
  139.         }  
  140.         return t;  
  141.     }  
  142.   
  143.     /** 
  144.      * json字符串转换为ContentValues 
  145.      * @param json  json字符串 
  146.      * @return 
  147.      */  
  148.     @SuppressWarnings("rawtypes")  
  149.     public static ContentValues jsonToContentValues(String json){  
  150.         ContentValues contentValues = new ContentValues();  
  151.         try {  
  152.             JSONObject jsonObject = new JSONObject(json);  
  153.             Iterator iterator = jsonObject.keys();  
  154.             String key;  
  155.             Object value;  
  156.             while (iterator.hasNext()) {  
  157.                 key = iterator.next().toString();  
  158.                 value = jsonObject.get(key);  
  159.                 String valueString = value.toString();  
  160.                 if (value instanceof String) {  
  161.                     contentValues.put(key, valueString);  
  162.                 }else if(value instanceof Integer){  
  163.                     contentValues.put(key, Integer.valueOf(valueString));  
  164.                 }else if(value instanceof Long){  
  165.                     contentValues.put(key, Long.valueOf(valueString));  
  166.                 }else if(value instanceof Double){  
  167.                     contentValues.put(key, Double.valueOf(valueString));  
  168.                 }else if(value instanceof Float){  
  169.                     contentValues.put(key, Float.valueOf(valueString));  
  170.                 }else if(value instanceof Boolean){  
  171.                     contentValues.put(key, Boolean.valueOf(valueString));  
  172.                 }  
  173.             }  
  174.         } catch (JSONException e) {  
  175.             e.printStackTrace();  
  176.             throw new Error("Json字符串不合法:" + json);  
  177.         }  
  178.           
  179.         return contentValues;  
  180.     }  
  181. }  
LogUtil工具类:

  1. import android.util.Log;  
  2.   
  3. /** 
  4.  * Log日志工具类 
  5.  */  
  6. public class LogUtil {  
  7.   
  8.     private LogUtil(){}  
  9.       
  10.     /** 
  11.      * 打印information日志 
  12.      * @param tag 标签 
  13.      * @param msg 日志信息 
  14.      */  
  15.     public static void i(String tag,String msg){  
  16.         Log.i(tag, msg);  
  17.     }  
  18.       
  19.     /** 
  20.      * 打印information日志 
  21.      * @param tag   标签 
  22.      * @param msg   日志信息 
  23.      * @param throwable 异常 
  24.      */  
  25.     public static void i(String tag, String msg, Throwable throwable){  
  26.         Log.i(tag,msg,throwable);  
  27.     }  
  28.       
  29.     /** 
  30.      * 打印verbose日志 
  31.      * @param tag   标签 
  32.      * @param msg   日志信息 
  33.      */  
  34.     public static void v(String tag, String msg){  
  35.         Log.v(tag, msg);  
  36.     }  
  37.       
  38.     /** 
  39.      * 打印verbose日志 
  40.      * @param tag   标签 
  41.      * @param msg   日志信息 
  42.      * @param throwable 异常 
  43.      */  
  44.     public static void v(String tag, String msg, Throwable throwable){  
  45.         Log.v(tag, msg, throwable);  
  46.     }  
  47.       
  48.     /** 
  49.      * 打印debug信息 
  50.      * @param tag   标签信息 
  51.      * @param msg   日志信息 
  52.      */  
  53.     public static void d(String tag, String msg){  
  54.         Log.d(tag, msg);  
  55.     }  
  56.       
  57.     /** 
  58.      * 打印debug日志 
  59.      * @param tag   标签信息 
  60.      * @param msg   日志信息 
  61.      * @param throwable 异常 
  62.      */  
  63.     public static void d(String tag, String msg, Throwable throwable){  
  64.         Log.d(tag, msg, throwable);  
  65.     }  
  66.       
  67.     /** 
  68.      * 打印warn日志 
  69.      * @param tag   标签信息 
  70.      * @param msg   日志信息 
  71.      */  
  72.     public static void w(String tag, String msg){  
  73.         Log.w(tag, msg);  
  74.     }  
  75.       
  76.     /** 
  77.      * 打印warn日志 
  78.      * @param tag   标签信息 
  79.      * @param msg   日志信息 
  80.      * @param throwable 异常 
  81.      */  
  82.     public static void w(String tag, String msg, Throwable throwable){  
  83.         Log.w(tag, msg, throwable);  
  84.     }  
  85.       
  86.     /** 
  87.      * 打印error日志 
  88.      * @param tag   标签 
  89.      * @param msg   日志信息 
  90.      */  
  91.     public static void e(String tag, String msg){  
  92.         Log.e(tag, msg);  
  93.     }  
  94.       
  95.     /** 
  96.      * 打印error日志 
  97.      * @param tag   标签 
  98.      * @param msg   日志信息 
  99.      * @param throwable 异常 
  100.      */  
  101.     public static void e(String tag, String msg, Throwable throwable){  
  102.         Log.e(tag, msg, throwable);  
  103.     }  
  104. }  
MeasureUtil工具类:

  1. import android.content.Context;  
  2. import android.view.View;  
  3. import android.view.ViewGroup;  
  4. import android.widget.Adapter;  
  5. import android.widget.GridView;  
  6. import android.widget.ListView;  
  7.   
  8. /** 
  9.  * 常用的测量功能 
  10.  */  
  11. public class MeasureUtil {  
  12.   
  13.     private MeasureUtil(){}  
  14.       
  15.     /** 
  16.      * 获取控件的测量高度 
  17.      * @param view  控件 
  18.      * @return  返回测量高度(MeasuredHeight) 
  19.      */  
  20.     public static int getMeasuredHeight(View view) {  
  21.         if (view == null) {  
  22.             throw new IllegalArgumentException("view is null");  
  23.         }  
  24.         view.measure(00);  
  25.         return view.getMeasuredHeight();  
  26.     }  
  27.       
  28.     /** 
  29.      * 控件的高度 
  30.      * @param view  控件View 
  31.      * @return  返回控件的高度 
  32.      */  
  33.     public static int getHeight(View view){  
  34.         if(view == null){  
  35.             throw new IllegalArgumentException("view is null");  
  36.         }  
  37.           
  38.         view.measure(00);  
  39.         return view.getHeight();  
  40.     }  
  41.   
  42.     /** 
  43.      * 获取控件的测量宽度 
  44.      * @param view  控件 
  45.      * @return  返回控件的测量宽度 
  46.      */  
  47.     public static int getMeasuredWidth(View view){  
  48.         if(view == null){  
  49.             throw new IllegalArgumentException("view is null");  
  50.         }  
  51.           
  52.         view.measure(00);  
  53.         return view.getMeasuredWidth();  
  54.     }  
  55.       
  56.     /** 
  57.      * 获取控件的宽度 
  58.      * @param view  控件 
  59.      * @return  返回控件的宽度 
  60.      */  
  61.     public static int getWidth(View view){  
  62.         if(view == null){  
  63.             throw new IllegalArgumentException("view is null");  
  64.         }  
  65.           
  66.         view.measure(00);  
  67.         return view.getWidth();  
  68.     }  
  69.       
  70.     /** 
  71.      * 设置高度 
  72.      * @param view  控件 
  73.      * @param height    高度   
  74.      */  
  75.     public static void setHeight(View view, int height) {  
  76.         if (view == null || view.getLayoutParams() == null) {  
  77.             throw new IllegalArgumentException("View LayoutParams is null");  
  78.         }  
  79.         ViewGroup.LayoutParams params = view.getLayoutParams();  
  80.         params.height = height;  
  81.         view.setLayoutParams(params);  
  82.     }  
  83.       
  84.     /** 
  85.      * 设置View的宽度 
  86.      * @param view  view 
  87.      * @param width 宽度 
  88.      */  
  89.     public static void setWidth(View view, int width){  
  90.         if(view == null || view.getLayoutParams() == null){  
  91.             throw new IllegalArgumentException("View LayoutParams is null");  
  92.         }  
  93.   
  94.         ViewGroup.LayoutParams params = view.getLayoutParams();  
  95.         params.width = width;  
  96.         view.setLayoutParams(params);  
  97.     }  
  98.       
  99.     /** 
  100.      * 设置ListView的实际高度 
  101.      * @param listView  ListView控件 
  102.      */  
  103.     public static void setListHeight(ListView listView) {  
  104.         if (listView == null) {  
  105.             throw new IllegalArgumentException("ListView is null");  
  106.         }  
  107.         Adapter adapter = listView.getAdapter();  
  108.         if (adapter == null) {  
  109.             return;  
  110.         }  
  111.         int totalHeight = 0;  
  112.         int size = adapter.getCount();  
  113.         for (int i = 0; i < size; i++) {  
  114.             View listItem = adapter.getView(i, null, listView);  
  115.             listItem.measure(00);  
  116.             totalHeight += listItem.getMeasuredHeight();  
  117.         }  
  118.         ViewGroup.LayoutParams params = listView.getLayoutParams();  
  119.         params.height = totalHeight + (listView.getDividerHeight() * (size - 1));  
  120.         LogUtil.d("MeasureUtil""listview-height--" + params.height);  
  121.         listView.setLayoutParams(params);  
  122.     }  
  123.       
  124.     /** 
  125.      * 设置GridView的高度, 
  126.      * @param context   应用程序上下文 
  127.      * @param gv        GridView控件 
  128.      * @param n         行数 
  129.      * @param m         列数 
  130.      */  
  131.     public static void setGridViewHeight(Context context, GridView gv, int n, int m) {  
  132.         if(gv == null){  
  133.             throw new IllegalArgumentException("GridView is null");  
  134.         }  
  135.         Adapter adapter = gv.getAdapter();  
  136.         if (adapter == null) {  
  137.             return;  
  138.         }  
  139.         int totalHeight = 0;  
  140.         int size = adapter.getCount();  
  141.         for (int i = 0; i < size; i++) {  
  142.             View listItem = adapter.getView(i, null, gv);  
  143.             listItem.measure(00);  
  144.             totalHeight += listItem.getMeasuredHeight() + ScreenUtil.dp2px(context, m);  
  145.         }  
  146.         ViewGroup.LayoutParams params = gv.getLayoutParams();  
  147.         params.height = totalHeight + gv.getPaddingTop() + gv.getPaddingBottom() + 2;  
  148.         LogUtil.d("MeasureUtil""gridview-height--" + params.height);  
  149.         gv.setLayoutParams(params);  
  150.     }  
  151.       
  152. }  
NetWorkUtil工具类:
  1. import android.app.Activity;  
  2. import android.content.ComponentName;  
  3. import android.content.Context;  
  4. import android.content.Intent;  
  5. import android.net.ConnectivityManager;  
  6. import android.net.NetworkInfo;  
  7. import android.provider.Settings;  
  8.   
  9. /** 
  10.  * 网络工具类,包含网络的判断、跳转到设置页面 
  11.  */  
  12. public class NetWorkUtil {  
  13.   
  14.     /** 
  15.      * 判断当前是否有网络连接 
  16.      * @param context 
  17.      * @return  有网络返回true;无网络返回false 
  18.      */  
  19.     @SuppressWarnings("null")  
  20.     public static boolean isNetWorkEnable(Context context){  
  21.         ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  22.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();  
  23.         if (networkInfo != null || networkInfo.isConnected()) {  
  24.             if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {  
  25.                 return true;  
  26.             }  
  27.         }  
  28.         return false;  
  29.     }  
  30.       
  31.     /** 
  32.      * 判断当前网络是否为wifi 
  33.      * @param context 
  34.      * @return  如果为wifi返回true;否则返回false 
  35.      */  
  36.     @SuppressWarnings("static-access")  
  37.     public static boolean isWiFiConnected(Context context){  
  38.         ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  39.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();  
  40.         return networkInfo.getType() == manager.TYPE_WIFI ? true : false;  
  41.     }  
  42.       
  43.     /** 
  44.      * 判断MOBILE网络是否可用 
  45.      * @param context 
  46.      * @return 
  47.      * @throws Exception 
  48.      */  
  49.     public static boolean isMobileDataEnable(Context context){  
  50.         ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  51.         boolean isMobileDataEnable = false;  
  52.         isMobileDataEnable = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();  
  53.         return isMobileDataEnable;  
  54.     }  
  55.       
  56.     /** 
  57.      * 判断wifi 是否可用 
  58.      * @param context 
  59.      * @return 
  60.      * @throws Exception 
  61.      */  
  62.     public static boolean isWifiDataEnable(Context context){  
  63.         ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  64.         boolean isWifiDataEnable = false;  
  65.         isWifiDataEnable = manager.getNetworkInfo(  
  66.                 ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();  
  67.         return isWifiDataEnable;  
  68.     }  
  69.       
  70.     /** 
  71.      * 跳转到网络设置页面 
  72.      * @param activity 
  73.      */  
  74.     public static void GoSetting(Activity activity){  
  75.         Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);  
  76.         activity.startActivity(intent);  
  77.     }  
  78.       
  79.     /** 
  80.      * 打开网络设置界面 
  81.      */  
  82.     public static void openSetting(Activity activity) {  
  83.         Intent intent = new Intent("/");  
  84.         ComponentName cn = new ComponentName("com.android.settings""com.android.settings.WirelessSettings");  
  85.         intent.setComponent(cn);  
  86.         intent.setAction("android.intent.action.VIEW");  
  87.         activity.startActivityForResult(intent, 0);  
  88.     }  
  89. }  

PreferencesUtil工具类:
  1. import java.lang.reflect.InvocationTargetException;  
  2. import java.lang.reflect.Method;  
  3. import java.util.Map;  
  4. import java.util.Set;  
  5.   
  6. import android.content.Context;  
  7. import android.content.SharedPreferences;  
  8. import android.content.SharedPreferences.Editor;  
  9.   
  10. /** 
  11.  * SharedPreferences工具类,包含常用的数值获取和存储 
  12.  */  
  13. public class PreferencesUtil {  
  14.   
  15.     private PreferencesUtil(){}  
  16.       
  17.     /** 
  18.      * 默认的SharePreference名称 
  19.      */  
  20.     private static final String SHARED_NAME = "SharedPreferences";  
  21.       
  22.     /** 
  23.      * 查询某个key是否已经存在 
  24.      * @param context   应用程序上下文 
  25.      * @param key   key关键字 
  26.      * @return  包含返回true;反之返回false 
  27.      */  
  28.     public static boolean containsKey(Context context, String key){  
  29.         SharedPreferences sp = getSharedPreferences(context);  
  30.         return sp.contains(key);  
  31.     }  
  32.       
  33.     /** 
  34.      * 返回所有的键值对 
  35.      * @param context 应用程序上下文 
  36.      * @return 
  37.      */  
  38.     public static Map<String, ?> getAll(Context context) {  
  39.         SharedPreferences sp = getSharedPreferences(context);  
  40.         return sp.getAll();  
  41.     }  
  42.       
  43.     /** 
  44.      * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 
  45.      * @param context   应用程序上下文 
  46.      * @param key       key关键字 
  47.      * @param defValue  默认值 
  48.      * @return  返回获取的String值 
  49.      */  
  50.     public static Object get(Context context, String key, Object defaultObject){  
  51.         SharedPreferences sp = getSharedPreferences(context);  
  52.         if (defaultObject instanceof String) {  
  53.             return sp.getString(key, (String) defaultObject);  
  54.         } else if (defaultObject instanceof Integer) {  
  55.             return sp.getInt(key, (Integer) defaultObject);  
  56.         } else if (defaultObject instanceof Boolean) {  
  57.             return sp.getBoolean(key, (Boolean) defaultObject);  
  58.         } else if (defaultObject instanceof Float) {  
  59.             return sp.getFloat(key, (Float) defaultObject);  
  60.         } else if (defaultObject instanceof Long) {  
  61.             return sp.getLong(key, (Long) defaultObject);  
  62.         }  
  63.         return null;  
  64.     }  
  65.       
  66.     /** 
  67.      * 获取Set<String> 集合 
  68.      * @param context   应用程序上下文 
  69.      * @param key       key关键字 
  70.      * @param defValues 默认值 
  71.      * @return  返回Set<String>值 
  72.      */  
  73.     public static Set<String> getStringSet(Context context, String key,  Set<String> defValues){  
  74.         SharedPreferences sp = getSharedPreferences(context);  
  75.         return sp.getStringSet(key, defValues);  
  76.     }  
  77.   
  78.     /** 
  79.      * 保存Set<String>集合的值 
  80.      * @param context   应用程序上下文 
  81.      * @param key       key关键字 
  82.      * @param value     对应值 
  83.      * @return 成功返回true,失败返回false 
  84.      */  
  85.     public static boolean putStringSet(Context context, String key, Set<String> value){  
  86.         return getEditor(context).putStringSet(key, value).commit();  
  87.     }  
  88.       
  89.     /** 
  90.      * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 
  91.      * @param context   应用程序上下文 
  92.      * @param key       key关键字 
  93.      * @param object    对应值 
  94.      * @return 成功返回true,失败返回false 
  95.      */  
  96.     public static void put(Context context, String key, Object object){  
  97.         if (object instanceof String) {  
  98.             getEditor(context).putString(key, (String) object);  
  99.         } else if (object instanceof Integer) {  
  100.             getEditor(context).putInt(key, (Integer) object);  
  101.         } else if (object instanceof Boolean) {  
  102.             getEditor(context).putBoolean(key, (Boolean) object);  
  103.         } else if (object instanceof Float) {  
  104.             getEditor(context).putFloat(key, (Float) object);  
  105.         } else if (object instanceof Long) {  
  106.             getEditor(context).putLong(key, (Long) object);  
  107.         } else {  
  108.             getEditor(context).putString(key, object.toString());  
  109.         }  
  110.         SharedPreferencesCompat.apply(getEditor(context));  
  111.     }  
  112.       
  113.   
  114.       
  115.     /** 
  116.      * 删除关键字key对应的值 
  117.      * @param context   应用程序上下文 
  118.      * @param key       关键字key 
  119.      */  
  120.     public static void removeKey(Context context, String key){  
  121.         getEditor(context).remove(key);  
  122.         SharedPreferencesCompat.apply(getEditor(context));  
  123.     }  
  124.       
  125.     /** 
  126.      * 清除所有的关键字对应的值 
  127.      * @param context   应用程序上下文 
  128.      */  
  129.     public static void clearValues(Context context){  
  130.         getEditor(context).clear();  
  131.         SharedPreferencesCompat.apply(getEditor(context));  
  132.     }  
  133.       
  134.     /** 
  135.      * 获取SharedPreferences对象 
  136.      * @param context   应用程序上下文 
  137.      * @return  返回SharedPreferences对象 
  138.      */  
  139.     private static SharedPreferences getSharedPreferences(Context context){  
  140.         return context.getSharedPreferences(SHARED_NAME, Context.MODE_PRIVATE);  
  141.     }  
  142.       
  143.     /** 
  144.      * 获取Editor对象 
  145.      * @param context   应用程序上下文 
  146.      * @return  返回Editor对象 
  147.      */  
  148.     private static Editor getEditor(Context context){   
  149.         return getSharedPreferences(context).edit();  
  150.     }  
  151.       
  152.     /** 
  153.      * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 
  154.      */  
  155.     private static class SharedPreferencesCompat {  
  156.         private static final Method sApplyMethod = findApplyMethod();  
  157.           
  158.         /** 
  159.          * 反射查找apply的方法 
  160.          * @return 
  161.          */  
  162.         @SuppressWarnings({ "unchecked""rawtypes" })  
  163.         private static Method findApplyMethod() {  
  164.             try {  
  165.                 Class clz = SharedPreferences.Editor.class;  
  166.                 return clz.getMethod("apply");  
  167.             } catch (NoSuchMethodException e) {  
  168.                 e.printStackTrace();  
  169.             }  
  170.             return null;  
  171.         }  
  172.           
  173.         /** 
  174.          * 如果找到则使用apply执行,否则使用commit 
  175.          * @param editor 
  176.          */  
  177.         public static void apply(SharedPreferences.Editor editor) {  
  178.             try {  
  179.                 if (sApplyMethod != null) {  
  180.                     sApplyMethod.invoke(editor);  
  181.                     return;  
  182.                 }  
  183.             } catch (IllegalArgumentException e) {  
  184.                 e.printStackTrace();  
  185.             } catch (IllegalAccessException e) {  
  186.                 e.printStackTrace();  
  187.             } catch (InvocationTargetException e) {  
  188.                 e.printStackTrace();  
  189.             }  
  190.             editor.commit();  
  191.         }  
  192.     }  
  193. }  
ReflectUtil工具类:
  1. import java.lang.reflect.Field;  
  2. import java.lang.reflect.Method;  
  3. import java.lang.reflect.Modifier;  
  4. import java.lang.reflect.Type;  
  5.   
  6. import android.text.TextUtils;  
  7.   
  8. /** 
  9.  * 反射工具类 
  10.  */  
  11. public class ReflectUtil {  
  12.   
  13.     private ReflectUtil(){}  
  14.       
  15.     /** 
  16.      * 设置字段值 
  17.      * @param t     对应实体 
  18.      * @param field     字段 
  19.      * @param fieldName     字段名称 
  20.      * @param value         字段值 
  21.      */  
  22.     public static<T> void setFieldValue(T t,Field field, String fieldName, String value){  
  23.         String name = field.getName();  
  24.         //判断该字段是否和目标字段相同  
  25.         if (!fieldName.equals(name)) {  
  26.             return;  
  27.         }  
  28.         //获取字段的类型  
  29.         Type type = field.getType();  
  30.         //获取字段的修饰符号码  
  31.         int typeCode = field.getModifiers();  
  32.         //获取字段类型的名称  
  33.         String typeName = type.toString();  
  34.         try {  
  35.             switch (typeName) {  
  36.             case "class java.lang.String":  
  37.                 if (Modifier.isPublic(typeCode)) {  
  38.                     field.set(t, value);  
  39.                 } else {  
  40.                     Method method = t.getClass().getMethod("set" + getMethodName(fieldName), String.class);  
  41.                     method.invoke(t, value);  
  42.                 }  
  43.                 break;  
  44.             case "double":  
  45.                 if(Modifier.isPublic(typeCode)){  
  46.                     field.setDouble(t, Double.valueOf(value));  
  47.                 }else{  
  48.                     Method method = t.getClass().getMethod("set" + getMethodName(fieldName),double.class);  
  49.                     method.invoke(t, Double.valueOf(value));  
  50.                 }  
  51.                 break;  
  52.             case "int":  
  53.                 if(Modifier.isPublic(typeCode)){  
  54.                     field.setInt(t, Integer.valueOf(value));  
  55.                 }else{  
  56.                     Method method = t.getClass().getMethod("set" + getMethodName(fieldName),int.class);  
  57.                     method.invoke(t, Integer.valueOf(value));  
  58.                 }  
  59.                 break;  
  60.             case "float":  
  61.                 if(Modifier.isPublic(typeCode)){  
  62.                     field.setFloat(t, Float.valueOf(value));  
  63.                 }else{  
  64.                     Method method = t.getClass().getMethod("set" + getMethodName(fieldName), float.class);  
  65.                     method.invoke(t, Float.valueOf(value));  
  66.                 }  
  67.                 break;  
  68.             }  
  69.         } catch (IllegalAccessException e) {  
  70.             e.printStackTrace();  
  71.         } catch (IllegalArgumentException e) {  
  72.             e.printStackTrace();  
  73.         } catch (NoSuchMethodException e) {  
  74.             e.printStackTrace();  
  75.         } catch (Exception e) {  
  76.             e.printStackTrace();  
  77.         }   
  78.     }  
  79.       
  80.     /** 
  81.      * 把字段名称第一个字母换成大写 
  82.      * @param fieldName     字段名称 
  83.      * @return 
  84.      * @throws Exception    异常处理 
  85.      */  
  86.      private static String getMethodName(String fieldName) throws Exception{    
  87.          byte[] items = fieldName.getBytes();  
  88.          items[0] = (byte) ((char)items[0] - 'a' + 'A');  
  89.          return new String(items);  
  90.      }  
  91.        
  92.      /** 
  93.       * 根据字段名称获取指定Field字段 
  94.       * @param clazz        实体的字节码文件 
  95.       * @param filedName        字段的名称 
  96.       * @return 返回对应的字符按Field或者返回null 
  97.       */  
  98.      public static Field getField(Class<?> clazz, String filedName){  
  99.          if (clazz == null || TextUtils.isEmpty(filedName)) {  
  100.              throw new IllegalArgumentException("params is illegal");  
  101.          }  
  102.          Field[] fields = clazz.getDeclaredFields();  
  103.          return getFieldByName(fields, filedName);  
  104.      }  
  105.        
  106.      /** 
  107.       * 根据字段名称获取指定的Field 
  108.       * @param fields   字段集合 
  109.       * @param fieldName     字段名称 
  110.       * @return 返回对应的Field字段或者返回null 
  111.       */  
  112.      public static Field getFieldByName(Field[] fields, String fieldName){  
  113.          if (fields == null || fields.length == 0 || TextUtils.isEmpty(fieldName)) {  
  114.              throw new IllegalArgumentException("params is illegal");  
  115.          }  
  116.          for (Field field : fields) {  
  117.             String name = field.getName();  
  118.             //判断该字段是否和目标字段相同  
  119.             if (fieldName.equals(name)) {  
  120.                 return field;  
  121.             }  
  122.         }  
  123.          return null;  
  124.      }  
  125.        
  126.      /** 
  127.       * 判断该字段是否为FieldName对应字段 
  128.       * @param field        Field字段 
  129.       * @param fieldName        目标字段 
  130.       * @return 是,返回true;否,返回false 
  131.       */  
  132.      public static boolean isFiledWithName(Field field, String fieldName){  
  133.         if(field == null || TextUtils.isEmpty(fieldName)){  
  134.             throw new IllegalArgumentException("params is illegal");  
  135.         }   
  136.         if (fieldName.equals(field.getName())) {  
  137.             return true;  
  138.         }   
  139.         return false;  
  140.      }  
  141. }  
SDCardUtil工具类:
  1. import java.io.File;  
  2.   
  3. import android.annotation.SuppressLint;  
  4. import android.content.Context;  
  5. import android.os.Environment;  
  6. import android.os.StatFs;  
  7.   
  8. /** 
  9.  * SD卡工具类,包含SD卡状态、路径、容量大小 
  10.  */  
  11. public class SDCardUtil {  
  12.   
  13.     private SDCardUtil(){}  
  14.       
  15.     /** 
  16.      * 判断SD卡是否可用 
  17.      * @return 
  18.      * ture:可用;false:不可用 
  19.      */  
  20.     public static boolean isSDCardEnable(){  
  21.         return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);  
  22.     }  
  23.       
  24.     /** 
  25.      * 获取SD卡路径 
  26.      * @return 
  27.      * SD卡存在返回正常路径;SD卡不存在返回"" 
  28.      */  
  29.     public static String getSDCradPath(){  
  30.         if (isSDCardEnable()) {  
  31.             return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;  
  32.         } else {  
  33.             return "";  
  34.         }  
  35.     }  
  36.       
  37.     /** 
  38.      * 获取SD卡路径文件 
  39.      * @return 
  40.      * SD卡存在返回正常路径;SD卡不存在返回null 
  41.      */  
  42.     public static File getSDCardFile(){  
  43.         if(isSDCardEnable()){  
  44.             return Environment.getExternalStorageDirectory();  
  45.         }else{  
  46.             return null;  
  47.         }  
  48.     }  
  49.       
  50.     /** 
  51.      * 获取SD卡DownloadCache路径 
  52.      * @return 
  53.      * SD卡存在返回正常路径;SD卡不存在返回"" 
  54.      */  
  55.     public static String getSDCardDownloadCachePath(){  
  56.         if(isSDCardEnable()){  
  57.             return Environment.getDownloadCacheDirectory().getAbsolutePath() + File.separator;  
  58.         }else{  
  59.             return "";  
  60.         }  
  61.     }  
  62.       
  63.     /** 
  64.      * 获取SD卡DownloadCache路径文件 
  65.      * @return 
  66.      * SD卡存在返回正常路径;SD卡不存在返回null 
  67.      */  
  68.     public static File getSDCardDownloadCacheFile(){  
  69.         if(isSDCardEnable()){  
  70.             return Environment.getDownloadCacheDirectory();  
  71.         }else{  
  72.             return null;  
  73.         }  
  74.     }  
  75.       
  76.     /** 
  77.      * 获取系统存储路径 
  78.      * @return 
  79.      * SD卡存在返回正常路径;SD卡不存在返回"" 
  80.      */  
  81.     public static String getSDCardRootPath(){  
  82.         if(isSDCardEnable()){  
  83.             return Environment.getRootDirectory().getAbsolutePath() + File.separator;  
  84.         }else{  
  85.             return "";  
  86.         }  
  87.     }  
  88.       
  89.     /** 
  90.      * 获取系统存储路径文件 
  91.      * @return 
  92.      * SD卡存在返回正常路径;SD卡不存在返回null 
  93.      */  
  94.     public static File getSDCardRootFile(){  
  95.         if(isSDCardEnable()){  
  96.             return Environment.getRootDirectory();  
  97.         }else{  
  98.             return null;  
  99.         }  
  100.     }  
  101.       
  102.     /** 
  103.      * 获取应用程序的/data/data目录 
  104.      * @param context 
  105.      * @return 
  106.      */  
  107.     public static String getDataFilePath(Context context){  
  108.         return context.getFilesDir().getAbsolutePath() + File.separator;  
  109.     }  
  110.       
  111.     /** 
  112.      * /data/data/PackageName/cache的路径 
  113.      * @param context 
  114.      * @return 
  115.      */  
  116.     public static String getDataCachePath(Context context){  
  117.         return context.getCacheDir().getAbsolutePath() + File.separator;  
  118.     }  
  119.       
  120.     /** 
  121.      * 获取SD卡大小 
  122.      * @return 
  123.      * SD卡存在返回大小;SD卡不存在返回-1 
  124.      */  
  125.     @SuppressWarnings("deprecation")  
  126.     @SuppressLint("NewApi")  
  127.     public static long getSDCardSize(){  
  128.         if (isSDCardEnable()) {  
  129.             StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);  
  130.             if (android.os.Build.VERSION.SDK_INT < 18) {  
  131.                 int blockSize = statFs.getBlockSize();  
  132.                 int blockCount = statFs.getBlockCount();  
  133.                 return blockSize * blockCount;  
  134.             } else {  
  135.                 long blockSize = statFs.getBlockSizeLong();  
  136.                 long blockCount = statFs.getBlockCountLong();  
  137.                 return blockSize * blockCount;  
  138.             }  
  139.         }  
  140.         return -1;  
  141.     }  
  142.       
  143.     /** 
  144.      * 获取SD卡可用大小 
  145.      * @return 
  146.      * SD卡存在返回大小;SD卡不存在返回-1 
  147.      */  
  148.     @SuppressWarnings("deprecation")  
  149.     @SuppressLint("NewApi")  
  150.     public static long getSDCardAvailableSize(){  
  151.         if (isSDCardEnable()) {  
  152.             StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);  
  153.             if (android.os.Build.VERSION.SDK_INT < 18) {  
  154.                 int blockSize = statFs.getBlockSize();  
  155.                 int blockCount = statFs.getAvailableBlocks();  
  156.                 return blockSize * blockCount;  
  157.             } else {  
  158.                 long blockSize = statFs.getBlockSizeLong();  
  159.                 long blockCount = statFs.getAvailableBlocksLong();  
  160.                 return blockSize * blockCount;  
  161.             }  
  162.         }  
  163.         return -1;  
  164.     }  
  165.       
  166.     /**  
  167.      * 获得手机内存总大小  
  168.      * @return  
  169.      */  
  170.     @SuppressWarnings("deprecation")  
  171.     @SuppressLint("NewApi")  
  172.     public long getRomTotalSize() {   
  173.         File path = Environment.getDataDirectory();  
  174.         StatFs statFs = new StatFs(path.getPath());  
  175.         if (android.os.Build.VERSION.SDK_INT < 18) {  
  176.             int blockSize = statFs.getBlockSize();  
  177.             int blockCount = statFs.getBlockCount();  
  178.             return blockSize * blockCount;  
  179.         } else {  
  180.             long blockSize = statFs.getBlockSizeLong();  
  181.             long blockCount = statFs.getBlockCountLong();  
  182.             return blockSize * blockCount;  
  183.         }  
  184.     }  
  185.       
  186.     /**  
  187.      * 获得手机可用内存  
  188.      * @return  
  189.      */  
  190.     @SuppressWarnings("deprecation")  
  191.     @SuppressLint("NewApi")  
  192.     public long getRomAvailableSize() {    
  193.         File path = Environment.getDataDirectory();  
  194.         StatFs statFs = new StatFs(path.getPath());  
  195.         if (android.os.Build.VERSION.SDK_INT < 18) {  
  196.             int blockSize = statFs.getBlockSize();  
  197.             int blockCount = statFs.getAvailableBlocks();  
  198.             return blockSize * blockCount;  
  199.         } else {  
  200.             long blockSize = statFs.getBlockSizeLong();  
  201.             long blockCount = statFs.getAvailableBlocksLong();  
  202.             return blockSize * blockCount;  
  203.         }  
  204.     }  
  205. }  
ScreenUtil工具类:

  1. import android.app.Activity;  
  2. import android.content.Context;  
  3. import android.graphics.Bitmap;  
  4. import android.graphics.Rect;  
  5. import android.util.DisplayMetrics;  
  6. import android.view.View;  
  7. import android.view.WindowManager;  
  8.   
  9. /** 
  10.  * 屏幕工具类,涉及到屏幕宽度、高度、密度比、(像素、dp、sp)之间的转换等。 
  11.  */  
  12. public class ScreenUtil {  
  13.   
  14.     private ScreenUtil(){}  
  15.       
  16.     /** 
  17.      * 获取屏幕宽度,单位为px 
  18.      * @param context   应用程序上下文 
  19.      * @return 屏幕宽度,单位px 
  20.      */  
  21.     public static int getScreenWidth(Context context){  
  22.         return getDisplayMetrics(context).widthPixels;  
  23.     }  
  24.       
  25.     /** 
  26.      * 获取屏幕高度,单位为px 
  27.      * @param context   应用程序上下文 
  28.      * @return 屏幕高度,单位px 
  29.      */  
  30.     public static int getScreenHeight(Context context){  
  31.         return getDisplayMetrics(context).heightPixels;  
  32.     }  
  33.       
  34.     /** 
  35.      * 获取系统dp尺寸密度值 
  36.      * @param context   应用程序上下文 
  37.      * @return 
  38.      */  
  39.     public static float getDensity(Context context){  
  40.         return getDisplayMetrics(context).density;  
  41.     }  
  42.       
  43.     /** 
  44.      * 获取系统字体sp密度值 
  45.      * @param context   应用程序上下文 
  46.      * @return 
  47.      */  
  48.     public static float getScaledDensity(Context context){  
  49.         return getDisplayMetrics(context).scaledDensity;  
  50.     }  
  51.       
  52.     /** 
  53.      * dip转换为px大小 
  54.      * @param context   应用程序上下文 
  55.      * @param dpValue   dp值 
  56.      * @return  转换后的px值 
  57.      */  
  58.     public static int dp2px(Context context, int dpValue){  
  59.         return (int) (dpValue * getDensity(context) + 0.5f);  
  60.     }  
  61.       
  62.     /** 
  63.      * px转换为dp值 
  64.      * @param context   应用程序上下文 
  65.      * @param pxValue   px值 
  66.      * @return  转换后的dp值 
  67.      */  
  68.     public static int px2dp(Context context, int pxValue){  
  69.         return (int) (pxValue / getDensity(context) + 0.5f);  
  70.     }  
  71.       
  72.     /** 
  73.      * sp转换为px 
  74.      * @param context   应用程序上下文 
  75.      * @param spValue   sp值 
  76.      * @return      转换后的px值 
  77.      */  
  78.     public static int sp2px(Context context, int spValue){  
  79.         return (int) (spValue * getScaledDensity(context) + 0.5f);  
  80.     }  
  81.       
  82.     /** 
  83.      * px转换为sp 
  84.      * @param context   应用程序上下文 
  85.      * @param pxValue   px值 
  86.      * @return  转换后的sp值 
  87.      */  
  88.     public static int px2sp(Context context, int pxValue){  
  89.         return (int) (pxValue / getScaledDensity(context) + 0.5f);  
  90.     }  
  91.       
  92.     /**  
  93.      * 获得状态栏的高度  
  94.      *   
  95.      * @param context  
  96.      * @return  
  97.      */    
  98.     public static int getStatusHeight(Context context){  
  99.         int statusHeight = -1;    
  100.         try {  
  101.             Class<?> clazz = Class.forName("com.android.internal.R$dimen");  
  102.             Object object = clazz.newInstance();  
  103.             int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());  
  104.             statusHeight = context.getResources().getDimensionPixelSize(height);  
  105.         } catch (Exception e) {  
  106.             e.printStackTrace();  
  107.         }  
  108.         return statusHeight;  
  109.     }  
  110.       
  111.     /**  
  112.      * 获取当前屏幕截图,包含状态栏  
  113.      * @param activity  
  114.      * @return  
  115.      */   
  116.      public static Bitmap snapShotWithStatusBar(Activity activity){    
  117.          View decorView = activity.getWindow().getDecorView();  
  118.          decorView.setDrawingCacheEnabled(true);  
  119.          decorView.buildDrawingCache();  
  120.          Bitmap bmp = decorView.getDrawingCache();  
  121.          int width = getScreenWidth(activity);  
  122.          int height = getScreenHeight(activity);  
  123.          Bitmap bitmap = null;  
  124.          bitmap = Bitmap.createBitmap(bmp, 00, width, height);  
  125.          decorView.destroyDrawingCache();  
  126.          return bitmap;  
  127.      }  
  128.       
  129.      /**  
  130.       * 获取当前屏幕截图,不包含状态栏  
  131.       * @param activity  
  132.       * @return  
  133.       */    
  134.      public static Bitmap snapShotWithoutStatusBar(Activity activity){    
  135.          View decorView = activity.getWindow().getDecorView();  
  136.          decorView.setDrawingCacheEnabled(true);  
  137.          decorView.buildDrawingCache();  
  138.          Bitmap bmp = decorView.getDrawingCache();  
  139.          Rect frame = new Rect();  
  140.          activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
  141.          int statusHeight = frame.top;  
  142.            
  143.          int width = getScreenWidth(activity);  
  144.          int height = getScreenHeight(activity);  
  145.          Bitmap bitmap = null;  
  146.          bitmap = Bitmap.createBitmap(bmp, 0, statusHeight, width, height - statusHeight);  
  147.          decorView.destroyDrawingCache();  
  148.          return bitmap;   
  149.      }  
  150.        
  151.     /** 
  152.      * 获取DisplayMetrics对象 
  153.      * @param context   应用程序上下文 
  154.      * @return 
  155.      */  
  156.     public static DisplayMetrics getDisplayMetrics(Context context){  
  157.         WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);  
  158.         DisplayMetrics metrics = new DisplayMetrics();  
  159.         manager.getDefaultDisplay().getMetrics(metrics);  
  160.         return metrics;  
  161.     }  
  162. }  
XmlUtil工具类:

  1. import java.io.ByteArrayInputStream;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.lang.reflect.Field;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import org.xmlpull.v1.XmlPullParser;  
  9. import org.xmlpull.v1.XmlPullParserException;  
  10.   
  11. import android.text.TextUtils;  
  12. import android.util.Xml;  
  13.   
  14. /** 
  15.  * XML文件工具类,包含:将xml文件解析成实体集合、获取xml标签值、将标签值解析成实体集合 
  16.  */  
  17. public class XMLUtil {  
  18.   
  19.     private XMLUtil(){}  
  20.       
  21.     /*- 
  22.      * XML文件解析成实体,不涉及到标签的属性值。 
  23.      * @param xml   xml字符串文件 
  24.      * @param clazz     对应实体的class文件 
  25.      * @param tagEntity      
  26.      * 开始解析实体的标签,例如下面的实例中就是student<br> 
  27.      * < person ><br> 
  28.      *      < student ><br> 
  29.      *              < name >Lucy< /name ><br> 
  30.      *              < age >21< /age ><br> 
  31.      *      < /student ><br> 
  32.      * < /person ><br> 
  33.      * @return      返回解析的对应实体文件 
  34.      */  
  35.     public static<T> List<T> xmlToObject(String xml, Class<T> clazz, String tagEntity){  
  36.         List<T> list = null;  
  37.         XmlPullParser xmlPullParser = Xml.newPullParser();  
  38.         InputStream inputStream = new ByteArrayInputStream(xml.getBytes());  
  39.         try {  
  40.             xmlPullParser.setInput(inputStream, "utf-8");  
  41.             Field[] fields = clazz.getDeclaredFields();  
  42.             int type = xmlPullParser.getEventType();  
  43.             String lastTag = "";  
  44.             T t = null;  
  45.             while (type != XmlPullParser.END_DOCUMENT) {  
  46.                 switch (type) {  
  47.                 case XmlPullParser.START_DOCUMENT:  
  48.                     list = new ArrayList<T>();  
  49.                     break;  
  50.                 case XmlPullParser.START_TAG:  
  51.                     String tagName = xmlPullParser.getName();  
  52.                     if(tagEntity.equals(tagName)){  
  53.                         t = clazz.newInstance();  
  54.                         lastTag = tagEntity;  
  55.                     }else if(tagEntity.equals(lastTag)){  
  56.                         String textValue = xmlPullParser.nextText();  
  57.                         String fieldName = xmlPullParser.getName();  
  58.                         for(Field field : fields){  
  59.                             ReflectUtil.setFieldValue(t,field,fieldName,textValue);  
  60.                         }  
  61.                     }  
  62.                     break;  
  63.                 case XmlPullParser.END_TAG:  
  64.                     tagName = xmlPullParser.getName();  
  65.                     if(tagEntity.equals(tagName)){  
  66.                         list.add(t);  
  67.                         lastTag = "";  
  68.                     }  
  69.                     break;  
  70.                 case XmlPullParser.END_DOCUMENT:  
  71.                     break;  
  72.                 }  
  73.             }  
  74.         } catch (XmlPullParserException e) {  
  75.             e.printStackTrace();  
  76.         } catch (InstantiationException e) {  
  77.             e.printStackTrace();  
  78.         } catch (IllegalAccessException e) {  
  79.             e.printStackTrace();  
  80.         } catch (IOException e) {  
  81.             e.printStackTrace();  
  82.         }  
  83.         return list;  
  84.     }  
  85.       
  86.     /** 
  87.      * 获取xml字符串标签中的属性值 
  88.      * @param xml   xml字符串 
  89.      * @param clazz     转换成对应的实体 
  90.      * @param tagName   实体对应xml字符串的起始标签,如下面实例中的person标签<br> 
  91.      * < person name="Lucy" age="12"><br> 
  92.      *      < student ><br> 
  93.      *              < name >Lucy< /name ><br> 
  94.      *              < age >21< /age ><br> 
  95.      *      < /student ><br> 
  96.      * < /person ><br> 
  97.      * @return  返回属性值组成的List对象集合。 
  98.      */  
  99.     public static<T> List<T> attributeToObject(String xml, Class<T> clazz, String tagName){  
  100.         if(TextUtils.isEmpty(tagName))return null;  
  101.         List<T> list = null;  
  102.         XmlPullParser xmlPullParser = Xml.newPullParser();  
  103.         InputStream inputStream = new ByteArrayInputStream(xml.getBytes());  
  104.         try {  
  105.             xmlPullParser.setInput(inputStream, "utf-8");  
  106.             int type = xmlPullParser.getEventType();  
  107.             T t = null;  
  108.             while(type != XmlPullParser.END_DOCUMENT){  
  109.                 switch(type){  
  110.                 case XmlPullParser.START_DOCUMENT:  
  111.                     list = new ArrayList<T>();  
  112.                     break;  
  113.                 case XmlPullParser.START_TAG:  
  114.                     if(tagName.equals(xmlPullParser.getName())){  
  115.                         t = clazz.newInstance();  
  116.                         Field[] fields = clazz.getDeclaredFields();  
  117.                         for(Field field : fields){  
  118.                             String fieldName = field.getName();  
  119.                             for(int index = 0;index < xmlPullParser.getAttributeCount();index++){  
  120.                                 if(fieldName.equals(xmlPullParser.getAttributeName(index))){  
  121.                                     ReflectUtil.setFieldValue(t,field,fieldName,xmlPullParser.getAttributeValue(index));  
  122.                                 }  
  123.                             }  
  124.                         }  
  125.                     }  
  126.                     break;  
  127.                 case XmlPullParser.END_TAG:  
  128.                     if(tagName.equals(xmlPullParser.getName())){  
  129.                         list.add(t);  
  130.                     }  
  131.                     break;  
  132.                 case XmlPullParser.END_DOCUMENT:  
  133.                     break;  
  134.                 }  
  135.                 type = xmlPullParser.next();  
  136.             }  
  137.         }catch(Exception ex){  
  138.             ex.printStackTrace();  
  139.         }  
  140.         return list;  
  141.           
  142.     }  
  143.       
  144.     /** 
  145.      * 获取Xml文件中的属性值 
  146.      * @param xml   xml文件字符串 
  147.      * @param tagName       标签名称 
  148.      * @param attributeName     属性名称 
  149.      * @return  返回获取的值,或者null 
  150.      */  
  151.     public static String getTagAttribute(String xml, String tagName, String attributeName){  
  152.         if(TextUtils.isEmpty(tagName) || TextUtils.isEmpty(attributeName)){  
  153.             throw new IllegalArgumentException("请填写标签名称或属性名称");  
  154.         }  
  155.         XmlPullParser xmlPullParser = Xml.newPullParser();  
  156.         InputStream inputStream = new ByteArrayInputStream(xml.getBytes());  
  157.         try {  
  158.             xmlPullParser.setInput(inputStream, "utf-8");  
  159.             int type = xmlPullParser.getEventType();  
  160.             while(type != XmlPullParser.END_DOCUMENT){  
  161.                 switch(type){  
  162.                 case XmlPullParser.START_TAG:  
  163.                     if(tagName.equals(xmlPullParser.getName())){  
  164.                         for(int i=0; i < xmlPullParser.getAttributeCount();i++){  
  165.                             if(attributeName.equals(xmlPullParser.getAttributeName(i))){  
  166.                                 return xmlPullParser.getAttributeValue(i);  
  167.                             }  
  168.                         }  
  169.                     }  
  170.                     break;  
  171.                 }  
  172.                 type = xmlPullParser.next();  
  173.             }  
  174.         } catch (XmlPullParserException e) {  
  175.             e.printStackTrace();  
  176.         } catch (IOException e) {  
  177.             e.printStackTrace();  
  178.         }  
  179.         return null;  
  180.     }  
  181. }  

ColorUtil工具类:

  1. public class ColorsUtil {  
  2.   
  3.     private ColorsUtil() {  
  4.         throw new Error("Do not need instantiate!");  
  5.     }  
  6.   
  7.     /** 
  8.      * 白色 
  9.      */  
  10.     public static final int WHITE = 0xffffffff;  
  11.   
  12.     /** 
  13.      * 白色 - 半透明 
  14.      */  
  15.     public static final int WHITE_TRANSLUCENT = 0x80ffffff;  
  16.   
  17.     /** 
  18.      * 黑色 
  19.      */  
  20.     public static final int BLACK = 0xff000000;  
  21.   
  22.     /** 
  23.      * 黑色 - 半透明 
  24.      */  
  25.     public static final int BLACK_TRANSLUCENT = 0x80000000;  
  26.   
  27.     /** 
  28.      * 透明 
  29.      */  
  30.     public static final int TRANSPARENT = 0x00000000;  
  31.   
  32.     /** 
  33.      * 红色 
  34.      */  
  35.     public static final int RED = 0xffff0000;  
  36.   
  37.     /** 
  38.      * 红色 - 半透明 
  39.      */  
  40.     public static final int RED_TRANSLUCENT = 0x80ff0000;  
  41.   
  42.     /** 
  43.      * 红色 - 深的 
  44.      */  
  45.     public static final int RED_DARK = 0xff8b0000;  
  46.   
  47.     /** 
  48.      * 红色 - 深的 - 半透明 
  49.      */  
  50.     public static final int RED_DARK_TRANSLUCENT = 0x808b0000;  
  51.   
  52.     /** 
  53.      * 绿色 
  54.      */  
  55.     public static final int GREEN = 0xff00ff00;  
  56.   
  57.     /** 
  58.      * 绿色 - 半透明 
  59.      */  
  60.     public static final int GREEN_TRANSLUCENT = 0x8000ff00;  
  61.   
  62.     /** 
  63.      * 绿色 - 深的 
  64.      */  
  65.     public static final int GREEN_DARK = 0xff003300;  
  66.   
  67.     /** 
  68.      * 绿色 - 深的 - 半透明 
  69.      */  
  70.     public static final int GREEN_DARK_TRANSLUCENT = 0x80003300;  
  71.   
  72.     /** 
  73.      * 绿色 - 浅的 
  74.      */  
  75.     public static final int GREEN_LIGHT = 0xffccffcc;  
  76.   
  77.     /** 
  78.      * 绿色 - 浅的 - 半透明 
  79.      */  
  80.     public static final int GREEN_LIGHT_TRANSLUCENT = 0x80ccffcc;  
  81.   
  82.     /** 
  83.      * 蓝色 
  84.      */  
  85.     public static final int BLUE = 0xff0000ff;  
  86.   
  87.     /** 
  88.      * 蓝色 - 半透明 
  89.      */  
  90.     public static final int BLUE_TRANSLUCENT = 0x800000ff;  
  91.   
  92.     /** 
  93.      * 蓝色 - 深的 
  94.      */  
  95.     public static final int BLUE_DARK = 0xff00008b;  
  96.   
  97.     /** 
  98.      * 蓝色 - 深的 - 半透明 
  99.      */  
  100.     public static final int BLUE_DARK_TRANSLUCENT = 0x8000008b;  
  101.   
  102.     /** 
  103.      * 蓝色 - 浅的 
  104.      */  
  105.     public static final int BLUE_LIGHT = 0xff36a5E3;  
  106.   
  107.     /** 
  108.      * 蓝色 - 浅的 - 半透明 
  109.      */  
  110.     public static final int BLUE_LIGHT_TRANSLUCENT = 0x8036a5E3;  
  111.   
  112.     /** 
  113.      * 天蓝 
  114.      */  
  115.     public static final int SKYBLUE = 0xff87ceeb;  
  116.   
  117.     /** 
  118.      * 天蓝 - 半透明 
  119.      */  
  120.     public static final int SKYBLUE_TRANSLUCENT = 0x8087ceeb;  
  121.   
  122.     /** 
  123.      * 天蓝 - 深的 
  124.      */  
  125.     public static final int SKYBLUE_DARK = 0xff00bfff;  
  126.   
  127.     /** 
  128.      * 天蓝 - 深的 - 半透明 
  129.      */  
  130.     public static final int SKYBLUE_DARK_TRANSLUCENT = 0x8000bfff;  
  131.   
  132.     /** 
  133.      * 天蓝 - 浅的 
  134.      */  
  135.     public static final int SKYBLUE_LIGHT = 0xff87cefa;  
  136.   
  137.     /** 
  138.      * 天蓝 - 浅的 - 半透明 
  139.      */  
  140.     public static final int SKYBLUE_LIGHT_TRANSLUCENT = 0x8087cefa;  
  141.   
  142.     /** 
  143.      * 灰色 
  144.      */  
  145.     public static final int GRAY = 0xff969696;  
  146.   
  147.     /** 
  148.      * 灰色 - 半透明 
  149.      */  
  150.     public static final int GRAY_TRANSLUCENT = 0x80969696;  
  151.   
  152.     /** 
  153.      * 灰色 - 深的 
  154.      */  
  155.     public static final int GRAY_DARK = 0xffa9a9a9;  
  156.   
  157.     /** 
  158.      * 灰色 - 深的 - 半透明 
  159.      */  
  160.     public static final int GRAY_DARK_TRANSLUCENT = 0x80a9a9a9;  
  161.   
  162.     /** 
  163.      * 灰色 - 暗的 
  164.      */  
  165.     public static final int GRAY_DIM = 0xff696969;  
  166.   
  167.     /** 
  168.      * 灰色 - 暗的 - 半透明 
  169.      */  
  170.     public static final int GRAY_DIM_TRANSLUCENT = 0x80696969;  
  171.   
  172.     /** 
  173.      * 灰色 - 浅的 
  174.      */  
  175.     public static final int GRAY_LIGHT = 0xffd3d3d3;  
  176.   
  177.     /** 
  178.      * 灰色 - 浅的 - 半透明 
  179.      */  
  180.     public static final int GRAY_LIGHT_TRANSLUCENT = 0x80d3d3d3;  
  181.   
  182.     /** 
  183.      * 橙色 
  184.      */  
  185.     public static final int ORANGE = 0xffffa500;  
  186.   
  187.     /** 
  188.      * 橙色 - 半透明 
  189.      */  
  190.     public static final int ORANGE_TRANSLUCENT = 0x80ffa500;  
  191.   
  192.     /** 
  193.      * 橙色 - 深的 
  194.      */  
  195.     public static final int ORANGE_DARK = 0xffff8800;  
  196.   
  197.     /** 
  198.      * 橙色 - 深的 - 半透明 
  199.      */  
  200.     public static final int ORANGE_DARK_TRANSLUCENT = 0x80ff8800;  
  201.   
  202.     /** 
  203.      * 橙色 - 浅的 
  204.      */  
  205.     public static final int ORANGE_LIGHT = 0xffffbb33;  
  206.   
  207.     /** 
  208.      * 橙色 - 浅的 - 半透明 
  209.      */  
  210.     public static final int ORANGE_LIGHT_TRANSLUCENT = 0x80ffbb33;  
  211.   
  212.     /** 
  213.      * 金色 
  214.      */  
  215.     public static final int GOLD = 0xffffd700;  
  216.   
  217.     /** 
  218.      * 金色 - 半透明 
  219.      */  
  220.     public static final int GOLD_TRANSLUCENT = 0x80ffd700;  
  221.   
  222.     /** 
  223.      * 粉色 
  224.      */  
  225.     public static final int PINK = 0xffffc0cb;  
  226.   
  227.     /** 
  228.      * 粉色 - 半透明 
  229.      */  
  230.     public static final int PINK_TRANSLUCENT = 0x80ffc0cb;  
  231.   
  232.     /** 
  233.      * 紫红色 
  234.      */  
  235.     public static final int FUCHSIA = 0xffff00ff;  
  236.   
  237.     /** 
  238.      * 紫红色 - 半透明 
  239.      */  
  240.     public static final int FUCHSIA_TRANSLUCENT = 0x80ff00ff;  
  241.   
  242.     /** 
  243.      * 灰白色 
  244.      */  
  245.     public static final int GRAYWHITE = 0xfff2f2f2;  
  246.   
  247.     /** 
  248.      * 灰白色 - 半透明 
  249.      */  
  250.     public static final int GRAYWHITE_TRANSLUCENT = 0x80f2f2f2;  
  251.   
  252.     /** 
  253.      * 紫色 
  254.      */  
  255.     public static final int PURPLE = 0xff800080;  
  256.   
  257.     /** 
  258.      * 紫色 - 半透明 
  259.      */  
  260.     public static final int PURPLE_TRANSLUCENT = 0x80800080;  
  261.   
  262.     /** 
  263.      * 青色 
  264.      */  
  265.     public static final int CYAN = 0xff00ffff;  
  266.   
  267.     /** 
  268.      * 青色 - 半透明 
  269.      */  
  270.     public static final int CYAN_TRANSLUCENT = 0x8000ffff;  
  271.   
  272.     /** 
  273.      * 青色 - 深的 
  274.      */  
  275.     public static final int CYAN_DARK = 0xff008b8b;  
  276.   
  277.     /** 
  278.      * 青色 - 深的 - 半透明 
  279.      */  
  280.     public static final int CYAN_DARK_TRANSLUCENT = 0x80008b8b;  
  281.   
  282.     /** 
  283.      * 黄色 
  284.      */  
  285.     public static final int YELLOW = 0xffffff00;  
  286.   
  287.     /** 
  288.      * 黄色 - 半透明 
  289.      */  
  290.     public static final int YELLOW_TRANSLUCENT = 0x80ffff00;  
  291.   
  292.     /** 
  293.      * 黄色 - 浅的 
  294.      */  
  295.     public static final int YELLOW_LIGHT = 0xffffffe0;  
  296.   
  297.     /** 
  298.      * 黄色 - 浅的 - 半透明 
  299.      */  
  300.     public static final int YELLOW_LIGHT_TRANSLUCENT = 0x80ffffe0;  
  301.   
  302.     /** 
  303.      * 巧克力色 
  304.      */  
  305.     public static final int CHOCOLATE = 0xffd2691e;  
  306.   
  307.     /** 
  308.      * 巧克力色 - 半透明 
  309.      */  
  310.     public static final int CHOCOLATE_TRANSLUCENT = 0x80d2691e;  
  311.   
  312.     /** 
  313.      * 番茄色 
  314.      */  
  315.     public static final int TOMATO = 0xffff6347;  
  316.   
  317.     /** 
  318.      * 番茄色 - 半透明 
  319.      */  
  320.     public static final int TOMATO_TRANSLUCENT = 0x80ff6347;  
  321.   
  322.     /** 
  323.      * 橙红色 
  324.      */  
  325.     public static final int ORANGERED = 0xffff4500;  
  326.   
  327.     /** 
  328.      * 橙红色 - 半透明 
  329.      */  
  330.     public static final int ORANGERED_TRANSLUCENT = 0x80ff4500;  
  331.   
  332.     /** 
  333.      * 银白色 
  334.      */  
  335.     public static final int SILVER = 0xffc0c0c0;  
  336.   
  337.     /** 
  338.      * 银白色 - 半透明 
  339.      */  
  340.     public static final int SILVER_TRANSLUCENT = 0x80c0c0c0;  
  341.   
  342.     /** 
  343.      * 高光 
  344.      */  
  345.     public static final int HIGHLIGHT = 0x33ffffff;  
  346.   
  347.     /** 
  348.      * 低光 
  349.      */  
  350.     public static final int LOWLIGHT = 0x33000000;  
  351. }  
ExitActivityUtil工具类:

  1. import android.app.Activity;  
  2. import android.view.KeyEvent;  
  3. import android.widget.Toast;  
  4.   
  5. public class ExitActivityUtil extends Activity{  
  6.       
  7.     private long exitTime = 0;  
  8.       
  9.     /* 
  10.      * 重写onKeyDown方法 
  11.      */  
  12.     @Override  
  13.     public boolean onKeyDown(int keyCode, KeyEvent event) {  
  14.         if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {  
  15.             //2s之内按返回键就会推出  
  16.             if((System.currentTimeMillis() - exitTime) > 2000){  
  17.                 Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();  
  18.                 exitTime = System.currentTimeMillis();  
  19.             } else {  
  20.                 finish();  
  21.                 System.exit(0);  
  22.             }  
  23.             return true;  
  24.         }  
  25.         return super.onKeyDown(keyCode, event);  
  26.     }  
  27.   
  28. }  
FileUtil工具类:
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6.   
  7. /** 
  8.  * 文件操作工具类 
  9.  */  
  10. public class FileUtil {  
  11.   
  12.     /** 
  13.      * 在指定的位置创建指定的文件 
  14.      * @param filePath 完整的文件路径 
  15.      * @param mkdir 是否创建相关的文件夹 
  16.      * @throws IOException  
  17.      */  
  18.     public static void mkFile(String filePath, boolean mkdir) throws IOException{  
  19.         File file = new File(filePath);  
  20.          /** 
  21.          * mkdirs()创建多层目录,mkdir()创建单层目录 
  22.          * writeObject时才创建磁盘文件。 
  23.          * 若不创建文件,readObject出错。 
  24.          */  
  25.         file.getParentFile().mkdirs();  
  26.         file.createNewFile();  
  27.         file = null;  
  28.     }  
  29.       
  30.     /** 
  31.      * 在指定的位置创建文件夹 
  32.      * @param dirPath 文件夹路径 
  33.      * @return 若创建成功,则返回True;反之,则返回False 
  34.      */  
  35.     public static boolean mkDir(String dirPath) {  
  36.         return new File(dirPath).mkdirs();  
  37.     }  
  38.       
  39.     /** 
  40.      * 删除指定的文件 
  41.      * @param filePath 文件路径 
  42.      * @return 若删除成功,则返回True;反之,则返回False 
  43.      */  
  44.     public static boolean delFile(String filePath) {  
  45.         return new File(filePath).delete();  
  46.     }  
  47.       
  48.     /** 
  49.      * 删除指定的文件夹 
  50.      * @param dirPath 文件夹路径 
  51.      * @param delFile 文件夹中是否包含文件 
  52.      * @return 若删除成功,则返回True;反之,则返回False 
  53.      */  
  54.     public static boolean delDir(String dirPath, boolean delFile) {  
  55.         if (delFile) {  
  56.             File file = new File(dirPath);  
  57.             if (file.isFile()) {  
  58.                 return file.delete();  
  59.             } else if (file.isDirectory()) {  
  60.                 if (file.listFiles().length == 0) {  
  61.                     return file.delete();  
  62.                 } else {  
  63.                     int zFiles = file.listFiles().length;  
  64.                     File[] delfile = file.listFiles();  
  65.                     for (int i = 0; i < zFiles; i++) {  
  66.                         if (delfile[i].isDirectory()) {  
  67.                             delDir(delfile[i].getAbsolutePath(), true);  
  68.                         }  
  69.                         delfile[i].delete();  
  70.                     }  
  71.                     return file.delete();  
  72.                 }  
  73.             } else {  
  74.                 return false;  
  75.             }  
  76.         } else {  
  77.             return new File(dirPath).delete();  
  78.         }  
  79.     }  
  80.       
  81.     /** 
  82.      * 复制文件/文件夹 若要进行文件夹复制,请勿将目标文件夹置于源文件夹中 
  83.      * @param source 源文件(夹) 
  84.      * @param target 目标文件(夹) 
  85.      * @param isFolder 若进行文件夹复制,则为True;反之为False 
  86.      * @throws IOException  
  87.      */  
  88.     public static void copy(String source, String target, boolean isFolder) throws IOException{  
  89.         if (isFolder) {  
  90.             new File(target).mkdirs();  
  91.             File a = new File(source);  
  92.             String[] file = a.list();  
  93.             File temp = null;  
  94.             for (int i = 0; i < file.length; i++) {  
  95.                 if (source.endsWith(File.separator)) {  
  96.                     temp = new File(source + file[i]);  
  97.                 } else {  
  98.                     temp = new File(source + File.separator + file[i]);  
  99.                 }  
  100.                 if (temp.isFile()) {  
  101.                     FileInputStream input = new FileInputStream(temp);  
  102.                     FileOutputStream output = new FileOutputStream(target + File.separator + temp.getName().toString());  
  103.                     byte[] b = new byte[1024];  
  104.                     int len;  
  105.                     while ((len = input.read(b)) != -1) {  
  106.                         output.write(b, 0, len);  
  107.                     }  
  108.                     output.flush();  
  109.                     output.close();  
  110.                     input.close();  
  111.                 } if (temp.isDirectory()) {  
  112.                     copy(source + File.separator + file[i], target + File.separator + file[i], true);  
  113.                 }  
  114.             }  
  115.         } else {  
  116.             int byteread = 0;  
  117.             File oldfile = new File(source);  
  118.             if (oldfile.exists()) {  
  119.                 InputStream inputStream = new FileInputStream(source);  
  120.                 File file = new File(target);  
  121.                 file.getParentFile().mkdirs();  
  122.                 file.createNewFile();  
  123.                 FileOutputStream outputStream = new FileOutputStream(file);  
  124.                 byte[] buffer = new byte[1024];  
  125.                 while ((byteread = inputStream.read(buffer)) != -1){  
  126.                     outputStream.write(buffer, 0, byteread);  
  127.                 }  
  128.                 inputStream.close();  
  129.                 outputStream.close();  
  130.             }  
  131.         }  
  132.     }  
  133. }  
HttpUtil工具类:

  1. import java.io.BufferedReader;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.io.PrintWriter;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.MalformedURLException;  
  9. import java.net.URL;  
  10.   
  11. /** 
  12.  * Http请求的相关工具类 
  13.  */  
  14. public class HttpUtil {  
  15.       
  16.     private static final int TIMEOUT_IN_MILLIONS = 5000;  
  17.       
  18.     public interface CallBack {  
  19.         void onRequestComplete(String requst);  
  20.     }  
  21.   
  22.     /** 
  23.      * 异步的Get请求 
  24.      * @param urlStr 
  25.      * @param callBack 
  26.      */  
  27.     public static void doGetAsyn(final String urlStr, final CallBack callBack) {  
  28.         new Thread(new Runnable() {  
  29.               
  30.             @Override  
  31.             public void run() {  
  32.                 try {  
  33.                     String result = doGet(urlStr);  
  34.                     if (callBack != null) {  
  35.                         callBack.onRequestComplete(result);  
  36.                     }  
  37.                 } catch (Exception e) {  
  38.                     e.printStackTrace();  
  39.                 }  
  40.             }  
  41.         }).start();  
  42.     }  
  43.       
  44.     /** 
  45.      * 异步的Post请求 
  46.      * @param urlStr 
  47.      * @param params 
  48.      * @param callBack 
  49.      * @throws Exception 
  50.      */  
  51.     public static void doPostAsyn(final String urlStr, final String params,  
  52.             final CallBack callBack) {  
  53.         new Thread(new Runnable() {  
  54.             @Override  
  55.             public void run() {  
  56.                 try {  
  57.                     String result = doPost(urlStr, params);  
  58.                     if (callBack != null) {  
  59.                         callBack.onRequestComplete(result);  
  60.                     }  
  61.                 } catch (Exception e) {  
  62.                     e.printStackTrace();  
  63.                 }  
  64.             }  
  65.         }).start();  
  66.     }  
  67.   
  68.       
  69.      /** 
  70.      * Get请求,获得返回数据 
  71.      * 
  72.      * @param urlStr 
  73.      * @return 
  74.      * @throws Exception 
  75.      */  
  76.     public static String doGet(String urlStr) {  
  77.         URL url = null;  
  78.         HttpURLConnection conn = null;  
  79.         InputStream is = null;  
  80.         ByteArrayOutputStream baos = null;  
  81.         try {  
  82.             url = new URL(urlStr);  
  83.             conn = (HttpURLConnection) url.openConnection();  
  84.             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);  
  85.             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);  
  86.             conn.setRequestMethod("GET");  
  87.             conn.setRequestProperty("accept""*/*");  
  88.             conn.setRequestProperty("connection""Keep-Alive");  
  89.             if (conn.getResponseCode() == 200) {  
  90.                 is = conn.getInputStream();  
  91.                 baos = new ByteArrayOutputStream();  
  92.                 int len = -1;  
  93.                 byte[] buf = new byte[1024];  
  94.                 while ((len = is.read()) != -1) {  
  95.                     baos.write(buf, 0, len);  
  96.                 }  
  97.                 baos.flush();  
  98.                 return baos.toString();  
  99.             } else {  
  100.                 throw new RuntimeException(" responseCode is not 200 ... ");  
  101.             }  
  102.         } catch (MalformedURLException e) {  
  103.             e.printStackTrace();  
  104.         } catch (IOException e) {  
  105.             e.printStackTrace();  
  106.         } finally {  
  107.             try {  
  108.                 if (is != null)  
  109.                     is.close();  
  110.             } catch (IOException e) {  
  111.                 e.printStackTrace();  
  112.             }  
  113.             try {  
  114.                 if (baos != null)  
  115.                     baos.close();  
  116.             } catch (IOException e) {  
  117.                 e.printStackTrace();  
  118.             }  
  119.             conn.disconnect();  
  120.         }  
  121.         return null;  
  122.     }  
  123.       
  124.      /**  
  125.      * 向指定 URL 发送POST方法的请求  
  126.      * @param url 发送请求的 URL  
  127.      * @param param  请求参数,请求参数应该是 name1=value1&name2=value2 的形式。  
  128.      * @return 所代表远程资源的响应结果  
  129.      * @throws Exception  
  130.      */  
  131.     public static String doPost(String url, String param) {  
  132.         PrintWriter out = null;  
  133.         BufferedReader in = null;  
  134.         String result = "";  
  135.         try {  
  136.             URL realUrl = new URL(url);  
  137.             HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();  
  138.             // 设置通用的请求属性  
  139.             conn.setRequestProperty("accept""*/*");  
  140.             conn.setRequestProperty("connection""Keep-Alive");  
  141.             conn.setRequestMethod("POST");  
  142.             conn.setRequestProperty("accept""*/*");  
  143.             conn.setRequestProperty("connection""Keep-Alive");  
  144.             conn.setRequestMethod("POST");  
  145.             conn.setRequestProperty("Content-Type",  
  146.                     "application/x-www-form-urlencoded");  
  147.             conn.setRequestProperty("charset""utf-8");  
  148.             conn.setUseCaches(false);  
  149.             // 发送POST请求必须设置如下两行  
  150.             conn.setDoOutput(true);  
  151.             conn.setDoInput(true);  
  152.             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);  
  153.             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);  
  154.             if (param != null && !param.trim().equals("")) {  
  155.                 // 获取URLConnection对象对应的输出流  
  156.                 out = new PrintWriter(conn.getOutputStream());  
  157.                 // 发送请求参数  
  158.                 out.print(param);  
  159.                 // flush输出流的缓冲  
  160.                 out.flush();  
  161.             }  
  162.             // 定义BufferedReader输入流来读取URL的响应  
  163.             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  164.             String line;  
  165.             while ((line = in.readLine()) != null) {  
  166.                 result += line;  
  167.             }  
  168.         } catch (Exception e) {  
  169.             e.printStackTrace();  
  170.         }  
  171.         // 使用finally块来关闭输出流、输入流  
  172.         finally {  
  173.             try {  
  174.                 if (out != null) {  
  175.                     out.close();  
  176.                 }  
  177.                 if (in != null) {  
  178.                     in.close();  
  179.                 }  
  180.             } catch (IOException ex) {  
  181.                 ex.printStackTrace();  
  182.             }  
  183.         }  
  184.         return result;  
  185.     }  
  186.       
  187. }  
PhoneUtil工具类:

  1. import java.io.File;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.net.Uri;  
  7. import android.provider.MediaStore;  
  8.   
  9. /** 
  10.  * 手机组件调用工具类 
  11.  */  
  12. public class PhoneUtil {  
  13.   
  14.     private static long lastClickTime;  
  15.       
  16.     private PhoneUtil() {  
  17.         throw new Error("Do not need instantiate!");  
  18.     }  
  19.       
  20.     /** 
  21.      * 调用系统发短信界面 
  22.      * @param activity    Activity 
  23.      * @param phoneNumber 手机号码 
  24.      * @param smsContent  短信内容 
  25.      */  
  26.     public static void sendMessage(Context activity, String phoneNumber, String smsContent) {  
  27.         if (smsContent == null || phoneNumber.length() < 4) {  
  28.             return;  
  29.         }  
  30.         Uri uri = Uri.parse("smsto:" + phoneNumber);  
  31.         Intent intent = new Intent(Intent.ACTION_SENDTO, uri);  
  32.         intent.putExtra("sms_body", smsContent);  
  33.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  34.         activity.startActivity(intent);  
  35.     }  
  36.       
  37.     /** 
  38.      * 判断是否为连击 
  39.      * @return  boolean 
  40.      */  
  41.     public static boolean isFastDoubleClick() {  
  42.         long time = System.currentTimeMillis();  
  43.         long timeD = time - lastClickTime;  
  44.         if (0 < timeD && timeD < 500) {  
  45.             return true;  
  46.         }  
  47.         lastClickTime = time;  
  48.         return false;  
  49.     }  
  50.       
  51.     /** 
  52.      * 获取手机型号 
  53.      * @param context  上下文 
  54.      * @return   String 
  55.      */  
  56.     public static String getMobileModel(Context context) {  
  57.         try {  
  58.             String model = android.os.Build.MODEL;  
  59.             return model;  
  60.         } catch (Exception e) {  
  61.             return "未知!";  
  62.         }  
  63.     }  
  64.       
  65.     /** 
  66.      * 获取手机品牌 
  67.      * @param context  上下文 
  68.      * @return  String 
  69.      */  
  70.     public static String getMobileBrand(Context context) {  
  71.         try {  
  72.             // android系统版本号  
  73.             String brand = android.os.Build.BRAND;   
  74.             return brand;  
  75.         } catch (Exception e) {  
  76.             return "未知";  
  77.         }  
  78.     }  
  79.       
  80.     /** 
  81.      *拍照打开照相机! 
  82.      * @param requestcode   返回值 
  83.      * @param activity   上下文 
  84.      * @param fileName    生成的图片文件的路径 
  85.      */  
  86.     public static void toTakePhoto(int requestcode, Activity activity,String fileName) {  
  87.         Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  88.         intent.putExtra("camerasensortype"2);// 调用前置摄像头  
  89.         intent.putExtra("autofocus"true);// 自动对焦  
  90.         intent.putExtra("fullScreen"false);// 全屏  
  91.         intent.putExtra("showActionIcons"false);  
  92.         try {  
  93.             //创建一个当前任务id的文件,然后里面存放任务的照片和路径!这主文件的名字是用uuid到时候再用任务id去查路径!  
  94.             File file = new File(fileName);  
  95.             //如果这个文件不存在就创建一个文件夹!  
  96.             if (!file.exists()) {  
  97.                 file.mkdirs();  
  98.             }  
  99.             Uri uri = Uri.fromFile(file);  
  100.             intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);  
  101.             activity.startActivityForResult(intent, requestcode);  
  102.         } catch (Exception e) {  
  103.             e.printStackTrace();  
  104.         }  
  105.     }  
  106.       
  107.     /** 
  108.      *打开相册 
  109.      * @param requestcode  响应码 
  110.      * @param activity  上下文 
  111.      */  
  112.     public static void toTakePicture(int requestcode, Activity activity){  
  113.         Intent intent = new Intent(Intent.ACTION_PICK, null);  
  114.         intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");  
  115.         activity.startActivityForResult(intent, requestcode);  
  116.     }  
  117. }  
ShortCutUtil工具类:

  1. import android.app.Activity;  
  2. import android.content.ComponentName;  
  3. import android.content.ContentResolver;  
  4. import android.content.Intent;  
  5. import android.database.Cursor;  
  6. import android.net.Uri;  
  7.   
  8. /** 
  9.  * 创建删除快捷图标 
  10.  * 需要权限: com.android.launcher.permission.INSTALL_SHORTCUT 
  11.  *        com.android.launcher.permission.UNINSTALL_SHORTCUT 
  12.  */  
  13. public class ShortCutUtil {  
  14.   
  15.     private ShortCutUtil() {  
  16.         throw new Error("Do not need instantiate!");  
  17.     }  
  18.       
  19.     /** 
  20.      * 检测是否存在快捷键 
  21.      * @param activity Activity 
  22.      * @return 是否存在桌面图标 
  23.      */  
  24.     public static boolean hasShortcut(Activity activity) {  
  25.         boolean isInstallShortcut = false;  
  26.         ContentResolver cr = activity.getContentResolver();  
  27.         String AUTHORITY = "com.android.launcher.settings";  
  28.         Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY  
  29.                 + "/favorites?notify=true");  
  30.         Cursor c = cr.query(CONTENT_URI,   
  31.                 new String[]{"title""iconResource"}, "title=?",   
  32.                 new String[]{activity.getString(R.string.app_name).trim()},  
  33.                 null);  
  34.         if (c != null && c.getCount() > 0) {  
  35.             isInstallShortcut = true;  
  36.         }  
  37.           
  38.         return isInstallShortcut;  
  39.     }  
  40.       
  41.     /** 
  42.      * 为程序创建桌面快捷方式 
  43.      * @param activity Activity 
  44.      * @param res     res 
  45.      */  
  46.     public static void addShortcut(Activity activity,int res) {  
  47.         Intent shortcut = new Intent(  
  48.                 "com.android.launcher.action.INSTALL_SHORTCUT");  
  49.         //快捷方式的名称  
  50.         shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,   
  51.                 activity.getString(R.string.app_name));  
  52.         //不允许重复创建  
  53.         shortcut.putExtra("duplicate"false);  
  54.          Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);  
  55.          shortcutIntent.setClassName(activity, activity.getClass().getName());  
  56.          shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);  
  57.         //快捷方式的图标  
  58.          Intent.ShortcutIconResource iconRes =   
  59.                  Intent.ShortcutIconResource.fromContext(activity, res);  
  60.          shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);  
  61.          activity.sendBroadcast(shortcut);  
  62.     }  
  63.       
  64.     /** 
  65.      * 删除程序的快捷方式 
  66.      * @param activity Activity 
  67.      */  
  68.     public static void delShortcut(Activity activity) {  
  69.         Intent shortcut = new Intent(  
  70.                 "com.android.launcher.action.UNINSTALL_SHORTCUT");  
  71.         shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,  
  72.                 activity.getString(R.string.app_name));  
  73.         String appClass = activity.getPackageName() + "."  
  74.                 + activity.getLocalClassName();  
  75.         ComponentName cn = new ComponentName(activity.getPackageName(), appClass);  
  76.         shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(  
  77.                 Intent.ACTION_MAIN).setComponent(cn));  
  78.         activity.sendBroadcast(shortcut);  
  79.     }  
  80. }  
StringUtil工具类:

  1. import java.io.UnsupportedEncodingException;  
  2. import java.net.URLEncoder;  
  3. import java.security.MessageDigest;  
  4. import java.util.ArrayList;  
  5. import java.util.Locale;  
  6. import java.util.regex.Matcher;  
  7. import java.util.regex.Pattern;  
  8.   
  9. /** 
  10.  * 字符串工具类,提供一些字符串相关的便捷方法 
  11.  */  
  12. public class StringUtil {  
  13.   
  14.     private StringUtil() {  
  15.         throw new AssertionError();  
  16.     }  
  17.       
  18.     /** 
  19.      * <pre> 
  20.      * isBlank(null) = true; 
  21.      * isBlank("") = true; 
  22.      * isBlank("  ") = true; 
  23.      * isBlank("a") = false; 
  24.      * isBlank("a ") = false; 
  25.      * isBlank(" a") = false; 
  26.      * isBlank("a b") = false; 
  27.      * </pre> 
  28.      * 
  29.      * @param str 字符串 
  30.      * @return 如果字符串为空或者长度为0,返回true,否则返回false 
  31.      */  
  32.     public static boolean isBlank(String str) {  
  33.         return (str == null || str.trim().length() == 0);  
  34.     }  
  35.       
  36.     /** 
  37.      * <pre> 
  38.      * isEmpty(null) = true; 
  39.      * isEmpty("") = true; 
  40.      * isEmpty("  ") = false; 
  41.      * </pre> 
  42.      * 
  43.      * @param c 字符序列 
  44.      * @return 如果字符序列为空或者长度为0,返回true,否则返回false 
  45.      */  
  46.     public static boolean isEmpty(CharSequence c) {  
  47.         return (c == null || c.length() == 0);  
  48.     }  
  49.       
  50.      /** 
  51.      * 获取字符序列的长度 
  52.      * <pre> 
  53.      * length(null) = 0; 
  54.      * length(\"\") = 0; 
  55.      * length(\"abc\") = 3; 
  56.      * </pre> 
  57.      * 
  58.      * @param c 字符序列 
  59.      * @return 如果字符序列为空,返回0,否则返回字符序列的长度 
  60.      */  
  61.     public static int length(CharSequence c) {  
  62.         return c == null ? 0 : c.length();  
  63.     }  
  64.       
  65.     /** 
  66.      * null Object to empty string 
  67.      *  空对象转化成空字符串 
  68.      * <pre> 
  69.      * nullStrToEmpty(null) = ""; 
  70.      * nullStrToEmpty("") = ""; 
  71.      * nullStrToEmpty("aa") = "aa"; 
  72.      * </pre> 
  73.      * 
  74.      * @param object 对象 
  75.      * @return String 
  76.      */  
  77.     public static String nullStrToEmpty(Object object) {  
  78.         return object == null ?  
  79.                 "" : (object instanceof String ? (String)object : object.toString());  
  80.     }  
  81.       
  82.     /** 
  83.      * @param str str 
  84.      * @return String 
  85.      */  
  86.     public static String capitalizeFirstLetter(String str) {  
  87.         if (isEmpty(str)) {  
  88.             return str;  
  89.         }  
  90.         char c = str.charAt(0);  
  91.         return (!Character.isLetter(c) || Character.isUpperCase(c))  
  92.                 ? str  
  93.                 : new StringBuilder(str.length()).append(  
  94.                 Character.toUpperCase(c))  
  95.                 .append(str.substring(1))  
  96.                 .toString();  
  97.     }  
  98.       
  99.     /** 
  100.      * 用utf-8编码 
  101.      * @param str 字符串 
  102.      * @return 返回一个utf8的字符串 
  103.      */  
  104.     public static String utf8Encode(String str) {  
  105.         if (!isEmpty(str) || str.getBytes().length != str.length()) {  
  106.             try {  
  107.                 return URLEncoder.encode(str, "utf-8");  
  108.             } catch (UnsupportedEncodingException e) {  
  109.                 throw new RuntimeException(  
  110.                         "UnsupportedEncodingException occurred. ", e);  
  111.             }  
  112.         }  
  113.         return str;  
  114.     }  
  115.       
  116.     /** 
  117.      * @param href 字符串 
  118.      * @return 返回一个html 
  119.      */  
  120.     public static String getHrefInnerHtml(String href) {  
  121.         if (isEmpty(href)) {  
  122.             return "";  
  123.         }  
  124.         String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";  
  125.         Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);  
  126.         Matcher hrefMatcher = hrefPattern.matcher(href);  
  127.         if (hrefMatcher.matches()) {  
  128.             return hrefMatcher.group(1);  
  129.         }  
  130.         return href;  
  131.     }  
  132.       
  133.     /** 
  134.      * @param source 字符串 
  135.      * @return 返回htmL到字符串 
  136.      */  
  137.     public static String htmlEscapeCharsToString(String source) {  
  138.         return StringUtil.isEmpty(source)  
  139.                 ? source  
  140.                 : source.replaceAll("<""<")  
  141.                 .replaceAll(">"">")  
  142.                 .replaceAll("&""&")  
  143.                 .replaceAll(""", "\"");   
  144.     }  
  145.       
  146.     /** 
  147.      * @param s 字符串 
  148.      * @return String 
  149.      */  
  150.     public static String fullWidthToHalfWidth(String s) {  
  151.         if (isEmpty(s)) {  
  152.             return s;  
  153.         }  
  154.         char[] source = s.toCharArray();  
  155.         for (int i = 0; i < source.length; i++) {  
  156.             if (source[i] == 12288) {  
  157.                 source[i] = ' ';  
  158.                 // } else if (source[i] == 12290) {  
  159.                 // source[i] = '.';  
  160.             }  
  161.             else if (source[i] >= 65281 && source[i] <= 65374) {  
  162.                 source[i] = (char) (source[i] - 65248);  
  163.             }  
  164.             else {  
  165.                 source[i] = source[i];  
  166.             }  
  167.         }  
  168.         return new String(source);  
  169.     }  
  170.       
  171.     /** 
  172.      * @param s 字符串 
  173.      * @return 返回的数值 
  174.      */  
  175.     public static String halfWidthToFullWidth(String s) {  
  176.   
  177.         if (isEmpty(s)) {  
  178.             return s;  
  179.         }  
  180.   
  181.         char[] source = s.toCharArray();  
  182.         for (int i = 0; i < source.length; i++) {  
  183.             if (source[i] == ' ') {  
  184.                 source[i] = (char12288;  
  185.                 // } else if (source[i] == '.') {  
  186.                 // source[i] = (char)12290;  
  187.             }  
  188.             else if (source[i] >= 33 && source[i] <= 126) {  
  189.                 source[i] = (char) (source[i] + 65248);  
  190.             }  
  191.             else {  
  192.                 source[i] = source[i];  
  193.             }  
  194.         }  
  195.         return new String(source);  
  196.     }  
  197.   
  198.   
  199.     /** 
  200.      * @param str 资源 
  201.      * @return 特殊字符串切换 
  202.      */  
  203.   
  204.     public static String replaceBlanktihuan(String str) {  
  205.   
  206.         String dest = "";  
  207.         if (str != null) {  
  208.             Pattern p = Pattern.compile("\\s*|\t|\r|\n");  
  209.             Matcher m = p.matcher(str);  
  210.             dest = m.replaceAll("");  
  211.         }  
  212.         return dest;  
  213.     }  
  214.   
  215.   
  216.     /** 
  217.      * 判断给定的字符串是否为null或者是空的 
  218.      * @param string 给定的字符串 
  219.      */  
  220.     public static boolean isEmpty(String string) {  
  221.         return string == null || "".equals(string.trim());  
  222.     }  
  223.   
  224.   
  225.     /** 
  226.      * 判断给定的字符串是否不为null且不为空 
  227.      * @param string 给定的字符串 
  228.      */  
  229.     public static boolean isNotEmpty(String string) {  
  230.         return !isEmpty(string);  
  231.     }  
  232.   
  233.   
  234.     /** 
  235.      * 判断给定的字符串数组中的所有字符串是否都为null或者是空的 
  236.      * @param strings 给定的字符串 
  237.      */  
  238.     public static boolean isEmpty(String... strings) {  
  239.         boolean result = true;  
  240.         for (String string : strings) {  
  241.             if (isNotEmpty(string)) {  
  242.                 result = false;  
  243.                 break;  
  244.             }  
  245.         }  
  246.         return result;  
  247.     }  
  248.   
  249.   
  250.     /** 
  251.      * 判断给定的字符串数组中是否全部都不为null且不为空 
  252.      * 
  253.      * @param strings 给定的字符串数组 
  254.      * @return 是否全部都不为null且不为空 
  255.      */  
  256.     public static boolean isNotEmpty(String... strings) {  
  257.         boolean result = true;  
  258.         for (String string : strings) {  
  259.             if (isEmpty(string)) {  
  260.                 result = false;  
  261.                 break;  
  262.             }  
  263.         }  
  264.         return result;  
  265.     }  
  266.   
  267.   
  268.     /** 
  269.      * 如果字符串是null或者空就返回"" 
  270.      */  
  271.     public static String filterEmpty(String string) {  
  272.         return StringUtil.isNotEmpty(string) ? string : "";  
  273.     }  
  274.   
  275.   
  276.     /** 
  277.      * 在给定的字符串中,用新的字符替换所有旧的字符 
  278.      * @param string 给定的字符串 
  279.      * @param oldchar 旧的字符 
  280.      * @param newchar 新的字符 
  281.      * @return 替换后的字符串 
  282.      */  
  283.     public static String replace(String string, char oldchar, char newchar) {  
  284.         char chars[] = string.toCharArray();  
  285.         for (int w = 0; w < chars.length; w++) {  
  286.             if (chars[w] == oldchar) {  
  287.                 chars[w] = newchar;  
  288.                 break;  
  289.             }  
  290.         }  
  291.         return new String(chars);  
  292.     }  
  293.   
  294.   
  295.     /** 
  296.      * 把给定的字符串用给定的字符分割 
  297.      * @param string 给定的字符串 
  298.      * @param ch 给定的字符 
  299.      * @return 分割后的字符串数组 
  300.      */  
  301.     public static String[] split(String string, char ch) {  
  302.         ArrayList<String> stringList = new ArrayList<String>();  
  303.         char chars[] = string.toCharArray();  
  304.         int nextStart = 0;  
  305.         for (int w = 0; w < chars.length; w++) {  
  306.             if (ch == chars[w]) {  
  307.                 stringList.add(new String(chars, nextStart, w - nextStart));  
  308.                 nextStart = w + 1;  
  309.                 if (nextStart ==  
  310.                         chars.length) {    //当最后一位是分割符的话,就再添加一个空的字符串到分割数组中去  
  311.                     stringList.add("");  
  312.                 }  
  313.             }  
  314.         }  
  315.         if (nextStart <  
  316.                 chars.length) {    //如果最后一位不是分隔符的话,就将最后一个分割符到最后一个字符中间的左右字符串作为一个字符串添加到分割数组中去  
  317.             stringList.add(new String(chars, nextStart,  
  318.                     chars.length - 1 - nextStart + 1));  
  319.         }  
  320.         return stringList.toArray(new String[stringList.size()]);  
  321.     }  
  322.   
  323.   
  324.     /** 
  325.      * 计算给定的字符串的长度,计算规则是:一个汉字的长度为2,一个字符的长度为1 
  326.      * 
  327.      * @param string 给定的字符串 
  328.      * @return 长度 
  329.      */  
  330.     public static int countLength(String string) {  
  331.         int length = 0;  
  332.         char[] chars = string.toCharArray();  
  333.         for (int w = 0; w < string.length(); w++) {  
  334.             char ch = chars[w];  
  335.             if (ch >= '\u0391' && ch <= '\uFFE5') {  
  336.                 length++;  
  337.                 length++;  
  338.             }  
  339.             else {  
  340.                 length++;  
  341.             }  
  342.         }  
  343.         return length;  
  344.     }  
  345.   
  346.     private static char[] getChars(char[] chars, int startIndex) {  
  347.         int endIndex = startIndex + 1;  
  348.         //如果第一个是数字  
  349.         if (Character.isDigit(chars[startIndex])) {  
  350.             //如果下一个是数字  
  351.             while (endIndex < chars.length &&  
  352.                     Character.isDigit(chars[endIndex])) {  
  353.                 endIndex++;  
  354.             }  
  355.         }  
  356.         char[] resultChars = new char[endIndex - startIndex];  
  357.         System.arraycopy(chars, startIndex, resultChars, 0, resultChars.length);  
  358.         return resultChars;  
  359.     }  
  360.   
  361.   
  362.     /** 
  363.      * 是否全是数字 
  364.      */  
  365.     public static boolean isAllDigital(char[] chars) {  
  366.         boolean result = true;  
  367.         for (int w = 0; w < chars.length; w++) {  
  368.             if (!Character.isDigit(chars[w])) {  
  369.                 result = false;  
  370.                 break;  
  371.             }  
  372.         }  
  373.         return result;  
  374.     }  
  375.   
  376.   
  377.   
  378.   
  379.     /** 
  380.      * 删除给定字符串中所有的旧的字符 
  381.      * 
  382.      * @param string 源字符串 
  383.      * @param ch 要删除的字符 
  384.      * @return 删除后的字符串 
  385.      */  
  386.     public static String removeChar(String string, char ch) {  
  387.         StringBuffer sb = new StringBuffer();  
  388.         for (char cha : string.toCharArray()) {  
  389.             if (cha != '-') {  
  390.                 sb.append(cha);  
  391.             }  
  392.         }  
  393.         return sb.toString();  
  394.     }  
  395.   
  396.   
  397.     /** 
  398.      * 删除给定字符串中给定位置处的字符 
  399.      * 
  400.      * @param string 给定字符串 
  401.      * @param index 给定位置 
  402.      */  
  403.     public static String removeChar(String string, int index) {  
  404.         String result = null;  
  405.         char[] chars = string.toCharArray();  
  406.         if (index == 0) {  
  407.             result = new String(chars, 1, chars.length - 1);  
  408.         }  
  409.         else if (index == chars.length - 1) {  
  410.             result = new String(chars, 0, chars.length - 1);  
  411.         }  
  412.         else {  
  413.             result = new String(chars, 0, index) +  
  414.                     new String(chars, index + 1, chars.length - index);  
  415.             ;  
  416.         }  
  417.         return result;  
  418.     }  
  419.   
  420.   
  421.     /** 
  422.      * 删除给定字符串中给定位置处的字符 
  423.      * 
  424.      * @param string 给定字符串 
  425.      * @param index 给定位置 
  426.      * @param ch 如果同给定位置处的字符相同,则将给定位置处的字符删除 
  427.      */  
  428.     public static String removeChar(String string, int index, char ch) {  
  429.         String result = null;  
  430.         char[] chars = string.toCharArray();  
  431.         if (chars.length > 0 && chars[index] == ch) {  
  432.             if (index == 0) {  
  433.                 result = new String(chars, 1, chars.length - 1);  
  434.             }  
  435.             else if (index == chars.length - 1) {  
  436.                 result = new String(chars, 0, chars.length - 1);  
  437.             }  
  438.             else {  
  439.                 result = new String(chars, 0, index) +  
  440.                         new String(chars, index + 1, chars.length - index);  
  441.                 ;  
  442.             }  
  443.         }  
  444.         else {  
  445.             result = string;  
  446.         }  
  447.         return result;  
  448.     }  
  449.   
  450.   
  451.     /** 
  452.      * 对给定的字符串进行空白过滤 
  453.      * 
  454.      * @param string 给定的字符串 
  455.      * @return 如果给定的字符串是一个空白字符串,那么返回null;否则返回本身。 
  456.      */  
  457.     public static String filterBlank(String string) {  
  458.         if ("".equals(string)) {  
  459.             return null;  
  460.         }  
  461.         else {  
  462.             return string;  
  463.         }  
  464.     }  
  465.   
  466.   
  467.     /** 
  468.      * 将给定字符串中给定的区域的字符转换成小写 
  469.      * 
  470.      * @param str 给定字符串中 
  471.      * @param beginIndex 开始索引(包括) 
  472.      * @param endIndex 结束索引(不包括) 
  473.      * @return 新的字符串 
  474.      */  
  475.     public static String toLowerCase(String str, int beginIndex, int endIndex) {  
  476.         return str.replaceFirst(str.substring(beginIndex, endIndex),  
  477.                 str.substring(beginIndex, endIndex)  
  478.                         .toLowerCase(Locale.getDefault()));  
  479.     }  
  480.   
  481.   
  482.     /** 
  483.      * 将给定字符串中给定的区域的字符转换成大写 
  484.      * 
  485.      * @param str 给定字符串中 
  486.      * @param beginIndex 开始索引(包括) 
  487.      * @param endIndex 结束索引(不包括) 
  488.      * @return 新的字符串 
  489.      */  
  490.     public static String toUpperCase(String str, int beginIndex, int endIndex) {  
  491.         return str.replaceFirst(str.substring(beginIndex, endIndex),  
  492.                 str.substring(beginIndex, endIndex)  
  493.                         .toUpperCase(Locale.getDefault()));  
  494.     }  
  495.   
  496.   
  497.     /** 
  498.      * 将给定字符串的首字母转为小写 
  499.      * 
  500.      * @param str 给定字符串 
  501.      * @return 新的字符串 
  502.      */  
  503.     public static String firstLetterToLowerCase(String str) {  
  504.         return toLowerCase(str, 01);  
  505.     }  
  506.   
  507.   
  508.     /** 
  509.      * 将给定字符串的首字母转为大写 
  510.      * 
  511.      * @param str 给定字符串 
  512.      * @return 新的字符串 
  513.      */  
  514.     public static String firstLetterToUpperCase(String str) {  
  515.         return toUpperCase(str, 01);  
  516.     }  
  517.   
  518.   
  519.     /** 
  520.      * 将给定的字符串MD5加密 
  521.      * 
  522.      * @param string 给定的字符串 
  523.      * @return MD5加密后生成的字符串 
  524.      */  
  525.     public static String MD5(String string) {  
  526.         String result = null;  
  527.         try {  
  528.             char[] charArray = string.toCharArray();  
  529.             byte[] byteArray = new byte[charArray.length];  
  530.             for (int i = 0; i < charArray.length; i++) {  
  531.                 byteArray[i] = (byte) charArray[i];  
  532.             }  
  533.   
  534.             StringBuffer hexValue = new StringBuffer();  
  535.             byte[] md5Bytes = MessageDigest.getInstance("MD5")  
  536.                     .digest(byteArray);  
  537.             for (int i = 0; i < md5Bytes.length; i++) {  
  538.                 int val = ((int) md5Bytes[i]) & 0xff;  
  539.                 if (val < 16) {  
  540.                     hexValue.append("0");  
  541.                 }  
  542.                 hexValue.append(Integer.toHexString(val));  
  543.             }  
  544.   
  545.             result = hexValue.toString();  
  546.         } catch (Exception e) {  
  547.             e.printStackTrace();  
  548.         }  
  549.         return result;  
  550.     }  
  551.   
  552.   
  553.     /** 
  554.      * 判断给定的字符串是否以一个特定的字符串开头,忽略大小写 
  555.      * 
  556.      * @param sourceString 给定的字符串 
  557.      * @param newString 一个特定的字符串 
  558.      */  
  559.     public static boolean startsWithIgnoreCase(String sourceString, String newString) {  
  560.         int newLength = newString.length();  
  561.         int sourceLength = sourceString.length();  
  562.         if (newLength == sourceLength) {  
  563.             return newString.equalsIgnoreCase(sourceString);  
  564.         }  
  565.         else if (newLength < sourceLength) {  
  566.             char[] newChars = new char[newLength];  
  567.             sourceString.getChars(0, newLength, newChars, 0);  
  568.             return newString.equalsIgnoreCase(String.valueOf(newChars));  
  569.         }  
  570.         else {  
  571.             return false;  
  572.         }  
  573.     }  
  574.   
  575.   
  576.     /** 
  577.      * 判断给定的字符串是否以一个特定的字符串结尾,忽略大小写 
  578.      * 
  579.      * @param sourceString 给定的字符串 
  580.      * @param newString 一个特定的字符串 
  581.      */  
  582.     public static boolean endsWithIgnoreCase(String sourceString, String newString) {  
  583.         int newLength = newString.length();  
  584.         int sourceLength = sourceString.length();  
  585.         if (newLength == sourceLength) {  
  586.             return newString.equalsIgnoreCase(sourceString);  
  587.         }  
  588.         else if (newLength < sourceLength) {  
  589.             char[] newChars = new char[newLength];  
  590.             sourceString.getChars(sourceLength - newLength, sourceLength,  
  591.                     newChars, 0);  
  592.             return newString.equalsIgnoreCase(String.valueOf(newChars));  
  593.         }  
  594.         else {  
  595.             return false;  
  596.         }  
  597.     }  
  598.   
  599.   
  600.     /** 
  601.      * 检查字符串长度,如果字符串的长度超过maxLength,就截取前maxLength个字符串并在末尾拼上appendString 
  602.      */  
  603.     public static String checkLength(String string, int maxLength, String appendString) {  
  604.         if (string.length() > maxLength) {  
  605.             string = string.substring(0, maxLength);  
  606.             if (appendString != null) {  
  607.                 string += appendString;  
  608.             }  
  609.         }  
  610.         return string;  
  611.     }  
  612.   
  613.   
  614.     /** 
  615.      * 检查字符串长度,如果字符串的长度超过maxLength,就截取前maxLength个字符串并在末尾拼上… 
  616.      */  
  617.     public static String checkLength(String string, int maxLength) {  
  618.         return checkLength(string, maxLength, "…");  
  619.     }  


猜你喜欢

转载自blog.csdn.net/lumingzhang/article/details/78616702