lmw
2023-06-16 03972ad1d3ce6ffe0be0395c0a4d5dcb4474031f
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
package com.luck.picture.lib;
 
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
 
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
 
import com.luck.picture.lib.broadcast.BroadcastAction;
import com.luck.picture.lib.broadcast.BroadcastManager;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.dialog.PictureCustomDialog;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.ImageCompleteCallback;
import com.luck.picture.lib.permissions.PermissionChecker;
import com.luck.picture.lib.photoview.PhotoView;
import com.luck.picture.lib.tools.AttrsUtils;
import com.luck.picture.lib.tools.DateUtils;
import com.luck.picture.lib.tools.JumpUtils;
import com.luck.picture.lib.tools.MediaUtils;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.tools.SdkVersionUtils;
import com.luck.picture.lib.tools.ToastUtils;
import com.luck.picture.lib.tools.ValueOf;
import com.luck.picture.lib.widget.PreviewViewPager;
import com.luck.picture.lib.widget.longimage.ImageSource;
import com.luck.picture.lib.widget.longimage.ImageViewState;
import com.luck.picture.lib.widget.longimage.SubsamplingScaleImageView;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
 
/**
 * @author:luck
 * @data:2017/01/18 下午1:00
 * @描述: 预览图片
 */
public class PictureExternalPreviewActivity extends PictureBaseActivity implements View.OnClickListener {
    private static final int SAVE_IMAGE_ERROR = -1;
    private static final int SAVE_IMAGE_SUCCESSFUL = 0;
 
    private ImageButton ibLeftBack;
    private TextView tvTitle;
    private PreviewViewPager viewPager;
    private List<LocalMedia> images = new ArrayList<>();
    private int position = 0;
    private SimpleFragmentAdapter adapter;
    private loadDataThread loadDataThread;
    private String downloadPath;
    private String mimeType;
    private ImageButton ibDelete;
    private boolean isAndroidQ;
    private View titleViewBg;
 
    @Override
    public int getResourceId() {
        return R.layout.picture_activity_external_preview;
    }
 
