Android实际开发中一些比较常用的工具类

来源:互联网 发布:北京ktv 知乎 编辑:程序博客网 时间:2024/06/04 06:08

总结了一些平时开发项目中的一些工具类,以前使用的时候相对比较分散一点,现在吧平时项目中用到的基本的工具类一起 拿出来看一下。
1,应用程序activity的管理类,管理当前项目中所以的activity

    /**     * 单实例 , UI无需考虑多线程同步问题     */    public static XAppManager getAppManager() {        if (instance == null) {            instance = new XAppManager();        }        return instance;    }    /**     * 添加Activity到栈     */    public void addActivity(Activity activity) {        if (activityStack == null) {            activityStack = new Stack<Activity>();        }        activityStack.add(activity);        XLog.d(PageTag, "ActivityList.onCreate(" + activity.getLocalClassName() + "),size() = " + activityStack.size() + ";") ;    }    /**     * 获取当前Activity(栈顶Activity)     */    public Activity currentActivity() {        if (activityStack == null || activityStack.isEmpty()) {            return null;        }        Activity activity = activityStack.lastElement();        return activity;    }    /**     * 获取当前Activity(栈顶Activity) 没有找到则返回null     */    public Activity findActivity(Class<?> cls) {        Activity activity = null;        for (Activity aty : activityStack) {            if (aty.getClass().equals(cls)) {                activity = aty;                break;            }        }        return activity;    }    /**     * 结束当前Activity(栈顶Activity)     */    public void finishActivity() {        Activity activity = activityStack.lastElement();        finishActivity(activity);        XLog.d(PageTag, "ActivityList.onDestroy栈顶(" + activity.getLocalClassName() + "),size() = " + activityStack.size() + ";") ;    }    /**     * 结束指定的Activity(重载)     */    public void finishActivity(Activity activity) {        if (activity != null) {            activityStack.remove(activity);            activity.finish();            XLog.d(PageTag, "ActivityList.onDestroy(" + activity.getLocalClassName() + "),size() = " + activityStack.size() + ";") ;            activity = null;        }    }    /**     * 结束指定的Activity(重载)     */    public void finishActivity(Class<?> cls) {        try {            for (Activity activity : activityStack) {                if (activity.getClass().equals(cls)) {                    finishActivity(activity);                }            }        } catch (ConcurrentModificationException e){}    }    /**     * 关闭除了指定activity以外的全部activity 如果cls不存在于栈中,则栈全部清空     *     * @param cls     */    public void finishOthersActivity(Class<?> cls) {        Stack<Activity> delList = new Stack<Activity>();//用来装需要删除的元素        for (Activity activity : activityStack) {            if (!(activity.getClass().equals(cls))) {                delList.add(activity);            }        }        for (Activity activity : delList) {            finishActivity(activity);        }        activityStack.removeAll(delList);//遍历完成后执行删除        if (delList!=null) {            delList.clear();            delList = null;        }    }    /**     * 结束所有Activity     */    public void finishAllActivity() {        for (int i = 0, size = activityStack.size(); i < size; i++) {            if (null != activityStack.get(i)) {                XLog.d(PageTag, "ActivityList.finish(" + activityStack.get(i).getLocalClassName() + ");") ;                activityStack.get(i).finish();            }        }        activityStack.clear();    }    /**     * 应用程序退出     * @param cls 退出后跳转的Activity     */    public void AppExit(Context context, Class cls) {        try {            finishAllActivity();            Intent intent = new Intent(context, cls) ;            context.startActivity(intent) ;            ActivityManager activityMgr = (ActivityManager) context                    .getSystemService(Context.ACTIVITY_SERVICE);            activityMgr.killBackgroundProcesses(context.getPackageName());            System.exit(0);        } catch (Exception e) {            System.exit(0);        }    }

2,判断当前APP的运行状态

 /**     * 当前App是否在前台运行     * add wdd 判断程序是否在运行、是否在前台     * tempMap 里含有  AppState.RUNNING 为 true 表示在运行     含有 AppS`     * 这里写代码片`tate.FOREGROUND 为  true 表示在前台     * 当有service需要常驻后台时候,此方法失效     */       public static Map<AppState, Boolean> isGetAppState(Context context){        XLog.d(PAGETAG, "appIs 正在运行app:mContext = " + context + ";");        Map<AppState,Boolean> tempMap = new HashMap<AppState, Boolean>() ;        ActivityManager am = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);        List<ActivityManager.RunningAppProcessInfo> list = am.getRunningAppProcesses();        tempMap.put(AppState.RUNNING, false) ;        tempMap.put(AppState.FOREGROUND, false) ;        if (list != null) {            /**             * RunningAppProcessInfo 运行应用过程             * 里面的变量importance就是上面说的那个什么前台后台,             * 其实是表示这个app进程的重要性,因为系统回收时候,             * 会根据importance的重要来杀进程的。 具体可以去看文档。             * IMPORTANCE_EMPTY = 500       空引用             * IMPORTANCE_BACKGROUND = 400  后台             * IMPORTANCE_SERVICE = 300     服务             * IMPORTANCE_VISIBLE = 200     可见             * IMPORTANCE_FOREGROUND = 100   前台             */            for (ActivityManager.RunningAppProcessInfo temp : list) {                if (context.getPackageName().equals(temp.processName)) {                    XLog.d(PAGETAG, "appIs" + context.getPackageName() + "在运行");                    tempMap.put(AppState.RUNNING, true) ;                    if (ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND == temp.importance) {                        XLog.d(PAGETAG, "appIs" + context.getPackageName() + "在前台");                        tempMap.put(AppState.FOREGROUND, true) ;                    }                    break;                }            }        }        XLog.d(PAGETAG, "appIsQianTai = " + tempMap.get(AppState.RUNNING) + "前后台;");        XLog.d(PAGETAG, "appIsRunning = " + tempMap.get(AppState.FOREGROUND) + "是否Run;");        return tempMap ;    }    /**     * 当前App是否在前台     * @return true:是,false:不是。     */    public static boolean appIsForeGround(Context context){        Map<AppState,Boolean> tempMap = isGetAppState(context) ;        boolean appIsForeGround = false ;        if (tempMap != null && tempMap.containsKey(AppState.FOREGROUND)) {            appIsForeGround = tempMap.get(AppState.FOREGROUND);        }        return appIsForeGround;    }    public static boolean appIsForeGround(){        return appIsForeGround(XAppManager.getAppManager().currentActivity());    }    /**     * 当前App是否在运行     * @return true:是,false:不是。     */    public static boolean appIsRunning(Context context){        Map<AppState,Boolean> tempMap = isGetAppState(context) ;        boolean appIsRunning = false ;        if (tempMap != null && tempMap.containsKey(AppState.RUNNING)) {            appIsRunning = tempMap.get(AppState.RUNNING) ;        }        return appIsRunning;    }    /**     * 当前App是否在前台     * @return true:是,false:不是。     */    public static boolean isAppIsForeGround(){        XLog.i(PAGETAG, "appCount : " + appCount);        return appCount > 0;    } 

