lmw
2023-04-13 c75cedf381f9f7909b9a06a2d932d1fe48773912
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
package com.zhaoyang.driver.utils;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Process;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
 
 
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
 
import cn.sinata.xldutils.utils.StringUtils;
import cn.sinata.xldutils.utils.UtilKtKt;
 
import static android.content.Context.TELEPHONY_SERVICE;
import static com.zhaoyang.driver.utils.PackageUtil.isHW;
import static com.zhaoyang.driver.utils.PackageUtil.isMi;
import static com.umeng.socialize.utils.ContextUtil.getPackageName;
 
 
/**
 * Created by Administrator on 2017/7/10.
 */
 
public class MyUtils {
    private static final String TAG = "MyUtils";
 
    private static volatile MyUtils myUtils;
 
    public MyUtils() {
 
    }
 
    public static boolean canBackgroundStart(Context context) {
        AppOpsManager ops = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        try {
            int op = 10021; // >= 23
            // ops.checkOpNoThrow(op, uid, packageName)
            Method method = ops.getClass().getMethod("checkOpNoThrow", new Class[]
                    {int.class, int.class, String.class}
            );
            Integer result = (Integer) method.invoke(ops, op, Process.myUid(), context.getPackageName());
            return result == AppOpsManager.MODE_ALLOWED;
        } catch (Exception e) {
            Log.e(TAG, "not support", e);
        }
        return false;
    }
 
    public static void toSettingPro(Context context) {
        if (isMi()) {
            toMi(context);
        }else if (isHW()){
            toHW(context);
        }else {
            toSetting(context);
        }
    }
 
    private static void toMi(Context context) {
        Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");
        ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
        i.setComponent(componentName);
        i.putExtra("extra_pkgname", getPackageName());
        try {
            context.startActivity(i);
        } catch (Exception e) {
            e.printStackTrace();
            toSetting(context);
        }
    }
 
    private static void toHW(Context context) {
        try {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");//华为权限管理
            intent.setComponent(comp);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            toSetting(context);
        }
    }
 
    private static void toSetting(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        context.startActivity(localIntent);
    }
 
    public static MyUtils getInstans() {
        // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率)
        if (myUtils == null) {
            //同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)
            synchronized (MyUtils.class) {
                //未初始化,则初始instance变量
                if (myUtils == null) {
                    myUtils = new MyUtils();
                }
            }
        }
        return myUtils;
    }
 
 
    //根句string转时间戳
    public long getLongTime(String timestamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        Date date = new Date();
        try {
            date = simpleDateFormat.parse(timestamp);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date.getTime();
    }
 
 
    //根据时间戳显示时间
    public String showTimeYMD(long timestamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        return simpleDateFormat.format(new Date(timestamp));
    }
 
    //根据时间戳显示时间
    public String showTimeYMDHM(long timestamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        return simpleDateFormat.format(new Date(timestamp));
    }
 
    //根据时间戳显示时间
    public String showTimeMMdd(long timestamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日 HH:mm", Locale.CHINA);
        return simpleDateFormat.format(new Date(timestamp));
    }
 
    //根据时间戳显示时间
    public String showTimeHHmm(long timestamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm", Locale.CHINA);
        return simpleDateFormat.format(new Date(timestamp));
    }
 
    //根据时间戳显示时间
    public String showTimeHHmmss(long timestamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        return simpleDateFormat.format(new Date(timestamp));
    }
 
    /**
     * 显示,今天、明后、后天、或者时间 yyyy年MM月dd日 HH:mm
     *
     * @param timestamp
     * @return
     */
    public String showTimeDays(long timestamp) {
        Date date;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            date = sdf.parse(sdf.format(new Date()));
            if (timestamp > date.getTime() && timestamp < (date.getTime() + 24 * 60 * 60 * 1000)) {//今天
                return String.format("今天 %s", showTimeMMdd(timestamp));
            } else if (timestamp > (date.getTime() + 24 * 60 * 60 * 1000) && timestamp < (date.getTime() + 48 * 60 * 60 * 1000)) {//明天
                return String.format("明天 %s", showTimeMMdd(timestamp));
            } else if (timestamp > (date.getTime() + 48 * 60 * 60 * 1000) && timestamp < (date.getTime() + 72 * 60 * 60 * 1000)) {
                return String.format("后天 %s", showTimeMMdd(timestamp));
            } else {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.CHINA);
                return simpleDateFormat.format(new Date(timestamp));
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }
 
    //设置double精确到小数点后两位
    public String doubleTwo(double price) {
        String shows = String.format("%.2f", price);
//        if (shows.indexOf(".")>0){
//            shows = shows.replaceAll("0+?$", "");//去掉多余的0
//            shows = shows.replaceAll("[.]$", "");//如最后一位是.则去掉
//        }
        return shows;
    }
 
    //设置double精确到小数点后两位(删除末尾的0)
    public String doubleDelete(double price) {
        String shows = String.format("%.2f", price);
        if (shows.indexOf(".") > 0) {
            shows = shows.replaceAll("0+?$", "");//去掉多余的0
            shows = shows.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return shows;
    }
 
    //设置double精确到小数点后1位
    public String doubleOne(double price) {
        String shows = String.format("%.1f", price);
        return shows;
    }
 
    /**
     * 将“0-9”转换为“00-09”
     */
    public String formatTime(int unit) {
        return unit < 10 ? "0" + String.valueOf(unit) : String.valueOf(unit);
    }
 
    /**
     * 显示 00:00 分:秒
     *
     * @param ss
     * @return
     */
    public String showTimeMMss(int ss) {
        String showMs = "";
        int mTime = ss / 60;
        int sTime = ss % 60;
        showMs = formatTime(mTime) + ":" + formatTime(sTime);
        return showMs;
    }
 
 
    /**
     * 跳转到应用详情界面
     */
    public void gotoAppDetailIntent(Activity activity, int resquestCode) {
        Intent intent = new Intent();
        intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + activity.getPackageName()));
        activity.startActivityForResult(intent, resquestCode);
    }
 
