Utility.java
19.6 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
package com.drp.mobliemall.utils;
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.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.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.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.drp.mobliemall.app.GlobalContext;
import com.drp.mobliemall.config.Constants;
import com.socks.library.KLog;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Hashtable;
import java.util.List;
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 {
private final static Pattern onlyDitital = Pattern
.compile("^[0-9]+(.[0-9]{0,1})?$");
private static Boolean isExit = false;
private static long exitTime = 0;
private Hashtable<String, Object> memCacheRegion = new Hashtable<String, Object>();
private static Boolean _isTablet = null;
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) {
}
}
/**
* 退出登录 注销
*
* @param cont
*/
/*
* public static void Logout(final Context cont) { final AlertDialog alg =
* new AlertDialog.Builder(cont).create(); alg.show(); Window window =
* alg.getWindow(); window.setContentView(R.layout.dialog); Button btnEntry
* = (Button) window .findViewById(R.id.dialog_button_entry); Button
* btnCancle = (Button) window .findViewById(R.id.dialog_button_cancle);
* btnEntry.setOnClickListener(new OnClickListener() {
*
* @Override public void onClick(View v) { // TODO Auto-generated method
* stub alg.cancel(); // 注销 Intent intent = new Intent(cont,
* LoginActivity.class); cont.startActivity(intent);
*
* } }); btnCancle.setOnClickListener(new OnClickListener() {
*
* @Override public void onClick(View v) { // TODO Auto-generated method
* stub alg.dismiss(); } });
*
* }
*/
/**
* 获取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) {
// TODO Auto-generated catch block
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;
flag = (0xf & GlobalContext.getInstance().getResources()
.getConfiguration().screenLayout) >= 3;
_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() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
/**
* 生成 六位随机数
*
* @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) { }
}
/**
* 从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;
}
/**
* 启动app
*
* @param pageName
*/
public static void launchApp(String pageName) {
Context context = GlobalContext.getInstance();
Intent LaunchIntent = context.getPackageManager().getLaunchIntentForPackage(pageName);
context.startActivity(LaunchIntent);
}
//压缩图片
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;
}
/**
* //获取完整的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();
}
}