.
yy1717
2024-02-18 f4a6a18770eb446c761c159edcfa800cf7fa6008
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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
package com.fwupgrade.saymanss.utils;
 
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.os.StatFs;
import android.provider.Settings;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
 
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
 
/**
 * 工具类,大家在这个工具类中添加方法的时候请注意分类,
 */
@SuppressLint("SimpleDateFormat")
public class UtilTools {
 
/****************************************   android系统设备获取信息相关类     *****************************************/
    
    /**
     * 获取手机型号
     * @author Snow
     * @date  2014-4-10
     * @return
     */
    public static String getPhoneModel() {
        return Build.MODEL;
    }
    
    /**
     * 得到android的id
     * @author Snow
     * @date  2014-4-10
     * @param mContext
     * @return
     */
    public static String getAndroidID(Context mContext) {
        String androidId = Settings.Secure.getString(
                mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
        return androidId;
    }
    
    /**
     * 判断是否为飞行模式
     * @param context
     * @return
     */
    @SuppressWarnings("deprecation")
    public static boolean isAirplaneModeOn(Context context) {
        return Settings.System.getInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0) != 0;
    }
    
    
/****************************************   文件相关类     *****************************************/
    /**
     * 截取文件类型,如"爱笑的眼睛.mp3",调用这个方法,则返回"mp3";
     * 
     * @param name : 文件名称 ,如: "爱笑的眼睛.mp3"
     * 
     * @return  返回文件的类型,如 : mp3
     */
    public static String getFileTypeFromName(String name) {
        String prefix = name.substring(name.lastIndexOf(".") + 1);
        return prefix;
    }
    
    /**
     * 截取文件类型,如"爱笑的眼睛.mp3",调用这个方法,则返回"mp3";
     * 
     * @param name : 文件名称 ,如: "爱笑的眼睛.mp3"
     * 
     * @return  返回文件的类型,如 : .mp3
     */
    public static String getFilePrefixLength(String name) {
        if(name == null || !name.contains(".")){
            return name;
        }
        String prefix = name.substring(0, name.lastIndexOf("."));
        return prefix;
    }
 
    /**
     * 截取文件类型,如"爱笑的眼睛.mp3",调用这个方法,则返回"mp3";
     *
     * @param name : 文件名称 ,如: "爱笑的眼睛.mp3"
     *
     * @return  返回文件的类型,如 : .mp3
     */
    public static String getFileSuffix(String name) {
        if(name == null || !name.contains(".")){
            return "";
        }
        String prefix = name.substring(name.lastIndexOf("."));
        return prefix;
    }
    
    /**
     * 创建文件
     * @param createdir
     * @return
     */
    public static String createFolderPath(String createdir) {
        final File downfolder = new File(createdir);
        if (!downfolder.exists()) {
            downfolder.mkdirs();
        }
        return createdir;
    }
 
    /**
     * 创建文件
     */
    public static boolean createFileInfSdcard(String createFile) {
        final String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) return false;
 
        boolean isCreateSu = false;
        File downfile = new File(createFile);
        if (!downfile.exists()) {
            try {
                isCreateSu = downfile.createNewFile();
            } catch(Exception e) {
                isCreateSu = false;
            }
        } else {
            isCreateSu = false;
        }
        return isCreateSu;
    }
    
    /**
     * 创建本地文件夹
     * 
     * @param createdir
     * 
     * @return  
     */
    public static boolean createFolderInSdcard(String createdir) {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) return false;
        
        boolean isCreateSu = false;
        File downfolder = new File(createdir);
        if (!downfolder.exists()) {
            downfolder.mkdirs();
            isCreateSu = true;
        } else {
            isCreateSu = false;
        }
        return isCreateSu;
    }
    
    /**
     * 从路径中获取文件名称.
     * @param filePath
     * @return 
     */
    public static String getFileName(String filePath) {
 
        int idx = filePath.lastIndexOf("/");
        filePath = filePath.substring(idx + 1, filePath.length());
        return filePath;
 
    }
    
    /**
     * 去掉文件名得到为文件所在的目录
     * @param fileAllpath
     * @return
     */
    public static String getFilePath(String fileAllpath) {
        if (fileAllpath == null) {
            return null;
        }
        int idx = fileAllpath.lastIndexOf("/");
        if (idx == -1) {
            return null;
        }
        String filepath = fileAllpath.substring(0, idx);
        return filepath;
    }
    
    /**
     * 将默认的SDCard路径转换为/mnt/sdcard路径
     * @param path
     * @return
     */
    public static String changeDefSDCardToMnt(String path) {
        String defaultSDCard = Environment.getExternalStorageDirectory().toString();
        
        if(path.startsWith(defaultSDCard)) {
            String sdcard = AppPathInfo.app_sdcard;
            String newPath = path.replace(defaultSDCard, sdcard);
            return newPath;
        } else {
            return path;
        }
    }
    
    /**
     * 文件集合列表排序
     * @param files
     */
    public static void do_sort(List<File> files) {
        if(!files.isEmpty()) {
            Collections.sort(files, new Comparator<File>() {
                @Override
                public int compare(File object1, File object2) {
                    return (object1.getPath().substring(object1.getPath().lastIndexOf("/")).toLowerCase(Locale.getDefault()))
                            .compareTo((String) object2.getPath().substring(object1.getPath().lastIndexOf("/")).toLowerCase(Locale.getDefault()));
                }
 
            });
        }
    }
    
    
    /**
     * 删除路径中的最后一个组成部分,即"/"后的部分
     *  
     * @param path 传入的路径参数
     * @return  返回"/"之前的字符串
     */
    public static String deleteFileNameFromPath(String path) {
        int idx = path.lastIndexOf("/");
        if(idx == -1){
            return null;
        }
        String filePath = "";
        filePath = path.substring(0, idx);
        return filePath;
    }
    
    