    /**
     * 转跳外部链接
     *
     * @param context
     * @param urlHtml
     */
    public void toWebView(Context context, String urlHtml) {
        if (StringUtils.isEmpty(urlHtml)) {
            return;
        } else if (urlHtml.startsWith("http://") || urlHtml.startsWith("https://")) {
            Intent intent = new Intent();
            intent.setData(Uri.parse(urlHtml));//Url 就是你要打开的网址
            intent.setAction(Intent.ACTION_VIEW);
            context.startActivity(intent); //启动浏览器
        }
    }
 
    /**
     * 复制到剪切板
     *
     * @param copyStr
     * @return
     */
    public void copyStr(Context context, String copyStr) {
        //获取剪贴板管理器
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", copyStr);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }
 
 
    /**
     * 调起拨号页面
     *
     * @param context
     * @param phone
     */
    public void CallPhone(Activity context, String phone) {
        if (phone == null || phone.trim().isEmpty()) {
            ToastUtils.showShortToast(context, "手机号为空");
            return;
        }
        try {
            UtilKtKt.callPhone(context, phone);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 过去uuid
     */
 
    //获得全球唯一性的id
    public String getUUid() {
        String id = UUID.randomUUID().toString();
        //生成的id942cd30b-16c8-449e-8dc5-028f38495bb5中间含有横杠,
        // <span style="color: rgb(75, 75, 75); font-family: Verdana, Arial, Helvetica,
        // sans-serif; line-height: 20.7999992370605px;">用来生成数据库的主键id是很实用的。</span>
//        id = id.replace("-", "");//替换掉中间的那个斜杠
        return id;
    }
 
    //获取手机唯一id (IMEI)
    public String getUuid(Context context) {
        TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        @SuppressLint({"MissingPermission", "HardwareIds"}) String szImei = TelephonyMgr.getDeviceId();
        return szImei;
    }
 
 
    /**
     * 获取指定文件大小(单位:字节)
     *
     * @param file
     * @return
     * @throws Exception
     */
    public long getFileSize(File file) throws Exception {
        if (file == null) {
            return 0;
        }
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        }
        return size;
    }
 
    /**
     * 判断压缩级别
     *
     * @param filePath
     * @return
     */
    public int getSampleSize(String filePath) {
        File file = new File(filePath);
        long size;
        try {
            size = getFileSize(file);
            int fileSize = (int) size / 1048576;
            LogUtils.e("文件大小", size + "");
            LogUtils.e("msg", "文件压缩级别" + fileSize);
            if (fileSize < 1) {
                return 0;
            } else if (fileSize <= 5) {
                return 2;
            } else if (fileSize <= 20) {
                return 4;
            } else if (fileSize <= 80) {
                return 6;
            } else if (fileSize <= 160) {
                return 8;
            } else {
                return 10;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 2;
    }
 
 
    public BitmapFactory.Options getBitmapOption(int inSampleSize) {
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }
 
 
    public void compressBitmapToFile(Bitmap bmp, File file) {
        // 尺寸压缩倍数,值越大,图片尺寸越小
        int ratio = 1;
        // 压缩Bitmap到对应尺寸
        Bitmap result = Bitmap.createBitmap(bmp.getWidth() / ratio, bmp.getHeight() / ratio, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect rect = new Rect(0, 0, bmp.getWidth() / ratio, bmp.getHeight() / ratio);
        canvas.drawBitmap(bmp, null, rect, null);
 
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        result.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    /**
     * 将json对象转换成map集合
     *
     * @param gsonStr
     * @return
     */
    public Map<String, Object> gsonToMap(String gsonStr) {
        Log.e("tag", gsonStr);
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, Object>>() {
        }.getType();
        Map<String, Object> map = gson.fromJson(gsonStr, type);
        return map;
    }
 
    /**
     * 隐藏展示身份证
     *
     * @param idNumber 身份证号码
     * @return
     */
    public String hideIdNumber(String idNumber) {
        if (StringUtils.isEmpty(idNumber)) {
            return idNumber;
        }
        if (idNumber.length() == 15 || idNumber.length() == 18) {
            StringBuffer substring = new StringBuffer();
            substring.append(idNumber.substring(0, idNumber.length() - 12));
            substring.append("********");
            substring.append(idNumber.substring(idNumber.length() - 4));
            return substring.toString();
        }
        return idNumber;
    }
 
 
    /**
     * 隐藏展示身份证
     *
     * @param idNumber 身份证号码
     * @return
     */
    public String hideIdNumber3(String idNumber) {
        if (StringUtils.isEmpty(idNumber)) {
            return idNumber;
        }
        if (idNumber.length() == 18) {
            StringBuffer substring = new StringBuffer();
            substring.append(idNumber.substring(0, idNumber.length() - 15));
            substring.append("************");
            substring.append(idNumber.substring(idNumber.length() - 3));
            return substring.toString();
        }
        return idNumber;
    }
 
    //判断是否包含字母和数字(长度6-16)
    public static boolean isLetterDigit(String str) {
        if (str.length() < 6 || str.length() > 16) {
            return false;
        }
        boolean isDigit = false;//定义一个boolean值,用来表示是否包含数字
        boolean isLetter = false;//定义一个boolean值,用来表示是否包含字母
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            }
            if (Character.isLetter(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }
        }
        String regex = "^[a-zA-Z0-9]+$";
        boolean isRight = isDigit && isLetter && str.matches(regex);
        return isRight;
    }
 
    //隐藏软键盘
    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
 
    /**
     * 显示或隐藏软键盘
     *
     * @param context 上下文对象
     */
    public void showOrHahe(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
 
    }
 
    public int dp2px(Context context, int dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());
    }
 
    public void getMemoryInfo(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        manager.getMemoryInfo(info);
        LogUtils.e("Memory", "系统总内存:" + (info.totalMem / (1024 * 1024)) + "M");
        LogUtils.e("Memory", "系统剩余内存:" + (info.availMem / (1024 * 1024)) + "M");
        LogUtils.e("Memory", "系统是否处于低内存运行:" + info.lowMemory);
        LogUtils.e("Memory", "系统剩余内存低于" + (info.threshold / (1024 * 1024)) + "M时为低内存运行");
    }
 
 
    /**
     * 是否使屏幕常亮
     *
     * @param activity
     * @Param isOpenLight
     */
    public void keepScreenLongLight(Activity activity, boolean isOpenLight) {
        Window window = activity.getWindow();
        if (isOpenLight) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
 
    }
 
    public String readAssetsFile(Context context, String fileName) {
        try {
            InputStream is = context.getAssets().open(fileName);
            int fileLength = is.available();
            byte[] buffer = new byte[fileLength];
            int readLength = is.read(buffer);
            is.close();
            return new String(buffer, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "读取错误,请检查文件是否存在";
    }
 
 
}