3,偶尔可能要用到 二维码的生成

/** * 用字符串生成二维码 * @param str * @return */public static Bitmap Create2DCode(String str) throws WriterException {    //生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败    Hashtable<EncodeHintType,String> hints = new Hashtable<EncodeHintType,String>();    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");    BitMatrix matrix = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, 300, 300, hints);    int width = matrix.getWidth();    int height = matrix.getHeight();    //二维矩阵转为一维像素数组,也就是一直横着排了    int[] pixels = new int[width * height];    for (int y = 0; y < height; y++) {        for (int x = 0; x < width; x++) {            if(matrix.get(x, y)){                pixels[y * width + x] = 0xff000000;            }        }    }    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);    //通过像素数组生成bitmap,具体参考api    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);    return bitmap;}/** * 用字符串生成二维码 * @param str * @return */public static Bitmap Create2DCode(String str,int intWidth ,int intHeight) throws WriterException {    //生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败    XLog.d("XQRCode", "str = " + str + ";");    Hashtable<EncodeHintType,String> hints = new Hashtable<EncodeHintType,String>();    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");    BitMatrix matrix = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, intWidth, intHeight, hints);    int width = matrix.getWidth();    int height = matrix.getHeight();    //二维矩阵转为一维像素数组,也就是一直横着排了    int[] pixels = new int[width * height];    for (int y = 0; y < height; y++) {        for (int x = 0; x < width; x++) {            if(matrix.get(x, y)){                pixels[y * width + x] = 0xff000000;            }        }    }    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);    //通过像素数组生成bitmap,具体参考api    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);    return bitmap;}

4,dp与px的转化
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}

/** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */public static int px2dip(Context context, float pxValue) {    final float scale = context.getResources().getDisplayMetrics().density;    return (int) (pxValue / scale + 0.5f);}

5,获取手机屏幕的一些信息
/**
* 获得屏幕高度
*
* @param context
* @return
*/
public static int getScreenWidth(Context context){
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}

/** * 获得屏幕宽度 * * @param context * @return */public static int getScreenHeight(Context context){    WindowManager wm = (WindowManager) context            .getSystemService(Context.WINDOW_SERVICE);    DisplayMetrics outMetrics = new DisplayMetrics();    wm.getDefaultDisplay().getMetrics(outMetrics);    return outMetrics.heightPixels;}/** * 获得状态栏的高度 * * @param context * @return */public static int getStatusHeight(Context context){    int statusHeight = -1;    try    {        Class<?> clazz = Class.forName("com.android.internal.R$dimen");        Object object = clazz.newInstance();        int height = Integer.parseInt(clazz.getField("status_bar_height")                .get(object).toString());        statusHeight = context.getResources().getDimensionPixelSize(height);    } catch (Exception e){        e.printStackTrace();    }    return statusHeight;}/** * 获取当前屏幕截图,包含状态栏 * * @param activity * @return */public static Bitmap snapShotWithStatusBar(Activity activity){    View view = activity.getWindow().getDecorView();    view.setDrawingCacheEnabled(true);    view.buildDrawingCache();    Bitmap bmp = view.getDrawingCache();    int width = getScreenWidth(activity);    int height = getScreenHeight(activity);    Bitmap bp = null;    bp = Bitmap.createBitmap(bmp, 0, 0, width, height);    view.destroyDrawingCache();    return bp;}/** * 获取当前屏幕截图,不包含状态栏 * * @param activity * @return */public static Bitmap snapShotWithoutStatusBar(Activity activity){    View view = activity.getWindow().getDecorView();    view.setDrawingCacheEnabled(true);    view.buildDrawingCache();    Bitmap bmp = view.getDrawingCache();    Rect frame = new Rect();    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);    int statusBarHeight = frame.top;    int width = getScreenWidth(activity);    int height = getScreenHeight(activity);    Bitmap bp = null;    bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height            - statusBarHeight);    view.destroyDrawingCache();    return bp;}

