Utility.java
33.9 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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
package com.drp.util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import com.drp.R;
import com.drp.mobliemall.app.GlobalContext;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 工具类
*/
@SuppressLint("NewApi")
public class Utility {
public static final File APP_CACHE_DIR = new File(GlobalContext.getInstance().getFilesDir().getAbsolutePath() + "/webcache");
private final static Pattern onlyDitital = Pattern
.compile("^[0-9]+(.[0-9]{0,1})?$");
private static Boolean isExit = false;
private static long exitTime = 0;
private static Boolean _isTablet = null;
private Hashtable<String, Object> memCacheRegion = new Hashtable<String, Object>();
private Utility() {
// Forbidden being instantiated.
}
public static void debug(String tag, String s) {
// if (Constants.ENABLE_DEBUG) {
// KLog.d(tag, s);
// }
}
public static String encodeUrl(Map<String, String> param) {
if (param == null) {
return "";
}
StringBuilder sb = new StringBuilder();
Set<String> keys = param.keySet();
boolean first = true;
for (String key : keys) {
String value = param.get(key);
if (!TextUtils.isEmpty(value)) {
if (first)
first = false;
else
sb.append("&");
// try {
// sb.append(URLEncoder.encode(key, "UTF-8")).append("=")
// .append(URLEncoder.encode(param.get(key), "UTF-8"));
sb.append(key).append("=").append(param.get(key));
// } catch (UnsupportedEncodingException e) {
// }
}
}
return sb.toString();
}
public static Bundle decodeUrl(String s) {
Bundle params = new Bundle();
if (s != null) {
String array[] = s.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
try {
if (v.length == 2)
params.putString(URLDecoder.decode(v[0], "UTF-8"),
URLDecoder.decode(v[1], "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return params;
}
public static void closeSilently(Closeable closeable) {
if (closeable != null)
try {
closeable.close();
} catch (IOException ignored) {
}
}
/**
* 将图片变为圆角
*
* @param bitmap 原Bitmap图片
* @param pixels 图片圆角的弧度(单位:像素(px))
* @return 带有圆角的图片(Bitmap 类型)
*/
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* Parse a URL query and fragment parameters into a key-value bundle.
*/
public static Bundle parseUrl(String url) {
// hack to prevent MalformedURLException
url = url.replace("weiboconnect", "http");
try {
URL u = new URL(url);
Bundle b = decodeUrl(u.getQuery());
b.putAll(decodeUrl(u.getRef()));
return b;
} catch (MalformedURLException e) {
return new Bundle();
}
}
public static void stopListViewScrollingAndScrollToTop(ListView listView) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.BASE) {
listView.setSelection(0);
listView.dispatchTouchEvent(MotionEvent.obtain(
SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
MotionEvent.ACTION_CANCEL, 0, 0, 0));
} else {
listView.dispatchTouchEvent(MotionEvent.obtain(
SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
MotionEvent.ACTION_DOWN, 0, 0, 0));
listView.dispatchTouchEvent(MotionEvent.obtain(
SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
MotionEvent.ACTION_UP, 0, 0, 0));
listView.setSelection(0);
}
}
public static int dip2px(int dipValue) {
float reSize = GlobalContext.getInstance().getResources()
.getDisplayMetrics().density;
return (int) ((dipValue * reSize) + 0.5);
}
public static float dpToPixel(float dp) {
return dp
* (GlobalContext.getInstance().getResources()
.getDisplayMetrics().densityDpi / 160F);
}
public static int px2dip(int pxValue) {
float reSize = GlobalContext.getInstance().getResources()
.getDisplayMetrics().density;
return (int) ((pxValue / reSize) + 0.5);
}
public static float sp2px(int spValue) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue,
GlobalContext.getInstance().getResources().getDisplayMetrics());
}
public static int length(String paramString) {
int i = 0;
for (int j = 0; j < paramString.length(); j++) {
if (paramString.substring(j, j + 1).matches("[Α-¥]"))
i += 2;
else
i++;
}
if (i % 2 > 0) {
i = 1 + i / 2;
} else {
i = i / 2;
}
return i;
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
public static boolean isWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
}
return false;
}
public static int getNetType(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return networkInfo.getType();
}
return -1;
}
public static boolean isGprs(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() != ConnectivityManager.TYPE_WIFI) {
return true;
}
}
return false;
}
public static boolean isSystemRinger(Context context) {
AudioManager manager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
return manager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
}
public static String getPicPathFromUri(Uri uri, Activity activity) {
String value = uri.getPath();
if (value.startsWith("/external")) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = activity.managedQuery(uri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else {
return value;
}
}
public static boolean isAllNotNull(Object... obs) {
for (int i = 0; i < obs.length; i++) {
if (obs[i] == null) {
return false;
}
}
return true;
}
public static boolean isIntentSafe(Activity activity, Uri uri) {
Intent mapCall = new Intent(Intent.ACTION_VIEW, uri);
PackageManager packageManager = activity.getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(
mapCall, 0);
return activities.size() > 0;
}
public static boolean isIntentSafe(Activity activity, Intent intent) {
PackageManager packageManager = activity.getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(
intent, 0);
return activities.size() > 0;
}
public static boolean isGooglePlaySafe(Activity activity) {
Uri uri = Uri
.parse("http://play.google.com/store/apps/details?id=com.google.android.gms");
Intent mapCall = new Intent(Intent.ACTION_VIEW, uri);
mapCall.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
mapCall.setPackage("com.android.vending");
PackageManager packageManager = activity.getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(
mapCall, 0);
return activities.size() > 0;
}
public static String buildTabText(int number) {
if (number == 0) {
return null;
}
String num;
if (number < 99) {
num = "(" + number + ")";
} else {
num = "(99+)";
}
return num;
}
/**
* 弹出Toast消息
*
* @param msg
*/
public static void ToastMessage(Context cont, String msg) {
Toast.makeText(cont, msg, Toast.LENGTH_SHORT).show();
}
public static void ToastMessage(Context cont, int msg) {
Toast.makeText(cont, msg, Toast.LENGTH_SHORT).show();
}
public static void ToastMessage(Context cont, String msg, int time) {
Toast.makeText(cont, msg, time).show();
}
/**
* 初始化动画
*
* @param context
* @param img
*/
public static void initAnim(Context context, ImageView img, int animId) {
Animation anim = AnimationUtils.loadAnimation(context, animId);
img.startAnimation(anim);
}
/**
* 判断只能输入数字
*
* @param text
* @return
*/
public static boolean isOnlyDigital(String text) {
if (text == null || text.trim().length() == 0)
return false;
return onlyDitital.matcher(text).matches();
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (; ; ) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
/**
* 获取assets 目录下 属性文件
*
* @return
*/
public static Properties getContextProperties() {
Properties pro = new Properties();
InputStream in = Utility.class
.getResourceAsStream("/assets/context.properties");
try {
pro.load(in);
} catch (IOException e) {
e.printStackTrace();
}
return pro;
}
// 校验Tag Alias 只能是数字,英文字母和中文
public static boolean isValidTagAndAlias(String s) {
Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
Matcher m = p.matcher(s);
return m.matches();
}
// 取得版本号
public static String getVersionName(Context context) {
try {
PackageInfo manager = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return manager.versionName;
} catch (NameNotFoundException e) {
return "Unknown";
}
}
/**
* 获得设别IMEI号码
*
* @param context
* @return
*/
public static String getDeviceIMEI(Context context) {
TelephonyManager tm = ((TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE));
return tm.getDeviceId();
}
/**
* 获得UUID
*
* @return
*/
public static String getUUID() {
UUID ud = UUID.randomUUID();
return ud.toString();
}
public static boolean isTablet() {
if (_isTablet == null) {
boolean flag;
if ((0xf & GlobalContext.getInstance().getResources()
.getConfiguration().screenLayout) >= 3)
flag = true;
else
flag = false;
_isTablet = Boolean.valueOf(flag);
}
return _isTablet.booleanValue();
}
public static DisplayMetrics getDisplayMetrics() {
DisplayMetrics displaymetrics = new DisplayMetrics();
((WindowManager) GlobalContext.getInstance().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(
displaymetrics);
return displaymetrics;
}
public static float getScreenHeight() {
return getDisplayMetrics().heightPixels;
}
public static float getScreenWidth() {
return getDisplayMetrics().widthPixels;
}
/**
* 检测Sdcard是否存在
*
* @return
*/
public static boolean isExitsSdcard() {
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
return true;
else
return false;
}
/**
* 生成 六位随机数
*
* @return
*/
public static long createSixBitRandom() {
return (long) ((Math.random() * 9 + 1) * 100000);
}
/**
* 退出应用程序
*/
@SuppressWarnings("deprecation")
public static void AppExit(Context context) {
try {
ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
activityMgr.restartPackage(context.getPackageName());
System.exit(0);
} catch (Exception e) {
}
}
public static String intToIp(int i) {
return (i & 0xFF) + "." +
((i >> 8) & 0xFF) + "." +
((i >> 16) & 0xFF) + "." +
(i >> 24 & 0xFF);
}
/**
* 获得 IP 地址
*
* @param context
* @return
*/
public static String getLocalIPAddress(Context context) {
if (isWifi(context)) {
//获取wifi服务
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
return intToIp(ipAddress);
} else {
try {
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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
}
return null;
}
}
/**
* 计算listview的高度,使用方法:Utility.setListViewHeightBasedOnChildren(listView);
*
* @param listView
*/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/**
* 验证手机格式
*/
public static boolean isMobileNO(String mobiles) {
/*
移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
联通:130、131、132、152、155、156、185、186
电信:133、153、180、189、(1349卫通)
总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9
*/
String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
if (TextUtils.isEmpty(mobiles)) return false;
else return mobiles.matches(telRegex);
}
/**
* 清除WebView缓存
*/
public static void clearWebViewCache() {
//清理Webview缓存数据库
try {
// deleteDatabase("webview.db");
// deleteDatabase("webviewCache.db");
} catch (Exception e) {
e.printStackTrace();
}
//WebView 缓存文件
File APP_CACHE_DIR = new File(GlobalContext.getInstance().getFilesDir().getAbsolutePath() + "/webcache");
File webviewCacheDir = new File(GlobalContext.getInstance().getCacheDir().getAbsolutePath() + "/webviewCache");
//删除webview 缓存目录
if (webviewCacheDir.exists()) {
deleteFile(webviewCacheDir);
}
//删除webview 缓存 缓存目录
if (APP_CACHE_DIR.exists()) {
deleteFile(APP_CACHE_DIR);
}
}
/**
* 递归删除 文件/文件夹
*
* @param file
*/
public static void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFile(files[i]);
}
}
file.delete();
} else {
}
}
//在进程中去寻找当前APP的信息,判断是否在前台运行
public static boolean isAppOnForeground() {
ActivityManager activityManager = (ActivityManager) GlobalContext.getInstance().getSystemService(
Context.ACTIVITY_SERVICE);
String packageName = GlobalContext.getInstance().getPackageName();
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;
}
//压缩图片
public static Bitmap lessenUriImage(String path) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(path, options); //此时返回 bm 为空
options.inJustDecodeBounds = false; //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = (int) (options.outHeight / (float) 320);
if (be <= 0)
be = 1;
options.inSampleSize = be; //重新读入图片,注意此时已经把 options.inJustDecodeBounds 设回 false 了
bitmap = BitmapFactory.decodeFile(path, options);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
System.out.println(w + " " + h); //after zoom
return bitmap;
}
/**
* 从html中获取url路径
*
* @param html
* @return
*/
public static String getUrlFromHtml(String html) {
String urlStr = "";
String regex = "(http:|https:)//[^\\u4e00-\\u9fa5]+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(html);
while (matcher.find()) {
urlStr = matcher.group();
}
return urlStr;
}
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
/**
* 关键字高亮显示
*
* @param target 需要高亮的关键字
* @param text 需要显示的文字
* @return spannable 处理完后的结果,记得不要toString(),否则没有效果
*/
public static SpannableStringBuilder highlight(String text, String target) {
SpannableStringBuilder spannable = new SpannableStringBuilder(text);
CharacterStyle span = null;
Pattern p = Pattern.compile(target);
Matcher m = p.matcher(text);
while (m.find()) {
span = new ForegroundColorSpan(GlobalContext.getInstance().getResources().getColor(R.color.app_blue));// 需要重复!
spannable.setSpan(span, m.start(), m.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannable;
}
/**
* //获取完整的URL
*
* @param text
*/
public static String getCompleteUrl(String text) {
Pattern p = Pattern.compile("((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?", Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(text);
matcher.find();
return matcher.group();
}
/**
* //判断是否包含URL
*
* @param text
*/
public static Boolean isCompleteUrl(String text) {
Pattern p = Pattern.compile("((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?", Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(text);
return matcher.find();
}
public static String subString(String text) {
String str = "";
if (!TextUtils.isEmpty(text)) {
if (text.length() > 5) {
str = text.substring(0, 5);
str = new StringBuffer(str).append("…").toString();
} else {
str = text;
}
} else {
str = text;
}
return str;
}
public static int getNavigationBarHeight(Context context) {
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");
int height = resources.getDimensionPixelSize(resourceId);
Log.v("dbw", "Navi height:" + height);
return height;
}
/**
* 调用可能打开文件的软件打开文件
* @param file
*/
public static void openFile(Context context,File file){
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
//获取文件file的MIME类型
String type = getMIMEType(file);
//设置intent的data和Type属性。
intent.setDataAndType(/*uri*/Uri.fromFile(file), type);
//跳转
try {
context.startActivity(intent); // 可能无应用可打开, 避免程序崩溃
} catch (Exception e) {
Toast.makeText(context, context.getString(R.string.no_application_can_open), Toast.LENGTH_SHORT).show();
return;
}
}
/**
* 根据文件后缀名获得对应的MIME类型。
* @param file
*/
private static String getMIMEType(File file) {
String type="*/*";
String fName = file.getName();
//获取后缀名前的分隔符"."在fName中的位置。
int dotIndex = fName.lastIndexOf(".");
if(dotIndex < 0){
return type;
}
/* 获取文件的后缀名*/
String end=fName.substring(dotIndex,fName.length()).toLowerCase(Locale.CHINA);
if(end=="")return type;
//在MIME和文件类型的匹配表中找到对应的MIME类型。
for(int i = 0; i< FileFormatParams.MIME_MapTable.length; i++){
if(end.equals(FileFormatParams.MIME_MapTable[i][0]))
type = FileFormatParams.MIME_MapTable[i][1];
}
return type;
}
/**
* 获取文件名称
*
* @return
*/
private String getPhotoFileName() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat(
"'IMG'_yyyyMMdd_HHmmss");
return dateFormat.format(date) + ".jpg";
}
/**
* 文件后缀对应文件类型。
*
*/
public static class FileFormatParams {
public static final String MIME_MapTable[][]={
//{后缀名,MIME类型}
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".xls", "application/vnd.ms-excel"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prop", "text/plain"},
{".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"},
{".rtf", "application/rtf"},
{".sh", "text/plain"},
{".tar", "application/x-tar"},
{".tgz", "application/x-compressed"},
{".txt", "text/plain"},
{".wav", "audio/x-wav"},
{".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"},
{".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/x-zip-compressed"},
{"", "*/*"}
};
}
public static Point getNavigationBarSize(Context context) {
Point appUsableSize = getAppUsableScreenSize(context);
Point realScreenSize = getRealScreenSize(context);
// navigation bar on the right
if (appUsableSize.x < realScreenSize.x) {
return new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y);
}
// navigation bar at the bottom
if (appUsableSize.y < realScreenSize.y) {
return new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y);
}
// navigation bar is not present
return new Point();
}
public static Point getAppUsableScreenSize(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}
public static Point getRealScreenSize(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
if (Build.VERSION.SDK_INT >= 17) {
display.getRealSize(size);
} else if (Build.VERSION.SDK_INT >= 14) {
try {
size.x = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
size.y = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
} catch (IllegalAccessException e) {} catch (InvocationTargetException e) {} catch (NoSuchMethodException e) {}
}
return size;
}
}