    @Override
    protected void initWidgets() {
        super.initWidgets();
        isAndroidQ = SdkVersionUtils.checkedAndroid_Q();
        titleViewBg = findViewById(R.id.titleViewBg);
        tvTitle = findViewById(R.id.picture_title);
        ibLeftBack = findViewById(R.id.left_back);
        ibDelete = findViewById(R.id.ib_delete);
        viewPager = findViewById(R.id.preview_pager);
        position = getIntent().getIntExtra(PictureConfig.EXTRA_POSITION, 0);
        images = (List<LocalMedia>) getIntent().getSerializableExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST);
        ibLeftBack.setOnClickListener(this);
        ibDelete.setOnClickListener(this);
        ibDelete.setVisibility(config.style != null ? config.style.pictureExternalPreviewGonePreviewDelete
                ? View.VISIBLE : View.GONE : View.GONE);
        initViewPageAdapterData();
    }
 
    /**
     * 设置样式
     */
    @Override
    public void initPictureSelectorStyle() {
        if (config.style != null) {
            if (config.style.pictureTitleTextColor != 0) {
                tvTitle.setTextColor(config.style.pictureTitleTextColor);
            }
            if (config.style.pictureTitleTextSize != 0) {
                tvTitle.setTextSize(config.style.pictureTitleTextSize);
            }
            if (config.style.pictureLeftBackIcon != 0) {
                ibLeftBack.setImageResource(config.style.pictureLeftBackIcon);
            }
            if (config.style.pictureExternalPreviewDeleteStyle != 0) {
                ibDelete.setImageResource(config.style.pictureExternalPreviewDeleteStyle);
            }
            if (config.style.pictureLeftBackIcon != 0) {
                ibLeftBack.setImageResource(config.style.pictureLeftBackIcon);
            }
            if (config.style.pictureTitleBarBackgroundColor != 0) {
                titleViewBg.setBackgroundColor(colorPrimary);
            }
        } else {
            int previewBgColor = AttrsUtils.getTypeValueColor(getContext(), R.attr.picture_ac_preview_title_bg);
            if (previewBgColor != 0) {
                titleViewBg.setBackgroundColor(previewBgColor);
            } else {
                titleViewBg.setBackgroundColor(colorPrimary);
            }
        }
    }
 
    private void initViewPageAdapterData() {
        tvTitle.setText(getString(R.string.picture_preview_image_num,
                position + 1, images.size()));
        adapter = new SimpleFragmentAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(position);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
 
            }
 
            @Override
            public void onPageSelected(int index) {
                tvTitle.setText(getString(R.string.picture_preview_image_num,
                        index + 1, images.size()));
                position = index;
            }
 
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }
 
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.left_back) {
            finish();
            exitAnimation();
        } else if (id == R.id.ib_delete) {
            if (images != null && images.size() > 0) {
                int currentItem = viewPager.getCurrentItem();
                images.remove(currentItem);
                // 删除通知用户更新
                Bundle bundle = new Bundle();
                bundle.putInt(PictureConfig.EXTRA_PREVIEW_DELETE_POSITION, currentItem);
                BroadcastManager.getInstance(getContext())
                        .action(BroadcastAction.ACTION_DELETE_PREVIEW_POSITION)
                        .extras(bundle).broadcast();
                if (images.size() == 0) {
                    onBackPressed();
                    return;
                }
                tvTitle.setText(getString(R.string.picture_preview_image_num,
                        position + 1, images.size()));
                position = currentItem;
                adapter.notifyDataSetChanged();
            }
        }
    }
 
    public class SimpleFragmentAdapter extends PagerAdapter {
 
        /**
         * 最大缓存图片数量
         */
        private static final int MAX_CACHE_SIZE = 20;
        /**
         * 缓存view
         */
        private SparseArray<View> mCacheView;
 
        public void clear() {
            if (null != mCacheView) {
                mCacheView.clear();
                mCacheView = null;
            }
        }
 
        public SimpleFragmentAdapter() {
            super();
            this.mCacheView = new SparseArray<>();
        }
 
        @Override
        public int getCount() {
            return images != null ? images.size() : 0;
        }
 
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            (container).removeView((View) object);
            if (mCacheView.size() > MAX_CACHE_SIZE) {
                mCacheView.remove(position);
            }
        }
 
        @Override
        public int getItemPosition(@NonNull Object object) {
            return POSITION_NONE;
        }
 
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
 
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View contentView = mCacheView.get(position);
            if (contentView == null) {
                contentView = LayoutInflater.from(container.getContext())
                        .inflate(R.layout.picture_image_preview, container, false);
                // 常规图控件
                final PhotoView imageView = contentView.findViewById(R.id.preview_image);
                // 长图控件
                final SubsamplingScaleImageView longImageView = contentView.findViewById(R.id.longImg);
                // 视频播放按钮
                ImageView ivPlay = contentView.findViewById(R.id.iv_play);
                LocalMedia media = images.get(position);
                if (media != null) {
                    final String path;
                    if (media.isCut() && !media.isCompressed()) {
                        // 裁剪过
                        path = media.getCutPath();
                    } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                        // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                        path = media.getCompressPath();
                    } else {
                        path = media.getPath();
                    }
                    boolean isHttp = PictureMimeType.isHttp(path);
                    mimeType = isHttp ? PictureMimeType.getImageMimeType(media.getPath()) : media.getMimeType();
                    boolean eqVideo = PictureMimeType.eqVideo(mimeType);
                    ivPlay.setVisibility(eqVideo ? View.VISIBLE : View.GONE);
                    boolean isGif = PictureMimeType.isGif(mimeType);
                    final boolean eqLongImg = MediaUtils.isLongImg(media);
                    imageView.setVisibility(eqLongImg && !isGif ? View.GONE : View.VISIBLE);
                    longImageView.setVisibility(eqLongImg && !isGif ? View.VISIBLE : View.GONE);
                    // 压缩过的gif就不是gif了
                    if (isGif && !media.isCompressed()) {
                        if (config != null && config.imageEngine != null) {
                            config.imageEngine.loadAsGifImage
                                    (getContext(), path, imageView);
                        }
                    } else {
                        if (config != null && config.imageEngine != null) {
                            if (isHttp) {
                                // 网络图片
                                config.imageEngine.loadImage(contentView.getContext(), path,
                                        imageView, longImageView, new ImageCompleteCallback() {
                                            @Override
                                            public void onShowLoading() {
                                                showPleaseDialog();
                                            }
 
                                            @Override
                                            public void onHideLoading() {
                                                dismissDialog();
                                            }
                                        });
                            } else {
                                if (eqLongImg) {
                                    displayLongPic(isAndroidQ
                                            ? Uri.parse(path) : Uri.fromFile(new File(path)), longImageView);
                                } else {
                                    config.imageEngine.loadImage(contentView.getContext(), path, imageView);
                                }
                            }
                        }
                    }
                    imageView.setOnViewTapListener((view, x, y) -> {
                        finish();
                        exitAnimation();
                    });
                    longImageView.setOnClickListener(v -> {
                        finish();
                        exitAnimation();
                    });
                    if (!eqVideo) {
                        longImageView.setOnLongClickListener(v -> {
                            if (config.isNotPreviewDownload) {
                                if (PermissionChecker.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    downloadPath = path;
                                    showDownLoadDialog();
                                } else {
                                    PermissionChecker.requestPermissions(PictureExternalPreviewActivity.this,
                                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PictureConfig.APPLY_STORAGE_PERMISSIONS_CODE);
                                }
                            }
                            return true;
                        });
                    }
                    if (!eqVideo) {
                        imageView.setOnLongClickListener(v -> {
                            if (config.isNotPreviewDownload) {
                                if (PermissionChecker.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    downloadPath = path;
                                    showDownLoadDialog();
                                } else {
                                    PermissionChecker.requestPermissions(PictureExternalPreviewActivity.this,
                                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PictureConfig.APPLY_STORAGE_PERMISSIONS_CODE);
                                }
                            }
                            return true;
                        });
                    }
                    ivPlay.setOnClickListener(v -> {
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putString(PictureConfig.EXTRA_VIDEO_PATH, path);
                        intent.putExtras(bundle);
                        JumpUtils.startPictureVideoPlayActivity(container.getContext(), bundle, PictureConfig.PREVIEW_VIDEO_CODE);
                    });
                }
                mCacheView.put(position, contentView);
            }
            (container).addView(contentView, 0);
            return contentView;
        }
    }
 
    /**
     * 加载长图
     *
     * @param uri
     * @param longImg
     */
    private void displayLongPic(Uri uri, SubsamplingScaleImageView longImg) {
        longImg.setQuickScaleEnabled(true);
        longImg.setZoomEnabled(true);
        longImg.setPanEnabled(true);
        longImg.setDoubleTapZoomDuration(100);
        longImg.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CENTER_CROP);
        longImg.setDoubleTapZoomDpi(SubsamplingScaleImageView.ZOOM_FOCUS_CENTER);
        longImg.setImage(ImageSource.uri(uri), new ImageViewState(0, new PointF(0, 0), 0));
    }
 
    /**
     * 下载图片提示
     */
    private void showDownLoadDialog() {
        if (!isFinishing() && !TextUtils.isEmpty(downloadPath)) {
            final PictureCustomDialog dialog =
                    new PictureCustomDialog(getContext(), R.layout.picture_wind_base_dialog);
            Button btn_cancel = dialog.findViewById(R.id.btn_cancel);
            Button btn_commit = dialog.findViewById(R.id.btn_commit);
            TextView tv_title = dialog.findViewById(R.id.tv_title);
            TextView tv_content = dialog.findViewById(R.id.tv_content);
            tv_title.setText(getString(R.string.picture_prompt));
            tv_content.setText(getString(R.string.picture_prompt_content));
            btn_cancel.setOnClickListener(v -> {
                if (!isFinishing()) {
                    dialog.dismiss();
                }
            });
            btn_commit.setOnClickListener(view -> {
                boolean isHttp = PictureMimeType.isHttp(downloadPath);
                if (isHttp) {
                    showPleaseDialog();
                    loadDataThread = new loadDataThread(downloadPath);
                    loadDataThread.start();
                } else {
                    // 有可能本地图片
                    try {
                        if (isAndroidQ) {
                            savePictureAlbumAndroidQ(Uri.parse(downloadPath));
                        } else {
                            // 把文件插入到系统图库
                            savePictureAlbum();
                        }
                        dismissDialog();
                    } catch (Exception e) {
                        ToastUtils.s(getContext(), getString(R.string.picture_save_error) + "\n" + e.getMessage());
                        dismissDialog();
                        e.printStackTrace();
                    }
                }
                if (!isFinishing()) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }
 
    /**
     * 保存相片至本地相册
     *
     * @throws Exception
     */
    private void savePictureAlbum() throws Exception {
        String suffix = PictureMimeType.getLastImgSuffix(mimeType);
        String state = Environment.getExternalStorageState();
        File rootDir = state.equals(Environment.MEDIA_MOUNTED)
                ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                : getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (rootDir != null && !rootDir.exists() && rootDir.mkdirs()) {
        }
        File folderDir = new File(isAndroidQ || !state.equals(Environment.MEDIA_MOUNTED)
                ? rootDir.getAbsolutePath() : rootDir.getAbsolutePath() + File.separator + "Camera" + File.separator);
        if (folderDir != null && !folderDir.exists() && folderDir.mkdirs()) {
        }
        String fileName = DateUtils.getCreateFileName("IMG_") + suffix;
        File file = new File(folderDir, fileName);
        PictureFileUtils.copyFile(downloadPath, file.getAbsolutePath());
        Message message = mHandler.obtainMessage();
        message.what = SAVE_IMAGE_SUCCESSFUL;
        message.obj = file.getAbsolutePath();
        mHandler.sendMessage(message);
    }
 
    /**
     * 保存图片到picture 目录,Android Q适配,最简单的做法就是保存到公共目录,不用SAF存储
     *
     * @param inputUri
     */
    private void savePictureAlbumAndroidQ(Uri inputUri) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, DateUtils.getCreateFileName("IMG_"));
        contentValues.put(MediaStore.Images.Media.DATE_TAKEN, ValueOf.toString(System.currentTimeMillis()));
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, PictureMimeType.MIME_TYPE_IMAGE);
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, PictureMimeType.DCIM);
        Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        if (uri == null) {
            mHandler.sendEmptyMessage(SAVE_IMAGE_ERROR);
            return;
        }
        AsyncTask.SERIAL_EXECUTOR.execute(() -> {
            OutputStream outputStream = null;
            try {
                outputStream = getContentResolver().openOutputStream(uri);
                ParcelFileDescriptor inputDescriptor = getContentResolver().openFileDescriptor(inputUri, "r");
                Bitmap bitmap = BitmapFactory.decodeFileDescriptor(inputDescriptor.getFileDescriptor());
                if (bitmap != null) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.close();
                    String path = PictureFileUtils.getPath(getContext(), uri);
                    Message message = mHandler.obtainMessage();
                    message.what = SAVE_IMAGE_SUCCESSFUL;
                    message.obj = path;
                    mHandler.sendMessage(message);
                } else {
                    mHandler.sendEmptyMessage(SAVE_IMAGE_ERROR);
                }
 
            } catch (Exception e) {
                mHandler.sendEmptyMessage(SAVE_IMAGE_ERROR);
                e.printStackTrace();
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
 
 
    // 进度条线程
    public class loadDataThread extends Thread {
        private String path;
 
        public loadDataThread(String path) {
            super();
            this.path = path;
        }
 
        @Override
        public void run() {
            try {
                showLoadingImage(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 针对Q版本创建uri
     *
     * @return
     */
    private Uri createOutImageUri() {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, DateUtils.getCreateFileName("IMG_"));
        contentValues.put(MediaStore.Images.Media.DATE_TAKEN, ValueOf.toString(System.currentTimeMillis()));
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, PictureMimeType.MIME_TYPE_IMAGE);
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, PictureMimeType.DCIM);
        return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
    }
 
    // 下载图片保存至手机
    public void showLoadingImage(String urlPath) {
        try {
            URL u = new URL(urlPath);
            String suffix = PictureMimeType.getLastImgSuffix(mimeType);
            String state = Environment.getExternalStorageState();
            BufferedOutputStream bout;
            String path;
            if (isAndroidQ) {
                Uri outImageUri = createOutImageUri();
                if (outImageUri == null) {
                    mHandler.sendEmptyMessage(SAVE_IMAGE_ERROR);
                    return;
                }
                bout = new BufferedOutputStream(getContentResolver().openOutputStream(outImageUri));
                path = PictureFileUtils.getPath(this, outImageUri);
            } else {
                File rootDir =
                        state.equals(Environment.MEDIA_MOUNTED)
                                ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                                : getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                if (rootDir != null && !rootDir.exists() && rootDir.mkdirs()) {
                }
                File folderDir = new File(!state.equals(Environment.MEDIA_MOUNTED)
                        ? rootDir.getAbsolutePath() : rootDir.getAbsolutePath() + File.separator + "Camera" + File.separator);
                if (folderDir != null && !folderDir.exists() && folderDir.mkdirs()) {
                }
                String fileName = DateUtils.getCreateFileName("IMG_") + suffix;
                File file = new File(folderDir, fileName);
                path = file.getAbsolutePath();
                bout = new BufferedOutputStream(new FileOutputStream(path));
            }
            if (bout == null) {
                mHandler.sendEmptyMessage(SAVE_IMAGE_ERROR);
                return;
            }
            byte[] buffer = new byte[1024 * 8];
            int read;
            int ava = 0;
            long start = System.currentTimeMillis();
            BufferedInputStream bin = new BufferedInputStream(u.openStream());
            while ((read = bin.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
                ava += read;
                long speed = ava / (System.currentTimeMillis() - start);
            }
            bout.flush();
            bout.close();
            Message message = mHandler.obtainMessage();
            message.what = SAVE_IMAGE_SUCCESSFUL;
            message.obj = path;
            mHandler.sendMessage(message);
        } catch (IOException e) {
            mHandler.sendEmptyMessage(SAVE_IMAGE_ERROR);
            e.printStackTrace();
        }
    }
 
 
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SAVE_IMAGE_SUCCESSFUL:
                    try {
                        String path = (String) msg.obj;
                        if (!TextUtils.isEmpty(path)) {
                            if (!SdkVersionUtils.checkedAndroid_Q()) {
                                File file = new File(path);
                                MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), null);
                                new PictureMediaScannerConnection(getContext(), file.getAbsolutePath(), () -> {
                                });
                            }
                            ToastUtils.s(getContext(), getString(R.string.picture_save_success) + "\n" + path);
                        }
                        dismissDialog();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case SAVE_IMAGE_ERROR:
                    ToastUtils.s(getContext(), getString(R.string.picture_save_error));
                    dismissDialog();
                    break;
                default:
                    break;
            }
        }
    };
 
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        exitAnimation();
    }
 
    private void exitAnimation() {
        overridePendingTransition(R.anim.picture_anim_fade_in, config.windowAnimationStyle != null
                && config.windowAnimationStyle.activityPreviewExitAnimation != 0
                ? config.windowAnimationStyle.activityPreviewExitAnimation : R.anim.picture_anim_exit);
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loadDataThread != null) {
            mHandler.removeCallbacks(loadDataThread);
            loadDataThread = null;
        }
        if (adapter != null) {
            adapter.clear();
        }
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PictureConfig.APPLY_STORAGE_PERMISSIONS_CODE:
                // 存储权限
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        showDownLoadDialog();
                    } else {
                        ToastUtils.s(getContext(), getString(R.string.picture_jurisdiction));
                    }
                }
                break;
        }
    }
}