6,各种渠道获取bitmap方法
/**
* 图片模糊效果
* @param context
* @param souBitmap
* @return
*/
public static Bitmap vagueImage(Context context, Bitmap souBitmap) {
if (souBitmap == null) return null;

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN){        Bitmap bitmap = souBitmap.copy(souBitmap.getConfig(),true);        final RenderScript rs = RenderScript.create(context);        final Allocation input = Allocation.createFromBitmap(rs, souBitmap, Allocation.MipmapControl.MIPMAP_NONE,                Allocation.USAGE_SCRIPT);        final Allocation output = Allocation.createTyped(rs, input.getType());        final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));        script.setRadius(25.f);// 0 < r <= 25        script.setInput(input);        script.forEach(output);        output.copyTo(bitmap);        return bitmap;    }    return souBitmap;}/** * 读取照片exif信息中的旋转角度 * @param path 照片路径 * @return */public static int readPictureDegree(String path) {    int degree  = 0;    try {        ExifInterface exifInterface = new ExifInterface(path);        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);        switch (orientation) {            case ExifInterface.ORIENTATION_ROTATE_90:                degree = 90;                break;            case ExifInterface.ORIENTATION_ROTATE_180:                degree = 180;                break;            case ExifInterface.ORIENTATION_ROTATE_270:                degree = 270;                break;        }    } catch (IOException e) {        e.printStackTrace();    }    return degree;}public static Bitmap toturn(Bitmap img, int degree){    Matrix matrix = new Matrix();    matrix.postRotate(degree); /*+90翻转90度*/    int width = img.getWidth();    int height =img.getHeight();    img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);    return img;}/** * 以最省内存的方式读取本地资源的图片 * @param context * @param resId * @return */public static Bitmap readBitMap(Context context, int resId) {    BitmapFactory.Options opt = new BitmapFactory.Options();    opt.inPreferredConfig = Bitmap.Config.RGB_565;    opt.inPurgeable = true;    opt.inInputShareable = true;    // 获取资源图片    InputStream is = context.getResources().openRawResource(resId);    return BitmapFactory.decodeStream(is, null, opt);}/** * 或者指定路径的文件bitmap * @param path  文件的路径 * @return */public static Bitmap myGetBitmap4(String path) {    BitmapFactory.Options options = new BitmapFactory.Options();  

// options.inJustDecodeBounds = true;
options.inSampleSize = 4;//图片宽高都为原来的二分之一,即图片为原来的四分之一
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
return bitmap;

}/** * 或者指定路径的文件bitmap * @param path  文件的路径 * @param inSampleSize 占用原图的比例(8 为 1/8) * @return */public static Bitmap myGetBitmap(String path,int inSampleSize) {    BitmapFactory.Options options = new BitmapFactory.Options();  

// options.inJustDecodeBounds = true;
options.inSampleSize = inSampleSize;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
return bitmap;

}/** * 从view 得到图片 * @param view * @return */public static Bitmap getBitmapFromView(View view) {    view.destroyDrawingCache();    view.measure(View.MeasureSpec.makeMeasureSpec(0,            View.MeasureSpec.UNSPECIFIED), View.MeasureSpec            .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());    view.setDrawingCacheEnabled(true);    Bitmap bitmap = view.getDrawingCache(true);    return bitmap;}/** Drawable → Bitmap   */public static Bitmap drawable2Bitmap(Drawable drawable) {    Bitmap bitmap = Bitmap.createBitmap(    drawable.getIntrinsicWidth(),    drawable.getIntrinsicHeight(),    drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);    Canvas canvas = new Canvas(bitmap);    // canvas.setBitmap(bitmap);    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());    drawable.draw(canvas);    return bitmap;}/** Bitmap---->Drawable */public static Drawable bitmap2Drawable(Bitmap bmp) {    Drawable drawable = new BitmapDrawable(bmp);    return drawable;}/** Bitmap → byte[] */public static byte[] Bitmap2Bytes(Bitmap bm){    ByteArrayOutputStream baos = new ByteArrayOutputStream();    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);    return baos.toByteArray();}/** byte[] → Bitmap */public static Bitmap Bytes2Bimap(byte[] b) {    if (b.length != 0) {        return BitmapFactory.decodeByteArray(b, 0, b.length);    } else {        return null;    }}

7,键盘的相关操作
/*控制键盘隐藏/
public static void hideKeyboard(Activity activity){
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager.isActive() && null != activity.getCurrentFocus()) {
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}

/** * 控制键盘显示  表示隐式显示输入窗口,非用户直接要求。窗口可能不显示。 * @param activity * @param view - 接受软键盘输入的视图View */public static void showKeyboard(Activity activity, View view){    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);    if (null != view) {        view.requestFocus();        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);    }}/** * 如果输入法打开则关闭,如果没打开则打开 * @param activity */public static void toggleKeyboard(Activity activity){    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);    inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);}

