• Android——m3u8视频文件下载


    效果图

    简介

    Aria

    下载器采用开源框架Aria
    github
    中文文档

    导入Aria

       implementation 'me.laoyuyu.aria:core:3.8.16'
        annotationProcessor 'me.laoyuyu.aria:compiler:3.8.16'
        implementation 'me.laoyuyu.aria:m3u8:3.8.16'
    
    • 1
    • 2
    • 3

    介绍

    service在Appliaction中启动,即启动app即启动service并且service只启动一次,后序通过单例binder去调用服务

    启动Service

    在Application中默认启动Service

    private void bindService(){
            DownloadService.bindService(this, new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
    
                }
    
                @Override
                public void onServiceDisconnected(ComponentName name) {
                    downloadService = null;
                }
            });
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    DownloadService

    用于Aplication调用起服务

    public static void bindService(Context context, ServiceConnection connection){
            Intent intent = new Intent(context, DownloadService.class);
            context.bindService(intent, connection, Service.BIND_AUTO_CREATE);
        }
    
    • 1
    • 2
    • 3
    • 4

    注册下载器

    @Override
        public void onCreate() {
            super.onCreate();
            Aria.download(this).register();
            Log.d("DownloadService","create service");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    若上次有未下载完成的视频,则恢复下载,并将binder赋给另一个单例binder,后续使用binder进行具体下载事项

    @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            Log.d("DownloadService","bind service");
            long taskId = (long)SP.getInstance().GetData(BaseApplication.getContext(),"lastDownloadID",0L);
            if (taskId != 0L){
                List entityList = Aria.download(this).getAllNotCompleteTask();
                if (entityList != null){
                    HttpNormalTarget target = Aria.download(this).load(taskId);
                    if (target.getTaskState() != STATE_COMPLETE){
                        target.m3u8VodOption(DownloadBinder.getInstance().getOption());
                        target.resume();
                        Log.d("DownloadService","resume download");
                    } else {
                        HttpNormalTarget resume =  Aria.download(this).load( entityList.get(0).getId());
                        resume.m3u8VodOption(DownloadBinder.getInstance().getOption());
                        if ((resume.getTaskState() == STATE_FAIL) || (resume.getTaskState() == STATE_OTHER)){
                            resume.resetState();
                            Log.d("DownloadService","resetState");
                        }else {
                            resume.resume();
                            Log.d("DownloadService","resumeState");
                        }
                    }
                }
            }
            return DownloadBinder.getInstance();
        }
    
    • 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

    注销aria下载器和解除binder绑定

     @Override
        public boolean onUnbind(Intent intent) {
            Log.d("DownloadService","unbind service");
            return super.onUnbind(intent);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Aria.download(this).unRegister();
            Log.d("DownloadService","service onDestroy");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    下载回调

    然后将Aria下载器的回调在进行一次中转,回调至单例binder,后面在下载就不需要binder服务,直接调用单例binder即可

        @Download.onNoSupportBreakPoint public void onNoSupportBreakPoint(DownloadTask task) {
            Log.d("DownloadService","该下载链接不支持断点");
           // DownloadBinder.getInstance().onTaskStart(task);
        }
    
        @Download.onTaskStart public void onTaskStart(DownloadTask task) {
            Log.d("DownloadService",task.getDownloadEntity().getFileName() +":开始下载");
            DownloadBinder.getInstance().onTaskStart(task);
        }
    
        @Download.onTaskStop public void onTaskStop(DownloadTask task) {
            Log.d("DownloadService",task.getDownloadEntity().getFileName() +":停止下载");
            DownloadBinder.getInstance().onTaskStop(task);
        }
    
        @Download.onTaskCancel public void onTaskCancel(DownloadTask task) {
            Log.d("DownloadService",task.getDownloadEntity().getFileName() +":取消下载");
            DownloadBinder.getInstance().onTaskCancel(task);
        }
    
        @Download.onTaskFail public void onTaskFail(DownloadTask task) {
            Log.d("DownloadService",task.getDownloadEntity().getFileName() +":下载失败");
            DownloadBinder.getInstance().onTaskFail(task);
        }
    
        @Download.onTaskComplete public void onTaskComplete(DownloadTask task) {
            Log.d("DownloadService",task.getDownloadEntity().getFileName() +":下载完成");
            DownloadBinder.getInstance().onTaskComplete(task);
        }
        /**
         * @param e 异常信息
         */
        @Download.onTaskFail void taskFail(DownloadTask task, Exception e) {
            try {
                DownloadBinder.getInstance().taskFail(task,e);
                ALog.d("DownloadService", task.getDownloadEntity().getFileName() +"error:"+ALog.getExceptionString(e));
            }catch (Exception ee){
                ee.printStackTrace();
            }
        }
    
        @Download.onTaskRunning public void onTaskRunning(DownloadTask task) {
            Log.d("DownloadService","pre = "+task.getPercent()+"   "+"speed = "+ task.getConvertSpeed());
            DownloadBinder.getInstance().onTaskRunning(task);
        }
    }
    
    • 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

    回调接口

    将服务中的Aria回调,回调至单例binder中

    public interface ServiceCallback {
        void onTaskStart(DownloadTask task);
        void onTaskStop(DownloadTask task);
        void onTaskCancel(DownloadTask task);
        void onTaskFail(DownloadTask task);
        void onTaskComplete(DownloadTask task);
        void onTaskRunning(DownloadTask task);
        void taskFail(DownloadTask task, Exception e);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    单例Binder

    构造单例

    public class DownloadBinder extends Binder implements ServiceCallback {
     private static DownloadBinder binder;
        private DownloadBinder() {
    
        }
    
        public static DownloadBinder getInstance() {
            if (binder == null) {
                binder = new DownloadBinder();
                downloadReceiver = Aria.download(BaseApplication.getContext());
            }
            return binder;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    下载

    将下载信息传入,并以视频type+id+name等构件下载文件夹名称,确保唯一性,然后通过配置Aria Option,使其切换至m3u8文件下载模式,具体配置文件还可配置下载速度、最大下载文件数量、线程数等等。
    Aria自带数据库,可通过其数据库保存一些数据,但读取数据较慢

    
        public void startDownload(DownloadBean downloadBean) {
            if (downloadBean == null) return;
            String locationDir = FileUtils.getInstance().mainCatalogue();
            String name = downloadBean.getVideoType()+downloadBean.gettId() + downloadBean.getsId() + downloadBean.geteId();
            String subFile = FileUtils.getInstance().createFile(locationDir, name);
            String path = subFile + File.separator + name + ".m3u8";
            Log.d("DownloadService", "start download");
            boolean isExist = IsExist(path);
            if (isExist) {
                Log.d("DownloadService", "exist same item");
                if (repeatTaskId != 0) {
                    if (Aria.download(this).load(repeatTaskId).getTaskState() != STATE_RUNNING) {
                        if (downloadReceiver.load(repeatTaskId).getEntity().getRealUrl().equals(downloadBean.getVideoUrl())) {
                            downloadReceiver.load(repeatTaskId).m3u8VodOption(DownloadBinder.getInstance().getOption());
                            downloadReceiver.load(repeatTaskId).resume();
                        } else {
                            downloadReceiver.load(repeatTaskId).m3u8VodOption(DownloadBinder.getInstance().getOption());
                            downloadReceiver.load(repeatTaskId).updateUrl(downloadBean.getVideoUrl()).resume();
                        }
                    }
                    Log.d("DownloadService", "resume exist same item");
                    return;
                }
            }
    
            HttpBuilderTarget target = downloadReceiver.load(downloadBean.getVideoUrl())
                    .setFilePath(path)
                    .ignoreFilePathOccupy()
                    .m3u8VodOption(getOption());
    
            List downloadEntityList = downloadReceiver.getDRunningTask();
            if (downloadEntityList == null) {
                repeatTaskId = target.create();
            } else {
                repeatTaskId = target.add();
            }
    
            try {
                repeatTaskId = target.getEntity().getId();
                downloadBean.setTaskId(repeatTaskId);
                SP.getInstance().PutData(BaseApplication.getContext(),"lastDownloadID",repeatTaskId);
                target.setExtendField(new Gson().toJson(downloadBean)).getEntity().save();
            }catch (NullPointerException e){
                e.printStackTrace();
            }
        }
    
    • 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

    辐射

    再一次将service回调的接口回调至binder的接口,通过EventBus辐射至外部,通过一层层封装,在外部监听当前文件下载状态,只需通过监听EventBus事件即可

     /**
         * download status
         * 0:prepare
         * 1:starting
         * 2:pause
         * 3:cancel
         * 4:failed
         * 5:completed
         * 6:running
         * 7:exception*/
        @Override
        public void onTaskStart(DownloadTask task) {
            EventBus.getDefault().postSticky(new DownloadStatusBean(1,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
        }
    
        @Override
        public void onTaskStop(DownloadTask task) {
            EventBus.getDefault().postSticky(new DownloadStatusBean(2,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
        }
    
        @Override
        public void onTaskCancel(DownloadTask task) {
            EventBus.getDefault().postSticky(new DownloadStatusBean(3,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
        }
    
        @Override
        public void onTaskFail(DownloadTask task) {
            EventBus.getDefault().postSticky(new DownloadStatusBean(4,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
        }
    
        @Override
        public void onTaskComplete(DownloadTask task) {
            EventBus.getDefault().postSticky(new DownloadStatusBean(5,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
        }
    
        @Override
        public void onTaskRunning(DownloadTask task) {
            EventBus.getDefault().postSticky(new DownloadStatusBean(6,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
        }
    
        @Override
        public void taskFail(DownloadTask task, Exception e) {
            try {
                EventBus.getDefault().postSticky(new DownloadStatusBean(4,task.getDownloadEntity().getId(), task.getConvertSpeed(), task.getPercent(),task.getConvertFileSize(),task.getFilePath()));
            }catch (NullPointerException ee){
                ee.printStackTrace();
            }
        }
    }
    
    • 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

    创建下载实例

    一句话我们就可以实现视频下载,然后后天服务自动回调给binder,然后binder回调给EventBus

     DownloadBean bean = new DownloadBean(0L,m_id,"","",sourceBean.getLink(),detailBean.getCover(),detailBean.getTitle(),"","","movie","",0);
      DownloadBinder.getInstance().startDownload(bean);
    
    • 1
    • 2

    监听下载状态

    然后只需要在需要更新界面的地方注册EventBus即可,通过封装,不同的类做不同的事情,将数据处理和UI更新进行隔离,可以提高代码阅读和执行效率

     /**
         * download status
         * 0:prepare
         * 1:starting
         * 2:pause
         * 3:cancel
         * 4:failed
         * 5:completed
         * 6:running
         * 7:exception*/
        /**
         * 下载item状态监听*/
        @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
        public void OnEvent(DownloadStatusBean bean) {
            taskID = bean.getTaskID();
            switch (bean.getStatus()) {
                case 1:
                    getRunningItem();
                    Log.d("DownloadService", "status start");
                    break;
                case 2:
                    updateStatus(bean);
                    Log.d("DownloadService", "status pause");
                    break;
                case 3:
                    if ((index == -1) && (beanList.size() > 0)){
                        index = 0;
                    }
                    Log.d("DownloadService", "status cancel"+bean.getTaskID());
                    break;
                case 4:
                    //update url
                    failCount++;
                    if (failCount >= 3){
                        failedReconnect(bean);
                        failCount = 0;
                        isRunning = true;
                        Log.d("DownloadService", "status fail in");
                    }
                    Log.d("DownloadService", "status fail");
                    break;
                case 5:
                    removeDownloadBead(bean.getTaskID());
                    startDownload();
                    Log.d("DownloadService", "status complete");
                    break;
                case 6:
                    if (isRunning) {
                        getRunningItem();
                    }
                    updateCurItem(bean);
                    Log.d("DownloadService", "status running: "+index);
                    break;
            }
        }
    
    • 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
  • 相关阅读:
    成本翻倍,部署复杂!为什么要停止使用Kubernetes
    MATLAB嵌套if语句
    【python小脚本】监听日志文件异常数据发送告警短信
    动手学习深度学习 05:深度学习计算
    按键的单击、双击、连续按、短按和长按实现思路
    gitbook使用
    Spark任务调度
    React脚手架配置axios代理 (1.配置在package.json, 2.配置在setupProxy.js)
    nvm 版本管理详解
    初识进程~
  • 原文地址:https://blog.csdn.net/News53231323/article/details/126020927