String的常用工具类

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 常用工具类
 */
public class Utils {
    /**
     * 传入出生日期获得年龄
     * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
     * Date date = null;
     * try {
     * date = sdf.parse(dateStr);
     * } catch (ParseException e) {
     * e.printStackTrace();
     * }
     *
     * @param birthDate
     * @return
     */
    public static int getAge(Date birthDate) {
        int age = 0;
        Date now = new Date();
        SimpleDateFormat format_y = new
                SimpleDateFormat("yyyy");
        SimpleDateFormat format_M = new
                SimpleDateFormat("MM");
        String birth_year =
                format_y.format(birthDate);
        String this_year =
                format_y.format(now);
        String birth_month =
                format_M.format(birthDate);
        String this_month =
                format_M.format(now);
        // 初步,估算
        age = Integer.parseInt(this_year) - Integer.parseInt(birth_year);
        // 如果未到出生月份,则age - 1
        if (this_month.compareTo(birth_month) < 0) age -= 1;
        if (age < 0) age = 0;
        return age;
    }



    /**
     * 格式化字符串 to 地区、属性 ID
     *
     * @param str
     * @return
     */
    public static String[] formatId(String str) {
        String[] strArr = str.split(",");
        if (strArr != null && str != null && str.length() > 0 && strArr.length > 0) {
            for (int i = 0; i < strArr.length; i++) {
                strArr[i] = strArr[i].replace("[", "").replace("]", "");
            }
        } else {
            strArr = new String[1];
            strArr[0] = "";
        }
        return strArr;
    }

    /**
     * 格式化字符串 to 地区、属性   名称
     *
     * @param str
     * @return
     */
    public static String[] formatName(String str) {
        String[] strArr = str.split(" ");
        if (strArr != null && str != null && str.length() > 0 && strArr.length > 0) {
            for (int i = 0; i < strArr.length; i++) {
                strArr[i] = strArr[i];
            }
        } else {
            strArr = new String[1];
            strArr[0] = "";
        }
        return strArr;
    }

    public static Bitmap getBitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

    //当前应用是否处于前台
    public static boolean isForeground(Context context) {
        if (context != null) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
            String currentPackageName = cn.getPackageName();
            if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName())) {
                return true;
            }
            return false;
        }
        return false;
    }

    public static String accuracy(double num, double total, int scale) {
        DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
        //可以设置精确几位小数
        df.setMaximumFractionDigits(scale);
//        //模式 例如四舍五入
//        df.setRoundingMode(RoundingMode.HALF_UP);
        double accuracy_num = num / total * 100;
        return df.format(accuracy_num);
    }

    /**
     * 四舍五入.
     *
     * @param number  原数
     * @param decimal 保留几位小数
     * @return 四舍五入后的值
     */
    public static BigDecimal round(double number, int decimal) {
        return new BigDecimal(number).setScale(decimal, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 根据手机的分辨率从 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);
    }

}

你可能感兴趣的:(String的常用工具类)