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
package com.tejia.lijin.app.ui.trends;
 
import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
 
import com.wpc.library.util.common.DimenUtils;
import com.wpc.library.util.security.MD5Utils;
import com.tejia.lijin.app.R;
import com.tejia.lijin.app.callBack.GeneralCallback;
import com.tejia.lijin.app.callBack.PermissionInterface;
import com.tejia.lijin.app.ui.BaseActivity;
import com.tejia.lijin.app.util.PermissionHelper;
import com.tejia.lijin.app.util.ToolUtil;
import com.ysh.wpc.appupdate.download.DownLoadFile;
 
import java.io.File;
 
import static com.tejia.lijin.app.ui.dialog.AddZFBInfoDialog2.Builder.TEXT_ALIGIN_MIDDLE;
 
/**
 * Created by weikou2015 on 2018/8/22.
 */
 
public class VideoPlayActivity extends BaseActivity implements PermissionInterface, View.OnClickListener {
 
    private VideoView vv_video;
    //控制区域
    private FrameLayout fl_controller, fl_top;
    private LinearLayout fl_bottom;
    private TextView tv_save;
    private ImageView iv_back, iv_status;
    private TextView tv_play_time, tv_total_time;
    private SeekBar sb_progress;
 
    private int errorCount = 0;
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setShowRecommend(false);
        setContentView(R.layout.activity_play_video);
        initView();
        initData();
    }
 
    private void initView() {
        vv_video = findViewById(R.id.vv_video);
        fl_controller = findViewById(R.id.fl_controller);
        tv_save = findViewById(R.id.tv_save);
        iv_back = findViewById(R.id.iv_back);
        iv_status = findViewById(R.id.iv_status);
        tv_play_time = findViewById(R.id.tv_play_time);
        tv_total_time = findViewById(R.id.tv_total_time);
        sb_progress = findViewById(R.id.sb_progress);
 
        fl_top = findViewById(R.id.fl_top);
        fl_bottom = findViewById(R.id.fl_bottom);
 
        tv_save.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        vv_video.setOnClickListener(this);
        iv_status.setOnClickListener(this);
 
        Drawable drawable = getNewDrawable(R.drawable.icon_play_video_thumb, DimenUtils.dip2px(getApplicationContext(), 36), DimenUtils.dip2px(getApplicationContext(), 36));
        sb_progress.setThumb(drawable);
 
        sb_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    vv_video.seekTo(progress);
                }
            }
 
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
 
            }
 
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
 
            }
        });
    }
 
 
    //调用函数缩小图片
    public BitmapDrawable getNewDrawable(int restId, int dstWidth, int dstHeight) {
        Bitmap Bmp = BitmapFactory.decodeResource(
                getResources(), restId);
        Bitmap bmp = Bmp.createScaledBitmap(Bmp, dstWidth, dstHeight, true);
        BitmapDrawable d = new BitmapDrawable(bmp);
        Bitmap bitmap = d.getBitmap();
        if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
            d.setTargetDensity(getResources().getDisplayMetrics());
        }
        return d;
    }
 
    int duration = -1;
    String videoUrl;//视频连接
 
    private void initVideoView() {
        videoUrl = getIntent().getStringExtra("url");
        vv_video.setVideoPath(videoUrl);
        vv_video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                duration = mp.getDuration();
                initSeekBarData();
                handler.sendEmptyMessage(1);
                handler.sendEmptyMessageDelayed(2, 2000);
                iv_status.setImageResource(R.drawable.icon_play_video_status_pause);
            }
        });
        vv_video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (errorCount > 2)
                    return;
                vv_video.setVideoPath(videoUrl);
                vv_video.start();
            }
        });
        vv_video.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
 
                ToolUtil.setGeneralPop(VideoPlayActivity.this,"温馨提示","糟糕,视频播放出错了。","确定",TEXT_ALIGIN_MIDDLE,new GeneralCallback(){
                    @Override
                    public void onSuccess() {
 
                    }
 
                    @Override
                    public void onError() {
 
                    }
                });
                return true;
            }
        });
 
 
        vv_video.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });
        vv_video.setOnClickListener(this);
        vv_video.start();
    }
 
    private String convertTime(int ms) {
        if (ms < 0)
            return "00:00";
        int s = ms / 1000;
        int hour = s / 3600;
        int minute = (s % 3600) / 60;
        int second = s % 60;
 
        String st = "";
        if (hour > 0) {
            if (hour < 10)
                st += "0";
            st += hour + ":";
 
        }
 
        if (minute < 10)
            st += "0";
        st += minute + ":";
 
        if (second < 10)
            st += "0";
        st += second;
 
        return st;
    }
 
    private void initSeekBarData() {
        tv_total_time.setText(convertTime(duration));
        sb_progress.setMax(duration);
 
    }
 
    private void setPlayProgress(int playTime) {
        tv_play_time.setText(convertTime(playTime));
    }
 
 
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (errorCount > 2)
                        return;
                    //1.得到当前的视频播放进程
                    int currentPosition = vv_video.getCurrentPosition();//0
 
                    //2.SeekBar.setProgress(当前进度);
                    sb_progress.setProgress(currentPosition);
 
                    setPlayProgress(currentPosition);
 
                    //4.每秒更新一次
                    handler.removeMessages(1);
                    handler.sendEmptyMessageDelayed(1, 1000);
                    break;
 
                case 2:
                    hiddenController();
                    break;
                case 3:
                    Toast.makeText(VideoPlayActivity.this, "保存视频成功", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(VideoPlayActivity.this, "保存视频失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
 
 
    private void initData() {
        mPermissionsChecker = new PermissionHelper(this, this);//权限
        initVideoView();
    }
 
 
    int animationDuration = 500;
 
    private synchronized void showController() {
        if (fl_top.getAnimation() != null && fl_top.getAnimation().hasStarted())
            return;
        if (fl_top.getVisibility() == View.VISIBLE)
            return;
 
        iv_status.setVisibility(View.VISIBLE);
        TranslateAnimation showAnimTop = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        showAnimTop.setDuration(animationDuration);
 
        showAnimTop.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                fl_top.setVisibility(View.VISIBLE);
            }
 
            @Override
            public void onAnimationEnd(Animation animation) {
                handler.removeMessages(2);
                handler.sendEmptyMessageDelayed(2, 3000);
            }
 
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
 
 
        TranslateAnimation showAnimBottom = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f);
        showAnimBottom.setDuration(animationDuration);
 
        showAnimBottom.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                fl_bottom.setVisibility(View.VISIBLE);
            }
 
            @Override
            public void onAnimationEnd(Animation animation) {
            }
 
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
 
        fl_top.startAnimation(showAnimTop);
        fl_bottom.startAnimation(showAnimBottom);
    }
 
    private synchronized void hiddenController() {
        if (fl_top.getAnimation() != null && fl_top.getAnimation().hasStarted())
            return;
        if (fl_top.getVisibility() == View.GONE)
            return;
        if (!vv_video.isPlaying())
            return;
        iv_status.setVisibility(View.GONE);
        TranslateAnimation hideAnimTop = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f);
        hideAnimTop.setDuration(animationDuration);
 
        hideAnimTop.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
 
            }
 
            @Override
            public void onAnimationEnd(Animation animation) {
                fl_top.setVisibility(View.GONE);
            }
 
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
 
 
        TranslateAnimation hideAnimBottom = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
        hideAnimBottom.setDuration(animationDuration);
 
        hideAnimBottom.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
 
            @Override
            public void onAnimationEnd(Animation animation) {
                fl_bottom.setVisibility(View.GONE);
            }
 
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
 
        fl_top.startAnimation(hideAnimTop);
        fl_bottom.startAnimation(hideAnimBottom);
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.vv_video:
                if (fl_top.getVisibility() == View.VISIBLE) {
                    hiddenController();
                } else {
                    showController();
                }
                break;
            case R.id.iv_status:
                if (vv_video.isPlaying()) {
                    vv_video.pause();
                    iv_status.setImageResource(R.drawable.icon_play_video_status_play);
                    showController();
                } else {
                    vv_video.start();
                    iv_status.setImageResource(R.drawable.icon_play_video_status_pause);
                    //隐藏操作条
                    handler.removeMessages(2);
                    handler.sendEmptyMessageDelayed(2, 3000);
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_save:
                if (mPermissionsChecker.lacksPermissions(getPermissions())) { //检测权限
                    mPermissionsChecker.showNormalDialog();
                } else {
                    saveVideo(videoUrl);
                }
                break;
        }
    }
 
 
    /**
     * 保存视频
     *
     * @param videoUrl
     */
    public void saveVideo(final String videoUrl) {
        final String fileName = MD5Utils.getMD532(videoUrl);
        final String path = Environment.getExternalStorageDirectory().getPath() + "/BanLiVideo/" + fileName + ".mp4";
        final File file = new File(path);
        if (!file.isDirectory() && file.exists()) {
            Toast.makeText(this, "视频已保存", Toast.LENGTH_SHORT).show();
            return;
        }
 
        new Thread() {
            @Override
            public void run() {
                DownLoadFile df = new DownLoadFile();
                File video = new File(file.getParentFile().getAbsolutePath(), file.getName());
                try {
                    df.downLoadFile(null, video.getPath(), videoUrl, VideoPlayActivity.this);
                    handler.sendEmptyMessage(3);//视频保存成功
                    //通知系统保存成功
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(video);
                    intent.setData(uri);
                    sendBroadcast(intent);
                } catch (Exception e) {//视频保存失败
                    e.printStackTrace();
                    if (video.exists())
                        video.delete();
                    handler.sendEmptyMessage(4);
                }
            }
        }.start();
    }
 
    protected PermissionHelper mPermissionsChecker; // 权限检测器 检测是否有储存卡写入读取权限
 
    /**
     * 权限请求码
     *
     * @return
     */
    @Override
    public int getPermissionsRequestCode() {
        return 1001;
    }
 
    /**
     * 请求权限
     *
     * @return
     */
    @Override
    public String[] getPermissions() {
        return new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
    }
 
    /**
     * 权限请求成功
     */
    @Override
    public void requestPermissionsSuccess() {
        tv_save.performClick();
    }
 
    /**
     * 权限请求失败
     */
    @Override
    public void requestPermissionsFail() {
//        Toast.makeText(this, "你以拒绝权限", Toast.LENGTH_SHORT).show();
    }
 
    /**
     * 请求权限结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (mPermissionsChecker.requestPermissionsResult(requestCode, permissions, grantResults)) {
            //权限请求结果,并已经处理了该回调
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
 
    int lastPosition = 0;
 
    @Override
    protected void onPause() {
        super.onPause();
        if (vv_video.isPlaying()) {
            lastPosition = vv_video.getCurrentPosition();
            iv_status.performClick();
        }
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        if (lastPosition > 0) {
            vv_video.seekTo(lastPosition);
            sb_progress.setProgress(lastPosition);
            if (!vv_video.isPlaying())
                vv_video.start();
        }
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (vv_video.isPlaying()) {
            vv_video.pause();
        }
    }
}