8,判断当前网络状态

public enum MyNetWorkState {    WIFI, MOBILE, NONE;}/** * 获取当前的网络状态 wifi,NONE,MOBILE * @return */public static MyNetWorkState getConnectState() {    ConnectivityManager manager = (ConnectivityManager) XAppManager.getAppManager().currentActivity().getSystemService(Context.CONNECTIVITY_SERVICE);    manager.getActiveNetworkInfo();    /** 当前wifi状态*/    NetworkInfo.State wifiState = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();    /** 当前移动网络状态*/    NetworkInfo.State mobileState = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();    if (wifiState != null && mobileState != null            && NetworkInfo.State.CONNECTED != wifiState            && NetworkInfo.State.CONNECTED == mobileState) {        return MyNetWorkState.MOBILE;    } else if (wifiState != null && mobileState != null            && NetworkInfo.State.CONNECTED != wifiState            && NetworkInfo.State.CONNECTED != mobileState) {        return MyNetWorkState.NONE;    } else if (wifiState != null && NetworkInfo.State.CONNECTED == wifiState) {        return MyNetWorkState.WIFI;    }    return MyNetWorkState.NONE;}/** * 检查网络连接状态 不可用时 会 提示 Toast * @param ctx * @return  false 不可用、 true 可用 */public static boolean isNetworkAvailable(Context ctx) {    Context mCtx = ctx ;    boolean isConnection=false;    try {        XLog.d("NetWorkUtil", "mContext = " + ctx + ";") ;        ConnectivityManager cm = (ConnectivityManager) ctx                .getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo info = cm.getActiveNetworkInfo();        if(info != null ){            isConnection= info.isAvailable();        }    } catch (Exception e) {        e.printStackTrace();    }    return isConnection;}

9,字符串的相关操作

