android Utils工具类方法大集合

/**
* 提供精确的小数位四舍五入处理,保留几位小数。
*
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
double bb = b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
return bb;
}

/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。
*
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}

/**
* 提供精确的乘法运算。
*
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}

/**
* 检查手机上是否安装了指定的软件
*
* @param context
* @param packageName :应用包名
* @return
*/
public static boolean isAvilible(Context context, String packageName) {
// 获取packagemanager
PackageManager packageManager = context.getPackageManager();
// 获取所有已安装程序的包信息
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
// 用于存储所有已安装程序的包名
List<String> packageNames = new ArrayList<String>();
// 从pinfo中将包名字逐一取出,压入pName list中
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
}
// 判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE
return packageNames.contains(packageName);
}

/**
* 根据一个网络连接(String)获取bitmap图像
*
* @param imageUri
* @return
*/
public static Bitmap getbitmap(String imageUri) {
Log.v("", "getbitmap:" + imageUri);
// 显示网络上的图片
Bitmap bitmap = null;
try {
URL myFileUrl = new URL(imageUri);
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();

Log.v("", "image download finished." + imageUri);
} catch (OutOfMemoryError e) {
e.printStackTrace();
bitmap = null;
} catch (IOException e) {
e.printStackTrace();
Log.v("", "getbitmap bmp fail---");
bitmap = null;
}
return bitmap;
}

/**
* 将字符串转换成Bitmap类型
*
* @param
* @return
*/
public static Bitmap stringtoBitmap(String string) {
Bitmap bitmap = null;
try {
byte[] bitmapArray;
bitmapArray = Base64.decode(string, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}

return bitmap;
}

/**
* 将Bitmap转换成字符串
*
* @param bitmap
* @return
*/
public static String bitmaptoString(Bitmap bitmap) {
String string = null;
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
byte[] bytes = bStream.toByteArray();
string = Base64.encodeToString(bytes, Base64.DEFAULT);
return string;
}

/**
* 返回当前程序版本名-V2 三段修改---ex 5.2---5.21
* support 7.8.8.1, 7.18.8.1, 17.18.8.1 modified by chenhong, 2018-5-25
*/
public static String getAppVersionNameV2(Context context) {
String versionCode = "";
try {
PackageInfo pi = MyApp.getAppContext().getPackageManager().getPackageInfo(MyApp.getAppContext().getPackageName(), 0);
versionCode = pi.versionName;
} catch (Exception e) {
e.printStackTrace();
}

if (!TextUtils.isEmpty(versionCode)) {
int firstDotIndex = versionCode.indexOf(".");
if (firstDotIndex > -1) {
String mainVersion = versionCode.substring(0, firstDotIndex);

String subVersion = "";
if (versionCode.length() > firstDotIndex + 1) {
subVersion = versionCode.substring(firstDotIndex + 1);
subVersion = subVersion.replace(".", "");
}
versionCode = mainVersion + "." + subVersion;

int length = versionCode.length();
int dotIndex = versionCode.indexOf(".");
if (dotIndex == length - 1) {
versionCode += "00";
} else if (dotIndex == length - 2) {
versionCode += "0";
}
} else {
versionCode += ".00";
}
}
return versionCode;
}

/**
* 获取IP地址
*
* @param context
* @return
*/
public static String getIPAddress(Context context) {
NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
try {
//Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}

} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
return ipAddress;
}
} else {
//当前无网络连接,请在设置中打开网络
}
return null;
}

/**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
public static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}

/**
* 获取屏幕高度
*
* @param context
* @return
*/
public static int getWindowHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int windowHeight = wm.getDefaultDisplay().getHeight();
return windowHeight;
}

/**
* 获取屏幕宽度
*
* @param context
* @return
*/
public static int getWindowWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int windowWidth = wm.getDefaultDisplay().getWidth();
return windowWidth;
}

/**
* json字符串转map
*
* @param jsonString
* @return
*/
public static Map transStringToMap(String jsonString) {
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
map = gson.fromJson(jsonString, map.getClass());
return map;
}

/**
* 计算两个时间相隔多少天
*
* @return
*/
public static String getDayNumberStr(String nowDate, String createDate) {
String str = "";
int strDay = 0;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d1 = df.parse(nowDate);
Date d2 = df.parse(createDate);
long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
// System.out.println("" + days + "天" + hours + "小时" + minutes + "分");
str = days + "";
strDay = Integer.parseInt(str) + 1;
} catch (Exception e) {
e.printStackTrace();
}

return strDay + "";
}

/**
* 获得当天0点时间
*/
public static int getTimesmorning() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return (int) (cal.getTimeInMillis() / 1000);
}

/**
* 获得当天24点时间
*/
public static int getTimesnight() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 24);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return (int) (cal.getTimeInMillis() / 1000);

}

/**
* 获得当天时间
*/
public static String getTodayDate() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
String date = df.format(new Date());// new Date()为获取当前系统时间
return date;
}


/**
* 判断当前时间是否在时间date之前 date1 7点 date2 8点
* 时间格式 2005-4-21 16:16:34 "yyyy-MM-dd HH:mm:ss"
*
* @param date
* @return
* @throws ParseException
*/
public static boolean isDateBefore(String date) throws ParseException {
Date date1 = new Date();//当前时间
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return date1.before(df.parse(date));
}

/**
* 判断当前时间是否在时间date之后 date1 8点 date2 5点
*
* @param date
* @return
* @throws ParseException
*/
public static boolean isDateAfter(String date) throws ParseException {
Date date1 = new Date();//当前时间
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return (df.parse(date)).before(date1);
}

/**
* 大小写转换
*
* @param UpperCasestr
* @return
* @throws Exception
*/
public static String toUpperCase(String UpperCasestr) throws Exception {
return UpperCasestr.toUpperCase().toString();
}

/**
* 去除字符串空格
*
* @return
*/
public static String removeAllSpace(String str) {
String tmpstr = str.replace(" ", "");
return tmpstr;
}

/**
* 获取当前网络类型
*
* @return
*/
public static String getNetworkTypeAll() {
String strNetworkType = "";
ConnectivityManager cm = (ConnectivityManager) MyApp.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
strNetworkType = "WIFI";
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
String _strSubTypeName = networkInfo.getSubtypeName();

// TD-SCDMA networkType is 17
int networkType = networkInfo.getSubtype();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
strNetworkType = "2G";
break;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11 : replace by 12
case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
strNetworkType = "3G";
break;
case TelephonyManager.NETWORK_TYPE_LTE: //api<11 : replace by 13
strNetworkType = "4G";
break;
default:
if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
strNetworkType = "3G";
} else {
strNetworkType = _strSubTypeName;
}
break;
}
}
}
return strNetworkType;
}


/**
* 获取sim卡运营商信息
*/
public static String getSimOperator() {
String operator = "";
try {
TelephonyManager telManager = (TelephonyManager) MyApp.mContext.getSystemService(Context.TELEPHONY_SERVICE);
operator = telManager.getSimOperator();
if (operator != null) {
if (operator.equals("46000") || operator.equals("46002") || operator.equals("46007")) {
operator = "中国移动";
} else if (operator.equals("46001")) {
operator = "中国联通";
} else if (operator.equals("46003")) {
operator = "中国电信";
}
}
} catch (Exception e) {
e.printStackTrace();
return operator;
}
return operator;
}

/**
* 强制隐藏输入法键盘
*
* @param context Context
* @param view EditText
*/
public void hideInput(Context context, View view) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
坚持原创技术分享,您的支持将鼓励我继续创作!