/****************************************   字符串转码相关类     *****************************************/
    /**
     * UTF8编码转URL编码.
     * @param urlStr
     * @return
     */
    public static String getUTF8CodeInfoFromURL(String urlStr) {
        try {
            StringBuffer sbuf = new StringBuffer();
            int l = urlStr.length();
            int ch = -1;
            int b, sumb = 0;
            int hb,lb;
            int flag1 = 0;
            for (int i = 0, more = -1; i < l; i++) {
                /* Get next byte b from URL segment s */
                switch (ch = urlStr.charAt(i)) {
                    case '%':
                        if(i >= l-2)
                            return urlStr;
                        ch = urlStr.charAt(++i);
                        if((ch >= 'a' && ch <='f') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) {
                            hb = (Character.isDigit((char) ch) ? ch - '0'
                                    : 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
                        }else{
                            return urlStr;
                        }
                        ch = urlStr.charAt(++i);
                        if((ch >= 'a' && ch <='f') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) {
                            lb = (Character.isDigit((char) ch) ? ch - '0'
                                    : 10 + Character.toLowerCase((char) ch) - 'a') & 0xF;
                        }else{
                            return urlStr;
                        }
                        b = (hb << 4) | lb;
                        flag1 = 1;
                        break;
                    default:
                        b = ch;
                        flag1 = 0;
                }
                if(flag1 == 0) {
                    sbuf.append((char) b);
                    continue;
                }
                /* Decode byte b as UTF-8, sumb collects incomplete chars */
                if ((b & 0xc0) == 0x80) { // 10xxxxxx (continuation byte)
                    sumb = (sumb << 6) | (b & 0x3f); // Add 6 bits to sumb
                    if (--more == 0)
                        sbuf.append((char) sumb); // Add char to sbuf
                } else if ((b & 0x80) == 0x00) { // 0xxxxxxx (yields 7 bits)
                    sbuf.append((char) b); // Store in sbuf
                } else if ((b & 0xe0) == 0xc0) { // 110xxxxx (yields 5 bits)
                    sumb = b & 0x1f;
                    more = 1; // Expect 1 more byte
                } else if ((b & 0xf0) == 0xe0) { // 1110xxxx (yields 4 bits)
                    sumb = b & 0x0f;
                    more = 2; // Expect 2 more bytes
                } else if ((b & 0xf8) == 0xf0) { // 11110xxx (yields 3 bits)
                    sumb = b & 0x07;
                    more = 3; // Expect 3 more bytes
                } else if ((b & 0xfc) == 0xf8) { // 111110xx (yields 2 bits)
                    sumb = b & 0x03;
                    more = 4; // Expect 4 more bytes
                } else /*if ((b & 0xfe) == 0xfc)*/{ // 1111110x (yields 1 bit)
                    sumb = b & 0x01;
                    more = 5; // Expect 5 more bytes
                }
                /* We don't test if the UTF-8 encoding is well-formed */
            }
            return sbuf.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return urlStr;
        }
    }
 
    /**
     * 把String进行UTF-8编码.
     * @param utf8Str
     * @return
     */
    public static String getURLCodeInfoFromUTF8(String utf8Str) {
        try {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < utf8Str.length(); i++) {
                char c = utf8Str.charAt(i);
                char begin;
                if (c >= 0 && c <= 127) {
                    if((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')
                            || (c >= 'A' && c <= 'Z')
                            || (c == '/')
                            || (c == '.')
                            || (c == '_')
                            || (c == '-')) {
                        sb.append(c);
                    }else{
                        sb.append("%" + Integer.toHexString((c)&0xFF).toUpperCase());
                    }
                } else {
                    byte[] b;
                    try {
                        b = String.valueOf(c).getBytes("utf-8");
                    } catch (Exception ex) {
                        System.out.println(ex);
                        b = new byte[0];
                    }
                    for (int j = 0; j < b.length; j++) {
                        int k = b[j];
                        if (k < 0)
                            k += 256;
                        sb.append("%" + Integer.toHexString(k).toUpperCase());
                    }
                }
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return utf8Str;
        }
    }
    
    /**
     * 替换特殊字符,将strFind字符串替换为strInstead
     * @param strText   目标字符串
     * @param strFind   需要转换的字符
     * @param strInstead 转换成需要的字符
     * @return 返回转换之后的字符
     */
    public static String replaceSpecialStingFormString(String strText, String strFind, String strInstead) {
        
        if ((strText == null) || (strFind == null) || (strInstead == null)) 
            return null;
        
        String strTempFront = null;
        String strTempBehind = null;
        int length = strFind.length();
        
        //循环查找,替换
        int index = strText.indexOf(strFind);
        while (index != -1) {
            strTempFront = strText.substring(0, index);
            strTempBehind = strText.substring(index + length);
            strText = strTempFront + strInstead + strTempBehind;
            
            //继续下一次查找
            index = strText.indexOf(strFind);
        }
        
        return strText;
    }
    
    /**
     * 将 "%2F"字符   转换为  "/"  字符。
     * @param urlStr 需要转换的字符串
     * @return 返回已经修改了的字符串
     */
    public static String getURLCodeInfoForSpecialChar(String urlStr) {
        //替换掉%2F为/特殊字符 
        urlStr = replaceSpecialStingFormString(urlStr, "%2F", "/");
        return urlStr;
    }
    
    /**
     * 将utf-8编码的字符转换为string
     * @param utf8Str
     * @return 如果成功转码则返回转码后的内容, 如果转码失败则返回原来的内容.
     */
    public static String getInfoUTF8toStr(String utf8Str) {
        String info;
        try {
            info = URLDecoder.decode(utf8Str, "UTF-8");
        } catch (Exception e) {
            info = utf8Str;
        }
        return info;
    }
    
    /**
     * 去掉字符串中的%20
     */
    public static String strSpaceConversionTo20(String ufilename) {
        String strSC = "";
        strSC = ufilename.replace(" ", "%20");
        return strSC;
    }
    
    /** 16进制数字字符集 */
    private static String hexString="0123456789ABCDEF";
    /**
     * 将字符串编码成16进制数字,适用于所有字符(包括中文)
     */
    public static String encode(String str) {
      //根据默认编码获取字节数组
         byte[] bytes=str.getBytes();
         StringBuilder sb=new StringBuilder(bytes.length*2);
         //将字节数组中每个字节拆解成2位16进制整数
         for(int i=0;i<bytes.length;i++) {
             sb.append(hexString.charAt((bytes[i]&0xf0)>>4));
             sb.append(hexString.charAt((bytes[i]&0x0f)>>0));
          }
        return sb.toString();
     }
    
    /**
     * 将16进制数字解码成字符串,适用于所有字符(包括中文)
     */
    public static String decode(String bytes) {
        ByteArrayOutputStream baos=new ByteArrayOutputStream(bytes.length()/2);
        //将每2位16进制整数组装成一个字节
        for(int i=0;i<bytes.length();i+=2) {
            baos.write((hexString.indexOf(bytes.charAt(i))<<4 | hexString.indexOf(bytes.charAt(i+1))));
        }
        return new String(baos.toByteArray());
   } 
    
/****************************************   时间相关类     *****************************************/
    
    public static final String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    
    /**
     *  设置时间格式
     * @param file
     * @return
     */
    public static String getFileLastModifiedTime(File file) {
        long modifiedTime = file.lastModified();
        Date date = new Date(modifiedTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String dd = sdf.format(date);
        return dd;
    }
    
    /**
     * 设置时间格式
     */
    public static String getTimeFromLong(long modifiedTime) {
        Date date = new Date(modifiedTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String dd = sdf.format(date);
        return dd;
    }
 
    /**
     * 设置时间格式
     */
    public static String getMsecTimeFromLong(long modifiedTime) {
        Date date = new Date(modifiedTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS", Locale.getDefault());
        String dd = sdf.format(date);
        return dd;
    }
 
    /**
     * 截取时间标签
     * @param time
     * @return
     */
    public static String getTimeTag(String time) {
        if(time.contains("T")) {
            int index = time.indexOf("T");
            String timeTag = time.substring(0,index);
            return timeTag;
        }else if(time.contains(" ")) {
            int index = time.indexOf(" ");
            String timeTag = time.substring(0,index);
            return timeTag;
        }else {
            return time;
        }
    }
    
    /**
     * 修改获取的时间的显示方式
     * 获取到的时间显示方式:Fri, 06 Dec 2013 06:05:45 GMT
     * 修改为:2013/12/06 06:05:45
     * @author Wangcan
     */
    public static String modifyTimeShowStyle(String time) {
        String timeShowStyle = "";
        String[] times = time.split(" ");
        
        if(times.length == 2) {
            //显示为 2014-12-06 06:05:45
            timeShowStyle = time.replace("-", "/");
        } else if(times.length == 6){
            String createDay = times[1];
            String createMonth = times[2];
            String createYear = times[3];
            String createTime = times[4];
            
            int i=0;
            for(; i<months.length; i++) {
                if(createMonth.equals(months[i])) {
                    break;
                }
            }
            
            String createMonthNew = "";
            if(i < 10) {
                createMonthNew = "0" + (i + 1);
            } else {
                createMonthNew = Integer.toString(i);
            }
            
            //日期为单个字符,前面加0
            if(createDay.length() == 1) {
                createDay += "0";
            }
             
            timeShowStyle = createYear + "/" 
                                + createMonthNew + "/"
                                + createDay + " "
                                + createTime;
        } else {
            timeShowStyle = time;
        }
        
        return timeShowStyle;
    }
     
    /**
     * 转化格林时间
     * @param formatDate
     * @return
     */ 
    @SuppressWarnings({ "deprecation", "finally" })
    public static String formatGMTDate(String formatDate) {
        String date = formatDate;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            date = sdf.format(new Date(formatDate));
            
        } catch (Exception e) {
        } finally {
            return date;
        }
    }
 
    /**
     * 转化时间
     * @param time
     * @return
     */
    public static long getPaserTime(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    
/****************************************   MD5值转换相关类     *****************************************/
    /**
     * 将key路径的文件转换为MD5值
     * @param key
     * @return
     */
    public static String cachePathMD5ValueForKey(String key) {
        if (key == null || key.length() == 0) {
            throw new IllegalArgumentException( "String to encript cannot be null or zero length");
        }
 
        StringBuffer hexString = new StringBuffer();
 
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(key.getBytes());
            byte[] hash = md.digest();
 
            for (int i = 0; i < hash.length; i++) {
                if ((0xff & hash[i]) < 0x10) {
                    hexString.append("0"
                            + Integer.toHexString((0xFF & hash[i])));
                } else {
                    hexString.append(Integer.toHexString(0xFF & hash[i]));
                }
            }
        } catch (NoSuchAlgorithmException e) {
        }
 
        return hexString.toString();
    }
    
/****************************************  sdcard的空间大小相关类     *****************************************/    
    /**
     *  获得card的可用空间大小
     * @param path
     * @return
     */
    @SuppressWarnings("deprecation")
    static public long getCardMemorySize(String path) {
        StatFs stat = new StatFs(path);
        // StatFs stat = new StatFs(UtilTools.getInfoUTF8toStr(path));
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }
     
    /**
     * 转换文件大小(MB、GB...).
     * @param fileSize
     * @return 
     */
    public static String FormetFileSize(String fileSize) {
        DecimalFormat df = new DecimalFormat("#.0");
        long fileS = 0;
        if (fileSize.equals("")) {
            fileS = 0;
        } else {
            fileS = Long.parseLong(fileSize);
        }
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else{
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        
        if(fileSizeString.startsWith(".")) {
            fileSizeString = "0" + fileSizeString;
        }
        
        return fileSizeString;
    }
    
    /**
     *     获取文件类型
     */
    public static String getFileType(String fileDevPath) {
        int start = fileDevPath.lastIndexOf(".");
        if (start < 0) {
            return null;
        }
        int end = fileDevPath.length();
        return fileDevPath.substring(start, end);
    }
    
    /**
     * 获取存储路径
     * @return 
     */
    public static String getExternalStoragePath() {
        // 获取SdCard状态
        String state = Environment.getExternalStorageState();
        // 判断SdCard是否存在并且是可用的
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            if (Environment.getExternalStorageDirectory().canWrite()) {
                return Environment.getExternalStorageDirectory()
                        .getPath();
            }
        }
        return null;
    }
    
    /**
     * 获取指定路径文件剩余容量.
     * @param filePath
     * @return 
     */
    @SuppressWarnings("deprecation")
    public static long getAvailableStore(String filePath) {
        // 取得sdcard文件路径
        StatFs statFs = new StatFs(filePath);
        // 获取block的SIZE
        long blocSize = statFs.getBlockSize();
        // 获取BLOCK数量
        // long totalBlocks = statFs.getBlockCount();
        // 可使用的Block的数量
        long availaBlock = statFs.getAvailableBlocks();
        // long total = totalBlocks * blocSize;
        long availableSpare = availaBlock * blocSize;
        return availableSpare;
    }
    
    public static String getFileTypeWithNoNod(String fileDevPath) {
        int start = fileDevPath.lastIndexOf(".");
        if (start < 0) {
            return null;
        }
        int end = fileDevPath.length();
        return fileDevPath.substring(start + 1, end);
    }
    
    /**
     * 隐藏软键盘
     * @param context
     * @param windowTockn
     */
    public static void hideSoftKeyboard(Context context, IBinder windowTockn) {
        InputMethodManager inputManger = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManger != null) {
            inputManger.hideSoftInputFromWindow(windowTockn, 0);
        }
    }
    
    /**
     * 定时器循环显示软键盘.
     * @param editText 
     */
    public static void showKeyboard(final EditText editText){
        Timer timer = new Timer();
 
         timer.schedule(new TimerTask(){
 
             public void run() {
 
                 InputMethodManager inputManager =
                     (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                 inputManager.showSoftInput(editText, 0);
             }
 
         },  
 
             1000);
    }
    
    /**
     * URL转UTF-8编码.
     * @param ufilename
     * @return 
     */
    public static String getUTF8Info2(String ufilename) {
 
        int index = -1;
        StringBuilder retName = new StringBuilder();
        String tmpstr;
        while (true) {
            index = ufilename.indexOf(' ');
 
            if (index != -1) {
                tmpstr = ufilename.substring(0, index);
                try {
                    retName.append(URLEncoder.encode(tmpstr, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                }
                retName.append("%20");
                ufilename = ufilename.substring(index + 1);
            } else
                break;
        }
 
        try {
            retName.append(URLEncoder.encode(ufilename, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
        }
        return retName.toString();
 
    }
 
/*******************************************获取本地音乐缩略图的方法*************************************/    
    /**
     * 获取本地音乐缩略图的方法
     * @param filePath
     * @return
     */
    @SuppressLint("NewApi")
    public static Bitmap getLocalMusicBitmap(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(filePath);
        bitmap = Bytes2Bimap(mmr.getEmbeddedPicture());
        return bitmap;
    }
    
    @SuppressLint("NewApi")
    public static Bitmap getLocalVideoBitmap(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(filePath);
        return mmr.getFrameAtTime();
    }
    
    /**
     * 将字节转换为Bitmap图片
     * @param b
     * @return
     */
     public static Bitmap Bytes2Bimap(byte[] b) {
          if(b == null)  return null; 
          
          if (b.length != 0) {
             return BitmapFactory.decodeByteArray(b, 0, b.length);
             
          } else {
             return null;
          }
    }
     
     public static String FormetkbTo(String fileSize) {// 转换文件大小
            DecimalFormat df = new DecimalFormat("#.0");
            long fileS = 0;
            if (fileSize.equals("")) {
                fileS = 0;
            } else {
                fileS = Long.parseLong(fileSize);
            }
            String fileSizeString = "";
            if (fileS == 0) {
                fileSizeString = "0MB";
            } else if (fileS < 1024) {
                fileSizeString = df.format((double) fileS) + "MB";
            } else if (fileS < 1048576) {
                fileSizeString = df.format((double) fileS / 1024) + "GB";
            } else if (fileS < 1073741824) {
                fileSizeString = df.format((double) fileS / 1048576) + "TB";
            } else {
                // fileSizeString = df.format((double) fileS / 1073741824) + "T";
            }
            return fileSizeString;
        }
     
    /**
     * 匹配由数字、26个英文字母或者下划线以及空格  组成的字符串
     * @param str
     * @return
     */
    public static boolean isMatchValidator(String str) {
        return str.matches("^[\\sA-Za-z0-9-]+$");
    }
 
    /**
     *  密码由英文字母(字母区分大小写)和数字组成,且长度5~32位!
     * @param str
     * @return
     */
    public static boolean isMatchValidator3(String str) {
        boolean b = str.matches("^[A-Za-z0-9]+$");
        return b;
    }
    
    /**
     * 以英文字母开头,由字母、数字和‘-’组成,且长度2~8位.
     * @param str
     * @return 
     */
    public static boolean isMatchValidator2(String str) {
        boolean b = str.matches("^[A-Za-z0-9-]+$");
        if (b) {
            String s = str.substring(0, 1);
            b = s.matches("^[A-Za-z]+$");
        }
        return b;
    } 
    
    /**
     * 把加密的密码转换为正确的秘密.
     * @param securityPwd
     * @return 
     */
    public static String changeSecurityPwd(String securityPwd) {
        String changeAfterPwd;
        if (securityPwd != null && !securityPwd.equals("") && (securityPwd.contains("CDATA") || securityPwd.contains("[["))) {
            final int endindex = securityPwd.indexOf("]]");
            changeAfterPwd = securityPwd.substring(8, endindex);
        } else {
            changeAfterPwd = securityPwd;
        }
        return changeAfterPwd;
    }
 
    
    private static boolean copyFile(String oldPath, String newPath) {
       try {
           int bytesum = 0;   
           int byteread = 0;   
           File oldfile = new File(oldPath);
           if (oldfile.exists()) { //文件存在时   
               InputStream inStream = new FileInputStream(oldPath); //读入原文件
               FileOutputStream fs = new FileOutputStream(newPath);
               byte[] buffer = new byte[1444];   
               
               while ( (byteread = inStream.read(buffer)) != -1) {   
                   bytesum += byteread; //字节数 文件大小   
                   fs.write(buffer, 0, byteread);
               }
               inStream.close();
               fs.close();
           }
           
           return true;
       } catch (Exception e) {
           return false;
       }
    }
    //----------->>>
 
 
    /**
     * 转换px单位的数值为dp单位的数值.
     * @param px px单位的数值.
     * @param context 上下文.
     * @return dp单位的数值.
     */
    public static float pixelsToDp(float px, Context context){
        final float scale = context.getResources()
                .getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }
    
    /**
     * 获取手机状态栏高度.
     * @param context
     * @return 
     */
    public static int getStatusBarHeight(Context context){
        Class<?> c = null;
        Object obj = null;
        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 int getNavigationBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }
 
    //获取是否存在NavigationBar
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
 
        }
        return hasNavigationBar;
 
    }
    
     /**
     * 获取名称的前缀
     * 
     * @param name
     * @return
     */
    public static String getPrefixFromName(String name) {
        String prefix = name.substring(0, name.lastIndexOf("."));
        return prefix;
    }
    
    /**
     * 设置光标在Edittext文本的末尾.
     * @param text 
     */
    public static void setCursorLocation(final CharSequence text){
        // 设置光标的位置在字符串的末尾
        if (text instanceof Spannable) {
            Spannable spanText = (Spannable)text;
            Selection.setSelection(spanText, text.length());
        }
    }
    
    /**
     * 将星号显示的密码转为明文显示.
     * @param editText 
     */
    public static void showEditTextPwd(EditText editText) {
        editText.setInputType(InputType.TYPE_CLASS_TEXT
                | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    }
    
    /**
     * 将明文显示的密码转为星号显示.
     * @param editText 
     */
    public static void hideEditTextPwd(EditText editText) {
        editText.setInputType(InputType.TYPE_CLASS_TEXT
                | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    }
    
    /**
     * 获取名称的"/"分隔符后面的字段
     * 
     * @param name
     * @return
     */
    public static String getSpecialFromName(String name) {
        String prefix = name.substring(name.lastIndexOf("/") + 1);
        return prefix;
    }
 
    /**
     * 获取后缀名
     *
     * @param name
     * @return
     */
    public static String getExtensionFromName(String name) {
        String prefix = name.substring(name.lastIndexOf(".") + 1);
        return prefix;
    }
 
 
    /**
     * 设置导航栏颜色
     * @param activity
     * @param colorResId
     */
    public static void setNavigationBarColor(Activity activity, int colorResId) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = activity.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//                window.setStatusBarColor(activity.getResources().getColor(colorResId));
 
                //底部导航栏
                window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @TargetApi(19)
    public static void setTranslucentStatus(Activity activity, boolean on) {
        Window win = activity.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
 
    // <<<------------------------- 自动生成ID ---------------------------------------
    public static final AtomicInteger sNextGeneratedId = new AtomicInteger(3000);
 
    /**
     * 自动生成View的ID.
     * This value will not collide with ID values generated at build time by aapt for R.id.
     *
     * @return a generated ID value
     */
    public static int generateViewId() {
        for (; ; ) {
            final int result = sNextGeneratedId.get();
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }
    // ---------------------------- 自动生成ID --------------------------------------->>>
 
 
    // <<<---------------------------- Camera初始化相关 --------------------------------------->>>
    /**
     * @return the default camera on the device. Return null if there is no camera on the device.
     */
    public static Camera getDefaultCameraInstance() {
        return Camera.open();
    }
 
    /**
     * Iterate over supported camera video sizes to see which one best fits the
     * dimensions of the given view while maintaining the aspect ratio. If none can,
     * be lenient with the aspect ratio.
     *
     * @param supportedVideoSizes Supported camera video sizes.
     * @param previewSizes Supported camera preview sizes.
     * @param w     The width of the view.
     * @param h     The height of the view.
     * @return Best match camera video size to fit in the view.
     */
    public static Camera.Size getOptimalVideoSize(List<Camera.Size> supportedVideoSizes,
                                                  List<Camera.Size> previewSizes, int w, int h) {
        // Use a very small tolerance because we want an exact match.
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
 
        // Supported video sizes list might be null, it means that we are allowed to use the preview
        // sizes
        List<Camera.Size> videoSizes;
        if (supportedVideoSizes != null) {
            videoSizes = supportedVideoSizes;
        } else {
            videoSizes = previewSizes;
        }
        Camera.Size optimalSize = null;
 
        // Start with max value and refine as we iterate over available video sizes. This is the
        // minimum difference between view and camera height.
        double minDiff = Double.MAX_VALUE;
 
        // Target view height
        int targetHeight = h;
 
        // Try to find a video size that matches aspect ratio and the target view size.
        // Iterate over all available sizes and pick the largest size that can fit in the view and
        // still maintain the aspect ratio.
        for (Camera.Size size : videoSizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;
            if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
 
        // Cannot find video size that matches the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : videoSizes) {
                if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }
    // ---------------------------- Camera初始化相关 --------------------------------------->>>
 
    /**
     * 设置状态栏图标为深色和魅族特定的文字风格,Flyme4.0以上
     * 可以用来判断是否为Flyme用户
     * @param window 需要设置的窗口
     * @param dark 是否把状态栏字体及图标颜色设置为深色
     * @return  boolean 成功执行返回true
     *
     */
    public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {
 
            }
        }
        return result;
    }
 
    /**
     * 设置状态栏字体图标为深色,需要MIUIV6以上
     * @param window 需要设置的窗口
     * @param dark 是否把状态栏字体及图标颜色设置为深色
     * @return  boolean 成功执行返回true
     *
     */
    public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if(dark){
                    extraFlagField.invoke(window,darkModeFlag,darkModeFlag);//状态栏透明且黑色字体
                }else{
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result=true;
            }catch (Exception e){
 
            }
        }
        return result;
    }
 
    private static Toast mToast;
 
    /**
     * 单例显示Toast消息.
     * @param context 上下文.
     * @param content 显示的内容.
     */
    public static void showToast(Context context, String content) {
        try {
            if (mToast == null) {
                mToast = Toast.makeText(context.getApplicationContext(), content, Toast.LENGTH_SHORT);
            } else {
                mToast.setText(content);
            }
            mToast.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 判断App是否已经启动.
     * @param context
     * @return
     */
    public static boolean isAppOnForeground(Context context, Class homeName) {
        // Returns a list of application processes that are running on the
        // device
        boolean isRunning = false;
        Intent intent = new Intent(context, homeName);
        ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
                    isRunning = true;
                    break;
                } else {
                    isRunning = false;
                }
            }
        }
        return isRunning;
    }
 
 
    /**
     * 获得文件大小
     * @param size
     * @return
     */
    public static String getFileSize(long size) {
        //如果字节数少于1024,则直接以B为单位,否则先除于1024,后3位因太少无意义
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }
        //如果原字节数除于1024之后,少于1024,则可以直接以KB作为单位
        //因为还没有到达要使用另一个单位的时候
        //接下去以此类推
        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            //因为如果以MB为单位的话,要保留最后1位小数,
            //因此,把此数乘以100之后再取余
            size = size * 100;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "MB";
        } else {
            //否则如果要以GB为单位的,先除于1024再作同样的处理
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "GB";
        }
    }
 
    /**
     * aes加密
     * @param key
     * @param data
     * @param ivbyte
     * @return
     */
    public static String encrypt(String key, String data, String ivbyte){
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
 
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
 
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
 
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(ivbyte.getBytes());
 
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
 
            String s = bytes2hex02(encrypted);
            return s;
 
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 转化为16进制
     *
     * @param bytes
     * @return
     */
    public static String bytes2hex02(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (byte b : bytes) {
            // 将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制
            tmp = Integer.toHexString(0xFF & b);
            if (tmp.length() == 1){// 每个字节8为,转为16进制标志,2个16进制位
                tmp = "0" + tmp;
            }
            sb.append(tmp);
        }
        return sb.toString();
    }
 
    /**
     *   判断是魅族操作系统
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/6/18,9:43
     * <h3>UpdateTime</h3> 2016/6/18,9:43
     * <h3>CreateAuthor</h3> vera
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @return true 为魅族系统 否则不是
     */
    public static boolean isMeizuFlymeOS() {
/* 获取魅族系统操作版本标识*/
        String meizuFlymeOSFlag  = getSystemProperty("ro.build.display.id","");
        if (TextUtils.isEmpty(meizuFlymeOSFlag)){
            return false;
        }else if (meizuFlymeOSFlag.contains("flyme") || meizuFlymeOSFlag.toLowerCase().contains("flyme")){
            return  true;
        }else {
            return false;
        }
    }
 
    /**
     *   获取系统属性
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/6/18,9:35
     * <h3>UpdateTime</h3> 2016/6/18,9:35
     * <h3>CreateAuthor</h3> vera
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param key  ro.build.display.id
     * @param defaultValue 默认值
     * @return 系统操作版本标识
     */
    private static String getSystemProperty(String key, String defaultValue) {
        try {
            Class<?> clz = Class.forName("android.os.SystemProperties");
            Method get = clz.getMethod("get", String.class, String.class);
            return (String)get.invoke(clz, key, defaultValue);
        } catch (ClassNotFoundException e) {
            return null;
        } catch (NoSuchMethodException e) {
            return null;
        } catch (IllegalAccessException e) {
            return null;
        } catch (IllegalArgumentException e) {
            return null;
        } catch (InvocationTargetException e) {
            return null;
        }
    }
 
    /**
     * 检测支付宝是否安装.
     * @return
     */
    public static boolean isZFBInstall(Context context) {
        boolean isInstall = false;
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.eg.android.AlipayGphone")) {
                    isInstall = true;
                }
            }
        }
        return isInstall;
    }
 
    /**
     * 除法保留小数点
     * @param v1
     * @param v2
     * @param scale
     * @return
     */
    public static double getRoundDecimal(long v1, long v2, int scale) {
        try {
            BigDecimal b1 = new BigDecimal(Double.toString(v1));
            BigDecimal b2 = new BigDecimal(Double.toString(v2));
            double result = b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /**
     * px2dp
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dp(Context context,float pxValue){
        final float scale=context.getResources().getDisplayMetrics().density;
        return (int)(pxValue/scale+0.5f);
    }
 
    /**
     * dp2px
     * @param context
     * @param dpValue
     * @return
     */
    public static int dp2px(Context context,float dpValue){
        final float scale=context.getResources().getDisplayMetrics().density;
        return (int)(dpValue*scale+0.5f);
    }
 
    /**
     * 判断Homepage 是否已经启动过
     * @return
     */
    public static boolean getAppIsRunning(Context context, Class mClass) {
        boolean isRunning = false;
        Intent intent = new Intent(context, mClass);
        ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
                    isRunning = true;
                    break;
                } else {
                    isRunning = false;
                }
            }
        }
        return isRunning;
    }
 
    /**
     * 显示成功或失败
     * @param isOk
     */
    public static void showResultToast(Context context, boolean isOk) {
//        int resId = isOk ? R.mipmap.ic_toast_ok : R.mipmap.ic_toast_error;
//        WdToast i4SeasonToast = WdToast.makeText(context, resId, Toast.LENGTH_SHORT);
//        i4SeasonToast.setGravity(Gravity.CENTER, 0, 0);
//        i4SeasonToast.show();
    }
 
}