/**获取人民币符号*/public static String getRMB(){    return "¥";}/**判断Str字符长度是否符合(小于或等于)*/public static boolean IsStrCharLength(String str,double length) {    if (length <= getStrCharLength(str)) {        return true;    }    return false;}/**得到Str字符长度*/public static double getStrCharLength(String str) {    double len = 0;    if (!isEmptyStr(str)) {        for (int i = 0; i < str.length(); i++) {            int temp = (int) str.charAt(i);            if (temp > 0 && temp < 127) {                len += 0.5;            } else {                len++;            }        }    }    return len;}/** * 判断str是否为空 * @param str * @return 空|"" :true、有:false; */public static boolean isEmptyStr(String str) {    if (str == null || str.length() == 0) {        return true;    }    return false;}/**从后面开始截取字符串 * @param str 要截取的字符串 * @param stripChars 截取的标记字符 * @return 截取后的字符串 */public static String subFromEndToStart(String str, String stripChars) {    if (XString.isEmptyStr(str)) {        return null;    }    int length = str.length();    int index = str.lastIndexOf(stripChars);    str = str.substring(index + 1, length);    if (str.contains("$")) {        int i = str.indexOf("$");        str = str.substring(0, i);    }    return str;}/**从后面开始截取字符串 * @param obj 要截取的字符串 * @param stripChars 截取的标记字符 * @return 截取后的字符串 */public static String subFromEndToStart(Object obj, String stripChars) {    String str = "";    if (obj == null) {        return null;    }    str = obj.getClass().getName();    if (isEmptyStr(str)) {        return null;    }    int length = str.length();    int index = str.lastIndexOf(stripChars);    return str.substring(index + 1, length);}/**获取当前类的名字 * @param obj 类的实例 * @return 类的名字 */public static String getClassName(Object obj) {    String stripChars = ".";    String str = "";    if (obj == null) {        return null;    }    str = obj.getClass().getName();    if (isEmptyStr(str)) {        return null;    }    int length = str.length();    int index = str.lastIndexOf(stripChars);    str = str.substring(index + 1, length);    if (str.contains("$")) {        int i = str.indexOf("$");        str = str.substring(0, i);    }    return str;}/** * 获取strc【字符串】 在string【总字符串】中出现的次数 * @param string 【总字符串】 * @param strC【字符串】 * @return 出现的次数 */public static int getStrCForStingCount(String string, String strC) {    int count = 0;    int index = -1;    int length = -1;    while (count != -1) {        index = string.indexOf(strC);        if (index == -1) {            break;        }        length = strC.length();        string = string.substring(index + length);        count++;    }    return count;}/** * 分解服务器mStrUrls 连接串数据 * @param mStrUrls mStrUrls 连接串数据 * @return map Map<Integer, String> */public static Map<Integer, String> getPicUrlToMap(String mStrUrls) {    Map<Integer, String> tempMap = new HashMap<Integer, String>();    String pics[];    if (mStrUrls.contains(";")) {        pics = mStrUrls.split(";");        for (int i = 0; i < pics.length; i++) {            tempMap.put(i, pics[i]);        }    } else {        tempMap.put(0, mStrUrls);    }    return tempMap;}/** * 获取Activity 名称 * @param activity activity实例 * @return strActivityName Activity 名称 */public static String getActivtyName(Activity activity) {    String strActivityName = activity.getClass().toString() ;    strActivityName = strActivityName.substring(strActivityName.lastIndexOf(".") + 1, strActivityName.length()) ;    return strActivityName ;}/** * 处理普通String * @param name 汪守炤 * @return *守炤 */public static String getStringWithstar(String name){    if (isEmptyStr(name)) return "";    if (name.length() < 1) return name;    return "*" + name.substring(1, name.length());}/** * 处理电话号码 * @param phone 18800008888 * @return 188****8888 */public static String getPhoneWithstar(String phone){    if (isEmptyStr(phone)) return "";    if (phone.length() < 6) return phone;    return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4, phone.length());}/** * 处理IDCARD * @param idcard 330127199201065133 * @return 33012719******5133 */public static String getIdCardWithstar(String idcard){    if (isEmptyStr(idcard)) return "";    if (idcard.length() < 8) return idcard;    return idcard.substring(0, 8) + "******" + idcard.substring(idcard.length() - 6, idcard.length());}/** * 处理银行卡号 * @param bankNum 6225885825652356 * @return 6225 **** **** 2356 */public static String getBankNumWithstar(String bankNum) {    if (isEmptyStr(bankNum)) return "";    if (bankNum.length() < 8) return bankNum;    return bankNum.substring(0, 4) + " **** **** " + bankNum.substring(bankNum.length() - 4, bankNum.length());}/**获取去除了城市名市【市】的城市名 * 如:【杭州市】-->【杭州】 * @param strCityName 城市名 */public static String getQuDiaoZuiHouWeiSHI(String strCityName){    if (isEmptyStr(strCityName)) {        return "" ;    }    if (strCityName.endsWith("市")) {        strCityName = strCityName.substring(0, strCityName.length()-1) ;    }    return strCityName ;}/**验证字符串---正则*/public static boolean validateStringWithRule(String password,String rule){    Pattern pattern = Pattern.compile(rule);    Matcher matcher = pattern.matcher(password);    return matcher.matches();}/**大数据指数形式转回正常格式--两位小数*/public static double getDouble(double value){    return Double.valueOf(getDoubleString(value));}public static String getDoubleString(double value){    DecimalFormat df = new DecimalFormat("##0.00");    //指数格式转回普通格式    java.text.NumberFormat nf = java.text.NumberFormat.getInstance();    nf.setGroupingUsed(false);    return df.format(Double.valueOf(nf.format(value)));}

10,跳转至手机系统界面
/**
* 跳转拨号页面
* @param phoneNumber phone
*/
public static void dialPhoneNumber(Context context, String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(“tel:” + phoneNumber));
if (intent.resolveActivity(context.getPackageManager()) != null) {
context.startActivity(intent);
}
}

/** * 跳转系统设置界面 */private void tell(Context context) {    Intent intent = new Intent("/");    ComponentName cm = new ComponentName("com.android.settings",            "com.android.settings.RadioInfo");    intent.setComponent(cm);    intent.setAction("android.intent.action.VIEW");    context.startActivity(intent);}/** *  com.android.settings.AccessibilitySettings 辅助功能设置   com.android.settings.ActivityPicker 选择活动   com.android.settings.ApnSettings APN设置   com.android.settings.ApplicationSettings 应用程序设置   com.android.settings.BandMode 设置GSM/UMTS波段   com.android.settings.BatteryInfo 电池信息   com.android.settings.DateTimeSettings 日期和坝上旅游网时间设置   com.android.settings.DateTimeSettingsSetupWizard 日期和时间设置   com.android.settings.DevelopmentSettings 应用程序设置=》开发设置   com.android.settings.DeviceAdminSettings 设备管理器   com.android.settings.DeviceInfoSettings 关于手机   com.android.settings.Display 显示——设置显示字体大小及预览   com.android.settings.DisplaySettings 显示设置   com.android.settings.DockSettings 底座设置   com.android.settings.IccLockSettings SIM卡锁定设置   com.android.settings.InstalledAppDetails 语言和键盘设置   com.android.settings.LanguageSettings 语言和键盘设置   com.android.settings.LocalePicker 选择手机语言   com.android.settings.LocalePickerInSetupWizard 选择手机语言   com.android.settings.ManageApplications 已下载(安装)软件列表   com.android.settings.MasterClear 恢复出厂设置   com.android.settings.MediaFormat 格式化手机闪存   com.android.settings.PhysicalKeyboardSettings 设置键盘   com.android.settings.PrivacySettings 隐私设置   com.android.settings.ProxySelector 代理设置   com.android.settings.RadioInfo 手机信息   com.android.settings.RunningServices 正在运行的程序(服务)   com.android.settings.SecuritySettings 位置和安全设置   com.android.settings.Settings 系统设置   com.android.settings.SettingsSafetyLegalActivity 安全信息   com.android.settings.SoundSettings 声音设置   com.android.settings.TestingSettings 测试——显示手机信息、电池信息、使用情况统计、Wifi information、服务信息   com.android.settings.TetherSettings 绑定与便携式热点   com.android.settings.TextToSpeechSettings 文字转语音设置   com.android.settings.UsageStats 使用情况统计   com.android.settings.UserDictionarySettings 用户词典   com.android.settings.VoiceInputOutputSettings 语音输入与输出设置   com.android.settings.WirelessSettings 无线和网络设置 */

