android Utils工具类方法大集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/**
* 提供精确的小数位四舍五入处理,保留几位小数。
*
* @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);
}
坚持原创技术分享,您的支持将鼓励我继续创作!