admin
2022-08-09 399ac289f80b7a40aa4210341db6b447cacdcf14
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
package com.tejia.lijin.app.util;
 
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
 
import com.wpc.lcjianlibrary.BuildConfig;
import com.wpc.library.util.MobileUtil;
import com.tejia.lijin.app.ui.dialog.UnbindDialog;
import com.wpc.library.util.common.DeviceUtil;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
 
 
/**
 * Created by Administrator on 2017/11/15.
 */
public class Tools {
 
    public static String IMAGE_NAME = "iv_share_";
    public static int i = 0;
 
    //保存网络图片保存到本地
    public static final File saveImageToSdCard(Context context, String image) {
        boolean success = false;
        File file = null;
        try {
            file = createStableImageFile(context);
            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            String length = conn.getHeaderField("Content-Length");
//            Log.e("mResult", length);
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            int size = bitmap.getByteCount();
//            Log.e("mResult", size + "");
            FileOutputStream outStream;
 
            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        if (success) {
            return file;
        } else {
            return null;
        }
    }
 
    //保存网络图片保存到本地
    public static final File saveImageFromPathToSdCard(Context context, String image,
                                                       String path, String imageFileName) {
        boolean success = false;
        File file = null;
        try {
            file = createImageFilePath(path, imageFileName);
            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            FileOutputStream outStream;
 
            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        if (success) {
            MediaScannerConnection.scanFile(context, new String[]{file.getPath()}, null, null);
            return file;
        } else {
            return null;
        }
    }
 
    //保存bitmap图片
    public static File saveBitmap(Context mContext, Bitmap bitmap) {
        String imageFileName = System.currentTimeMillis() + ".jpg";
        String path = Environment.getExternalStorageDirectory()
                + "/rebateshare";
        File storageDir = new File(path);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
 
//        Toast.makeText(this, "宽:" + bitmap.getWidth() + "---高:" + bitmap.getHeight(), Toast.LENGTH_LONG).show();
//        Log.e("mResult", "bitmap宽:" + bitmap.getWidth() + "---bitmap高:" + bitmap.getHeight());
        // 保存图片到SD卡上
        File imgfile = new File(path, imageFileName);
        FileOutputStream stream;
        try {
            stream = new FileOutputStream(imgfile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
            // 把文件插入到系统图库(注释是因为 会在相册和保存文件夹内各有一张图片)
//            try {
//                MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
//                        imgfile.getAbsolutePath(), imageFileName, null);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
            //通知系统消息更新
            MediaScannerConnection.scanFile(mContext, new String[]{imgfile.toString()}, null, null);
 
            // Android设备Gallery应用只会在启动的时候扫描系统文件夹
            // 这里模拟一个媒体装载的广播,用于使保存的图片可以在Gallery中查看
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//                Intent mediaScanIntent = new Intent(
//                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//                Uri contentUri = Uri.fromFile(Environment
//                        .getExternalStorageDirectory()); // out is your output
//                // file
//                mediaScanIntent.setData(contentUri);
//                mContext.sendBroadcast(mediaScanIntent);
//            } else {
//                Intent intent = new Intent();
//                intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
//                intent.setData(Uri.fromFile(Environment
//                        .getExternalStorageDirectory()));
//                mContext.sendBroadcast(intent);
//            }
        } catch (FileNotFoundException e) {
            Log.i("mResult", "文件没有找到");
            e.printStackTrace();
        }
        return imgfile;
    }
 
 
    //保存bitmap图片
    public static File saveBitmap(Bitmap bitmap, String path, String name) {
        String imageFileName = name;
        File storageDir = new File(path);
        if (!storageDir.exists()) {
            storageDir.mkdirs();
        }
 
//        Toast.makeText(this, "宽:" + bitmap.getWidth() + "---高:" + bitmap.getHeight(), Toast.LENGTH_LONG).show();
//        Log.e("mResult", "bitmap宽:" + bitmap.getWidth() + "---bitmap高:" + bitmap.getHeight());
        // 保存图片到SD卡上
        File imgfile = new File(path, imageFileName);
        FileOutputStream stream;
        try {
            stream = new FileOutputStream(imgfile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        } catch (FileNotFoundException e) {
            Log.i("mResult", "文件没有找到");
            e.printStackTrace();
        }
        return imgfile;
    }
 
 
    //保存bitmap图片
    public static File saveBitmapToPath(Context mContext, Bitmap bitmap, String path, String imageFileName, String ToastName) {
        File storageDir = new File(path);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        // 保存图片到SD卡上
        File imgfile = new File(path, imageFileName);
        FileOutputStream stream;
        try {
            stream = new FileOutputStream(imgfile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
            // 其次把文件插入到系统图库(注释是因为 会在相册和保存文件夹内各有一张图片)
//            try {
//                MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
//                        imgfile.getAbsolutePath(), imageFileName, null);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
            //通知系统消息更新
            MediaScannerConnection.scanFile(mContext, new String[]{imgfile.toString()}, null, null);
//            "分享图保存成功,请到相册中查看"
            Toast.makeText(mContext, ToastName, Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            Log.i("mResult", "文件没有找到");
            Toast.makeText(mContext, "图片保存失败", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        return imgfile;
    }
 
    public static void saveImageToGallery(Context context, Bitmap bmp, String path, String imageFileName) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, imageFileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), imageFileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
    }
 
    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {
        i++;
        String imageFileName = IMAGE_NAME + i + ".png";
        String path = context.getExternalCacheDir().getPath() + "/share";
        File storageDir = new File(path);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File image = new File(storageDir, imageFileName);
        return image;
    }
 
    //创建本地保存路径
    public static File createImageFilePath(String path, String imageFileName) throws IOException {
        File storageDir = new File(path);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File image = new File(storageDir, imageFileName);
        return image;
    }
 
    // 判断文件是否存在
    public static void singleFileExists(File file) {
 
        if (file.exists()) {
            System.out.println("file exists");
        } else {
            System.out.println("file not exists, create it ...");
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
 
    }
 
    // 判断文件夹是否存在
    public static void fileDirExists(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                System.out.println("dir exists");
            } else {
                System.out.println("the same name file exists, can not create dir");
            }
        } else {
            System.out.println("dir not exists, create it ...");
            file.mkdir();
        }
 
    }
 
 
    //判断是否安装了淘宝
    public static int isTaobaoAvilible(final Context context) {
        int returnNum;
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = DeviceUtil.getInstalledPackagesCache(context);
        if (pinfo != null) {
            boolean isReadSuc = false;
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(context.getPackageName())) {
                    isReadSuc = true;
                }
            }
            if (isReadSuc) {
                boolean isHave = false;
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equals("com.taobao.taobao")) {
                        isHave = true;
                    }
                }
                if (isHave) {
                    returnNum = 0;
                } else {
                    returnNum = 2;
                }
            } else {
                returnNum = 1;
            }
        } else {
            returnNum = 1;
        }
        if (returnNum == 1) {
            openAppListPermission(context, "淘宝");
        }
        return returnNum;
    }
 
    /**
     * @param context
     * @return 0-安装了微信  1-没有读取应用权限  2-没有安装微信
     */
    //判断是否安装了微信
    public static int isWeixinAvilible(final Context context) {
        int returnNum = 2;
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = DeviceUtil.getInstalledPackagesCache(context);
        if (pinfo != null) {
            boolean isReadSuc = false;
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(context.getPackageName())) {
                    isReadSuc = true;
                }
            }
            if (isReadSuc) {
                boolean isHave = false;
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equals("com.tencent.mm")) {
                        isHave = true;
                    }
                }
                if (isHave) {
                    returnNum = 0;
                } else {
                    returnNum = 2;
                }
            } else {
                returnNum = 1;
            }
        } else {
            returnNum = 1;
        }
        if (returnNum == 1) {
            openAppListPermission(context, "微信");
        }
        return returnNum;
    }
 
    //判断是否安装了sina
    public static int isSinaAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = DeviceUtil.getInstalledPackagesCache(context);
        int returnNum = 2;
        if (pinfo != null) {
            boolean isReadSuc = false;
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(context.getPackageName())) {
                    isReadSuc = true;
                }
            }
            if (isReadSuc) {
                boolean isHave = false;
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equals("com.sina.weibo")) {
                        isHave = true;
                    }
                }
                if (isHave) {
                    returnNum = 0;
                } else {
                    returnNum = 2;
                }
            } else {
                returnNum = 1;
            }
        } else {
            returnNum = 1;
        }
        if (returnNum == 1) {
            openAppListPermission(context, "新浪");
        }
        return returnNum;
    }
 
    //判断是否安装了QQ
    public static int isQQAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = DeviceUtil.getInstalledPackagesCache(context);
        int returnNum;
        if (pinfo != null) {
            boolean isReadSuc = false;
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(context.getPackageName())) {
                    isReadSuc = true;
                }
            }
            if (isReadSuc) {
                boolean isHave = false;
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equals("com.tencent.mobileqq")) {
                        isHave = true;
                    }
                }
                if (isHave) {
                    returnNum = 0;
                } else {
                    returnNum = 2;
                }
            } else {
                returnNum = 1;
            }
        } else {
            returnNum = 1;
        }
        if (returnNum == 1) {
            openAppListPermission(context, "QQ");
        }
        return returnNum;
    }
 
    private static void openAppListPermission(final Context context, String platform) {
        UnbindDialog.Builder builder = new UnbindDialog.Builder(context);
        builder.setMessage("需要检测是否安装" + platform + ",请打开  读取应用列表权限")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                if (MobileUtil.getSystem().equals("MIUI")) {
                    gotoMiuiPermission(context);
                } else if (MobileUtil.getSystem().equals("EMUI")) {
                    gotoHuaweiPermission(context);
                } else if (MobileUtil.getSystem().equals("flyme")) {
                    gotoMiuiPermission(context);
                } else {
                    context.startActivity(getAppDetailSettingIntent(context));
                }
            }
        }).create().show();
    }
 
    /**
     * 跳转到miui的权限管理页面
     */
    public static void gotoMiuiPermission(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", context.getPackageName());
        try {
            context.startActivity(i);
        } catch (Exception e) {
            e.printStackTrace();
            context.startActivity(getAppDetailSettingIntent(context));
        }
    }
 
    /**
     * 跳转到魅族的权限管理系统
     */
    private static void gotoMeizuPermission(Context context) {
        Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra("packageName", context.getPackageName());
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            context.startActivity(getAppDetailSettingIntent(context));
        }
    }
 
    /**
     * 华为的权限管理页面
     */
    private static void gotoHuaweiPermission(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();
            context.startActivity(getAppDetailSettingIntent(context));
        }
    }
 
    /**
     * 获取应用详情页面intent
     *
     * @return
     */
    private static Intent getAppDetailSettingIntent(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", context.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", context.getPackageName());
        }
        return localIntent;
    }
 
    /**
     * @param context
     * @param imageFile
     * @return content Uri
     */
    public static Uri getImageContentUri(Context context, File imageFile) {
//        if (1 > 0) {
//            try {
//                ApplicationInfo applicationInfo = context.getApplicationInfo();
//                int targetSDK = applicationInfo.targetSdkVersion;
//                Uri uri;
//                if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                            imageFile.getAbsolutePath(), imageFile.getName(), null));
//                } else {
//                    uri = Uri.fromFile(new File(imageFile.getPath()));
//                }
//
//                return uri;
//            } catch (Exception e) {
//                return null;
//            }
//
//        }
 
 
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }
}