11,时间处理的相关工具
/**
* 自定DataPicker获取日期 转换
* @param calendar
* @return
*/
public static String getFormatTime(Calendar calendar) {
String parten = “00”;
DecimalFormat decimal = new DecimalFormat(parten);
// 设置日期的显示
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1 ;
int day = calendar.get(Calendar.DAY_OF_MONTH)+1;

    switch (month) {        case 1:            if (day == 32) {                return year + "-0" + (month + 1) +"-0"+1;            }            break;        case 2:            if (day == 29) {                return year + "-0" + (month + 1) +"-0"+1;            }else if(day == 30){                return year + "-0" + (month + 1) +"-0"+1;            }else if(day == 31){                return year + "-0" + (month + 1) +"-0"+1;            }            break;        case 3:            if (day == 32) {                return year + "-0" + (month + 1) +"-0"+1;            }            break;        case 4:            if (day == 31) {                return year + "-0" + (month + 1) +"-0"+1;            }            break;        case 5:            if (day == 32) {                return year + "-0" + (month + 1) +"-0"+1;            }            break;        case 6:            if (day == 31) {                return year + "-0" + (month + 1) +"-0"+1;            }            break;        case 7:            if (day == 32) {                return year + "-0" + (month + 1) +"-0"+1;            }            break;        case 8:            if (day == 32) {                return year + "-0" + (month + 1) +"-0"+1;            }            break;        case 9:            if (day == 31) {                return year + "-" + (month + 1) +"-0"+1;            }            break;        case 10:            if (day == 32) {                return year + "-" + (month + 1) +"-0"+1;            }            break;        case 11:            if (day == 31) {                return year + "-" + (month + 1) +"-0"+1;            }            break;        case 12:            if (day == 32) {                return (year+1) + "-0" + 1 +"-0"+1;            }            break;        default:            break;    }    return year + "-" + decimal.format(month) + "-"            + decimal.format(day);}/** * 是否超过现在时间点 * @param timePoint 开始时间 * * @param formatTimePoint   "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E", * @return */public static boolean isTimeOut(String timePoint ,String formatTimePoint) {    boolean isTimeOut = false;    long timePointMillis = getMillisFromDate(timePoint, formatTimePoint) ;    if (timePointMillis != -1 && timePointMillis <= System.currentTimeMillis() ) {        isTimeOut = true;    }    return isTimeOut ;}/** * begin 时间点 是否超过(不等于) end 时间点 * * @param begin 开始时间 * @param formatBegin   "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E", * * @param end   结束时间 * @param formatEnd "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E", * @return */public static boolean isTimeOut(String begin ,String formatBegin ,String end ,String formatEnd) {    boolean isTimeOut = false;    long beginMillis = getMillisFromDate(begin, formatBegin) ;    long endMillis = getMillisFromDate(end, formatEnd) ;    if (beginMillis != -1 && endMillis != -1 && beginMillis > endMillis ) {        isTimeOut = true;    }    return isTimeOut ;}/** * begin 时间点 是否超过(等于) end 时间点 * * @param begin 开始时间 * @param formatBegin   "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E", * * @param end   结束时间 * @param formatEnd "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E", * @return */public static boolean isTimeOutAndEqual(String begin ,String formatBegin ,String end ,String formatEnd) {    boolean isTimeOut = false;    long beginMillis = getMillisFromDate(begin, formatBegin) ;    long endMillis = getMillisFromDate(end, formatEnd) ;    if (beginMillis != -1 && endMillis != -1 && beginMillis >= endMillis ) {        isTimeOut = true;    }    return isTimeOut ;}/** * 是否是现在时间段 * @param begin 开始时间 * * @param formatBegin   "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E", * * @param end   结束时间 * * @param formatEnd "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E", * * @return */public static boolean isNow(String begin ,String formatBegin ,String end ,String formatEnd) {    boolean isNow = false;    long beginMillis = getMillisFromDate(begin, formatBegin) ;    long endMillis = getMillisFromDate(end, formatEnd) ;    if (beginMillis != -1 && endMillis != -1 && beginMillis <= System.currentTimeMillis() && endMillis >= System.currentTimeMillis()) {        isNow = true;    }    return isNow ;}/** * * @param date      200612241200    ,20061224   ,2006-12-24, *                  2006年12月24日"    ,12月24日" ; *                  2006-12-24 12:00:59 星期四 ,2006年12月24日 12时00分59秒 星期四, * * @param format    "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E", * * @return */public static int getAge(String date ,String format) {    if (XString.isEmptyStr(date) || "-1".equals(date)) {        return 0;    }    long dateMillis = getMillisFromDate(date, format) ;    long days= ( System.currentTimeMillis() - dateMillis ) / (1000*60*60*24);   //  得到总天数    int years= (int) ( days / 365 ) ;   //  计算出年数    return years ;}/** * 将日期转化为毫秒 * @param date      200612241200    ,20061224   ,2006-12-24, *                  2006年12月24日"    ,12月24日" ; *                  2006-12-24 12:00:59 星期四 ,2006年12月24日 12时00分59秒 星期四, * * @param format    "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E ", * * @return */public static long getMillisFromDate(String date ,String format) {    if (XString.isEmptyStr(date) || "-1".equals(date)) {        return 0;    }    long millionSeconds = -1;    try {        SimpleDateFormat sdf = new SimpleDateFormat(format);        millionSeconds = sdf.parse(date).getTime() ;    } catch (ParseException e) {        e.printStackTrace();    }    return millionSeconds;}/** * 将时间日期转化格式 * @param time 时间(2013-09-12 12:00 或者任意) * @param fromFormat 时间传进的格式( *                  "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E","yyyy年MM月dd日 HH时mm分ss秒 E ") * @param toFormat 时间传出的格式( *                  "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E" ,"yyyy年MM月dd日 HH时mm分ss秒 E ") * @return */public static String getFormatTime(String time, String fromFormat, String toFormat){    if (XString.isEmptyStr(time) || "-1".equals(time)) {        return "" ;    }    long haoMiao = getMillisFromDate(time, fromFormat) ;    return getCalendarFromMillis(haoMiao, toFormat) ;}/** * 毫秒数 转 日期 * @param millis        200612241200    ,20061224   ,2006-12-24, *                  2006年12月24日"    ,12月24日" ; *                  2006-12-24 12:00:59 星期四 ,2006年12月24日 12时00分59秒 星期四, * * @param format    "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E ", * * @return  yyyy-MM-dd HH:mm:ss */public static String getCalendarFromMillis(long millis, String format){    if (String.valueOf(millis).length() == 10)        millis = millis * 1000;    SimpleDateFormat formatter = new SimpleDateFormat(format);    String riQi = formatter.format(millis);    return riQi ;}/** * 获取几天后的日期 */public static String getCalendarAfterDays(int days, String format){    SimpleDateFormat formatter = new SimpleDateFormat(format);    Calendar calendar = Calendar.getInstance();    calendar.setTimeInMillis(System.currentTimeMillis());    calendar.add(Calendar.DATE, days);    String riQi = formatter.format(calendar.getTimeInMillis());    return riQi ;}/**获取今天的日期 *  @param format   "yyyyMMddhhmm"  ,"yyyyMMdd" ,"yyyy-MM-dd", *                  "yyyy年MM月dd日"   ,"MM月dd日" ; *                  "yyyy-MM-dd HH:mm:ss E"     ,"yyyy年MM月dd日 HH时mm分ss秒 E " *                  "yyyy-MM-dd HH:mm:ss" * * @return  yyyy-MM-dd HH:mm:ss */public static String getToDay(String format) {    return getCalendarFromMillis(System.currentTimeMillis(), format);}/** 将字符串转换为日期*/public static Date getData(String time, String dateFormat) {    Date date = null;    SimpleDateFormat format = new SimpleDateFormat(dateFormat);// 定义日期格式    try {        date = format.parse(time);// 将字符串转换为日期    } catch (ParseException e) {        e.printStackTrace();    }    return date;}/** *将字符串转换为星期几 * @param time * @return */public static String getWeek(String time, String dateFormat) {    Date date = getData(time, dateFormat);    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");    String week = sdf.format(date);    return week;}/** * 将日期转换为星期几 * @param date * @return */public static String getWeek(Date date) {    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");    String week = sdf.format(date);    return week;}/**判断time是否在num个月后 * 如果是,返回true * */public static boolean isMonthsOut(long time,int num){    Calendar cal = Calendar.getInstance();    long systemTime = System.currentTimeMillis();    cal.setTimeInMillis(systemTime);    cal.add(Calendar.MONTH, num);    long afterTime = cal.getTimeInMillis();    return time < afterTime;}/** * 获取距离现在多少天 24小时 * @param time * @return */public static int getDaysToNow(long time){    long systemTime = System.currentTimeMillis();    return (int)((time - systemTime) / (24 * 60 * 60 *1000)) + 1;}/** * 判断现在是否是股票交易时间 * 9:30-11:30、13:00-15:00 * 除去双休日 * @return */public static boolean isStockTime(){    Calendar calendar = Calendar.getInstance();    long systemTime = System.currentTimeMillis();    calendar.setTimeInMillis(systemTime);    int hour = calendar.get(Calendar.HOUR_OF_DAY);    int min = calendar.get(Calendar.MINUTE);    int day = calendar.get(Calendar.DAY_OF_WEEK);    if (day == 1 || day == 7)        return false;    if (hour == 11 && min <= 30)        return true;    if (hour == 9 && min >= 30)        return true;    if (hour == 10)        return true;    if (hour > 12 && hour < 15)        return true;    return false;}//获取jin天public static String todayTime(){    Date date=new Date();//取时间    Calendar calendar = new GregorianCalendar();    calendar.setTime(date);    calendar.add(calendar.DATE,0);//把日期往后增加一天.整数往后推,负数往前移动    date=calendar.getTime(); //这个时间就是日期往后推一天的结果    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");    return formatter.format(date);}

12,TextView的加线处理
/*下划线/
public static void setXiaHuaXian(TextView textView) {
if (textView!=null)
textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); // 下划线
}

/**抗锯齿*/public static void setKangJuCi(TextView textView) {    if (textView!=null)         textView.getPaint().setAntiAlias(true);// }/**中划线*/public static void setZhongHuaXian(TextView textView) {    if (textView!=null)         textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); // 中划线}/**设置中划线并加清晰*/public static void setZhongHuaXianQingXi(TextView textView) {    if (textView!=null)         textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰}/**取消设置的的划线*/public static void setQuXiaoHuaXian(TextView textView) {    if (textView!=null)         textView.getPaint().setFlags(0); // 取消设置的的划线}/**设置输入框的问题长度*/public void mySetEditMiddleMaxLength(EditText editText, int length) {    InputFilter[] filters = { new InputFilter.LengthFilter(length) };    if (editText != null) {        editText.setFilters(filters);    }}/** *  设置textView 的DrawableLeft... * @param textView   * @param drawableId 资源图片的Id * @param weizi 0:左,1:上,2:右,3:下 * @param activity  * @throws NotFoundException */public static void setDrawable(Activity activity, TextView textView ,int drawableId, int weizi, int pad) throws NotFoundException{

// /// 这一步必须要做,否则不会显示.
Drawable mDrawableYes = activity.getResources().getDrawable(drawableId);
mDrawableYes.setBounds(0, 0, mDrawableYes.getMinimumWidth(), mDrawableYes.getMinimumHeight());
switch (weizi) {
case 0:
textView.setCompoundDrawables(mDrawableYes,null,null,null);
break;
case 1:
textView.setCompoundDrawables(null,mDrawableYes,null,null);
break;
case 2:
textView.setCompoundDrawables(null,null,mDrawableYes,null);
break;
case 3:
textView.setCompoundDrawables(null,null,null,mDrawableYes);
break;
default:
break;
}
textView.setCompoundDrawablePadding(pad);
}
13,缓存相关
public static String PREFERENCE_NAME = “CommonSharedPreference”;

public static boolean putString(Context context, String key, String value) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    SharedPreferences.Editor editor = settings.edit();    editor.putString(key, value);    return editor.commit();}public static String getString(Context context, String key) {    return getString(context, key, null);}public static String getString(Context context, String key, String defaultValue) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    return settings.getString(key, defaultValue);}public static boolean putInt(Context context, String key, int value) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    SharedPreferences.Editor editor = settings.edit();    editor.putInt(key, value);    return editor.commit();}public static int getInt(Context context, String key) {    return getInt(context, key, -1);}public static int getInt(Context context, String key, int defaultValue) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    return settings.getInt(key, defaultValue);}public static boolean putLong(Context context, String key, long value) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    SharedPreferences.Editor editor = settings.edit();    editor.putLong(key, value);    return editor.commit();}public static long getLong(Context context, String key) {    return getLong(context, key, -1);}public static long getLong(Context context, String key, long defaultValue) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    return settings.getLong(key, defaultValue);}public static boolean putFloat(Context context, String key, float value) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    SharedPreferences.Editor editor = settings.edit();    editor.putFloat(key, value);    return editor.commit();}public static float getFloat(Context context, String key) {    return getFloat(context, key, -1);}public static float getFloat(Context context, String key, float defaultValue) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    return settings.getFloat(key, defaultValue);}public static boolean putBoolean(Context context, String key, boolean value) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    SharedPreferences.Editor editor = settings.edit();    editor.putBoolean(key, value);    return editor.commit();}public static boolean getBoolean(Context context, String key) {    return getBoolean(context, key, false);}public static boolean getBoolean(Context context, String key, boolean defaultValue) {    SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);    return settings.getBoolean(key, defaultValue);}大致项目中用的比较多的就这些了,欢迎大家补充。