Util.java
23 KB
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
package com.chudiangameplay.android.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.chudiangameplay.android.MyApplication;
import com.chudiangameplay.android.R;
import com.chudiangameplay.android.bean.ProductInfo;
import com.chudiangameplay.android.tool.CommToast;
import com.chudiangameplay.android.tool.Log;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkDownload;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Administrator on 2018/6/12.
*/
public class Util {
//检查是否包含敏感词
public static boolean checkWords(List<String> map, String string) {
if (map == null || TextUtils.isEmpty(string)) return false;
for (int i = 0; i < map.size(); i++) {
if (!TextUtils.isEmpty(map.get(i)) && string.contains(map.get(i))) {
return true;
}
}
return false;
}
//获取后台自定义渠道编号
public static String getPlatform(String _vendor) {
String platform = "";
switch (_vendor) {
case "10000":
platform = "5";
break;
case "10001":
platform = "501";
break;
case "10002":
platform = "502";
break;
case "10003":
platform = "503";
break;
case "10004":
platform = "504";
break;
case "10005":
platform = "505";
break;
case "10006":
platform = "506";
break;
case "10007":
platform = "507";
break;
case "10008":
platform = "508";
break;
case "10009":
platform = "509";
break;
case "10010":
platform = "510";
break;
case "10011":
platform = "511";
break;
case "10012":
platform = "512";
break;
case "10013":
platform = "513";
break;
case "10014":
platform = "514";
break;
case "10015":
platform = "515";
break;
case "10016":
platform = "516";
break;
case "10017":
platform = "517";
break;
case "10018":
platform = "518";
break;
case "10019":
platform = "519";
break;
case "10020":
platform = "520";
break;
case "10021":
platform = "521";
break;
case "10022":
platform = "522";
break;
case "10023":
platform = "523";
break;
case "10024":
platform = "524";
break;
case "10025":
platform = "525";
break;
case "10026":
platform = "526";
break;
}
return platform;
}
/**
* 程序是否在前台运行
*/
public static boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
String packageName = context.getApplicationContext().getPackageName();
//获取Android设备中所有正在运行的App
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null)
return false;
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(packageName)
&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public static String getWebviewVersion() {
String webSettings = WebSettings.getDefaultUserAgent(MyApplication.context);
int beginIndex = webSettings.indexOf("Chrome");
int endIndex = webSettings.indexOf("Mobile");
return webSettings.substring(beginIndex, endIndex).trim();
}
public static float getDensityDpi() {
return MyApplication.context.getResources().getDisplayMetrics().densityDpi;
}
/**
* 获取app当前的渠道号或application中指定的meta-data
*
* @return 如果没有获取成功(没有对应值,或者异常),则返回值为空
*/
public static String getAppMetaData(Context context, String key) {
if (context == null || TextUtils.isEmpty(key)) {
return null;
}
String channelNumber = null;
try {
PackageManager packageManager = context.getPackageManager();
if (packageManager != null) {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
if (applicationInfo != null) {
if (applicationInfo.metaData != null) {
channelNumber = applicationInfo.metaData.get(key) + "";
}
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return channelNumber;
}
public static void closeApp() {
// android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
//获取星座
public static String getStar(int month, int day) {
String star = "";
if (month == 1 && day >= 20 || month == 2 && day <= 18) {
star = "水瓶座";
}
if (month == 2 && day >= 19 || month == 3 && day <= 20) {
star = "双鱼座";
}
if (month == 3 && day >= 21 || month == 4 && day <= 19) {
star = "白羊座";
}
if (month == 4 && day >= 20 || month == 5 && day <= 20) {
star = "金牛座";
}
if (month == 5 && day >= 21 || month == 6 && day <= 21) {
star = "双子座";
}
if (month == 6 && day >= 22 || month == 7 && day <= 22) {
star = "巨蟹座";
}
if (month == 7 && day >= 23 || month == 8 && day <= 22) {
star = "狮子座";
}
if (month == 8 && day >= 23 || month == 9 && day <= 22) {
star = "处女座";
}
if (month == 9 && day >= 23 || month == 10 && day <= 23) {
star = "天秤座";
}
if (month == 10 && day >= 24 || month == 11 && day <= 22) {
star = "天蝎座";
}
if (month == 11 && day >= 23 || month == 12 && day <= 21) {
star = "射手座";
}
if (month == 12 && day >= 22 || month == 1 && day <= 19) {
star = "摩羯座";
}
return star;
}
//数字显示处理,去掉末尾的0
public static String numDecimalFormat(String num) {
if (TextUtils.isEmpty(num)) {
num = "";
} else {
if (num.contains(".")) {
while (num.endsWith("0")) {
num = num.substring(0, num.length() - 1);
}
while (num.endsWith(".")) {
num = num.substring(0, num.length() - 1);
}
}
}
return num;
}
//数字显示处理,保留几位小数点 length: 几位小数点
public static String numDecimalFormat(String num, int length) {
try {
String decimalStr = "0";
if (length > 0) {
decimalStr += ".";
for (int i = 0; i < length; i++) {
decimalStr += "0";
}
}
DecimalFormat format = new DecimalFormat(decimalStr);
String a = format.format(new BigDecimal(num));
return a;
} catch (Exception e) {
return num;
}
}
public static boolean isWifi(Context context) {
if (getNetworkClass(context) == ConnectivityManager.TYPE_WIFI) {
return true;
} else {
return false;
}
}
private static int getNetworkClass(Context context) {
int networkType = ConnectivityManager.TYPE_MOBILE;
try {
final NetworkInfo network = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (network != null && network.isAvailable() && network.isConnected()) {
int type = network.getType();
if (type == ConnectivityManager.TYPE_WIFI) {
networkType = ConnectivityManager.TYPE_WIFI;
} else if (type == ConnectivityManager.TYPE_MOBILE) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
networkType = telephonyManager.getNetworkType();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
Log.i("networkType:" + networkType);
return networkType;
}
//万 级转换
public static String numberFormat(int num) {
String numStr = num + "";
if (num >= 10000) {
DecimalFormat format = new DecimalFormat("0.0");
numStr = format.format(num / 10000) + "万";
}
return numStr;
}
public static Bitmap drawableToBitmap(Drawable drawable) {
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
System.out.println("Drawable转Bitmap");
Bitmap.Config config =
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
//注意,下面三行代码要用到,否则在View或者SurfaceView里的canvas.drawBitmap会看不到图
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void copy(Context context, String msg, boolean... ishowTost) {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("code", msg);
clipboard.setPrimaryClip(clip);
if (ishowTost.length > 0 && (boolean) ishowTost[0]) {
CommToast.showToast(context, "已复制");
}
}
/**
* 获取手机大小(分辨率)
*/
public static DisplayMetrics getScreenPix(Activity activity) {
DisplayMetrics displaysMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displaysMetrics);
return displaysMetrics;
}
/**
* 判断SDCard是否可用
*/
public static boolean existSDCard() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/**
* 将dip或dp值转换为px值,保证尺寸大小不变
*
* @param dipValue
* @return
*/
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
// 获取手机状态栏高度
public static int getStatusBarHeight(Context context) {
Class<?> c = null;
Object obj = null;
java.lang.reflect.Field field = null;
int x = 0, statusBarHeight = 0;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
}
public static List<PackageInfo> getAppList(Context context) {
PackageManager packageManager = context.getPackageManager();
List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
// 判断是否系统应用:
List<PackageInfo> apps = new ArrayList<PackageInfo>();
for (int i = 0; i < packageInfoList.size(); i++) {
PackageInfo pak = (PackageInfo) packageInfoList.get(i);
//判断是否为系统预装的应用
if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
// 第三方应用
apps.add(pak);
} else {
//系统应用
}
}
return apps;
}
//启动一个app
public static void startAPP(Context context, String appPackageName) {
try {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPackageName);
context.startActivity(intent);
} catch (Exception e) {
CommToast.showToast(context, "没有安装");
}
}
/**
* 设置键盘展现和关闭
*
* @param bShow
* @param context
* @param view
*/
public static void showKeyBoard(boolean bShow, Context context, View view) {
if (bShow) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
} else {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* 获取app的根目录
*
* @return 文件缓存根路径
*/
public static String getDiskCacheRootDir(Context context) {
File diskRootFile;
if (existsSdcard()) {
diskRootFile = context.getExternalCacheDir();
} else {
diskRootFile = context.getCacheDir();
}
String cachePath = "";
if (diskRootFile != null) {
cachePath = diskRootFile.getPath();
} else {
throw new IllegalArgumentException("disk is invalid");
}
return cachePath;
}
/**
* 判断外置sdcard是否可以正常使用
*
* @return
*/
public static Boolean existsSdcard() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable();
}
//手机号检查
public static boolean isChinaPhoneLegal(String str) {
// String regExp = "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}$";
String regExp = "^1\\d{10}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}
/**
* 获取版本号名称
*
* @return 当前应用的版本号
*/
public static String getVersionName(Context context) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
String version = info.versionName;
return version;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获取版本号code
*
* @return
*/
public static int getVersionCode(Context context) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
int version = info.versionCode;
return version;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
//通过反射获取类的属性和属性值
public static Map<String, String> getFieldMap(Object object) {
Map<String, String> map = new HashMap<>();
Field fields[] = object.getClass().getDeclaredFields();//cHis 是实体类名称
try {
Field.setAccessible(fields, true);
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
String value = "";
if (fields[i].get(object) != null) {
value = fields[i].get(object).toString();
}
map.put(name, value);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static File uri2File(Context context, Uri uri) {
String img_path;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor actualimagecursor = context.getContentResolver().query(uri, proj, null, null, null);
if (actualimagecursor == null) {
img_path = uri.getPath();
} else {
int actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
img_path = actualimagecursor
.getString(actual_image_column_index);
}
File file = new File(img_path);
return file;
}
//压缩图片
public static File compressImageToFile(File file) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
if (bitmap == null) {
return null;
}
// 0-100 100为不压缩
int options = 60;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 把压缩后的数据存放到baos中
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
try {
long time = System.currentTimeMillis();
File temp_file = new File(Environment.getExternalStorageDirectory(), "temp_pic_"+ time +".jpg");
FileOutputStream fos = new FileOutputStream(temp_file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
return temp_file;
} catch (Exception e) {
e.printStackTrace();
return file;
}
}
private static final int MIN_DELAY_TIME= 300; // 两次点击间隔不能少于1000ms
private static long lastClickTime;
public static boolean isFastClick() {
boolean flag = true;
long currentClickTime = System.currentTimeMillis();
if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
flag = false;
}
lastClickTime = currentClickTime;
return flag;
}
public static void createTag(LinearLayout linearLayout, ProductInfo info, Context mContext) {
linearLayout.removeAllViews();
int count = 1;
//创建段位标签
if (!TextUtils.isEmpty(info.dan)) {
addGuangfangTag(linearLayout, info.dan, mContext);
count++;
}
//创建官方认证标签
if (info.techAuthorityTag != null) {
for (int i = 0; i < info.techAuthorityTag.size(); i++) {
if (count < 4) {
count++;
addGuangfangTag(linearLayout, info.techAuthorityTag.get(i), mContext);
}
}
}
if (info.techTags != null) {
for (int i = 0; i < info.techTags.size(); i++) {
if (count < 4) {
count++;
addUserTag(linearLayout, info.techTags.get(i), mContext);
}
}
}
}
//创建段位标签
private static void addGuangfangTag(LinearLayout linearLayout, String tag, Context mContext) {
TextView textView = new TextView(mContext);
textView.setText(tag);
textView.setTextSize(10);
textView.setBackgroundResource(R.drawable.shape_round2dp_ff9141);
textView.setTextColor(Color.parseColor("#ffffff"));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, Util.dip2px(mContext, 15));
params.setMargins(0, 0, Util.dip2px(mContext, 4), 0);
textView.setPadding(Util.dip2px(mContext, 5), 0, Util.dip2px(mContext, 5), 0);
textView.setGravity(Gravity.CENTER);
textView.setLayoutParams(params);
linearLayout.addView(textView);
}
private static void addUserTag(LinearLayout linearLayout, String tags, Context mContext) {
TextView textView = new TextView(mContext);
textView.setText(tags);
textView.setTextSize(10);
textView.setTextColor(Color.parseColor("#FF9141"));
textView.setBackgroundResource(R.drawable.shape_round2dp_stroke1px_ff9141);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, Util.dip2px(mContext, 15));
params.setMargins(0, 0, Util.dip2px(mContext, 4), 0);
textView.setPadding(Util.dip2px(mContext, 5), 0, Util.dip2px(mContext, 5), 0);
textView.setGravity(Gravity.CENTER);
textView.setLayoutParams(params);
linearLayout.addView(textView);
}
}