Android 后台下载视频

博客新手

 

首先我用得是

implementation 'com.liulishuo.filedownloader:library:1.7.6'
实现得视频缓存

通过service后台下载。下载得状态通过广播发送出去更新UI。

代码:

首先先创建个service 在清单文件里面注册

public class DownloadService extends Service {

    private String uri;
    private HuancunBean dataa;

    MyReceiver1 myreceiver;

    private List<Integer> downloadingTaskId = new ArrayList<>();//正在下载中的id


    @Override
    public void onCreate() {

        FileDownloader.setup(DownloadService.this);
        myreceiver = new MyReceiver1();  //创建BroadcastReceiver子类对象
        super.onCreate();

    }


    List<Integer> list = new ArrayList<>();

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

    }

    private class MyReceiver1 extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //这里接受处理activity传来的广播,如手动控制service停止等

            int pos = intent.getIntExtra("pos", 0);


            dataa = (HuancunBean) intent.getSerializableExtra("dataa");

            String video = intent.getStringExtra("video");
            uri = intent.getStringExtra("uri");

            Downloader downloader = new Downloader(DownloadService.this, video, uri);
            downloader.setDownloadListener(downListener);

            if (list != null){
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i) == pos){

                        Intent intent1 = new Intent();
                        intent1.setAction("com.cwb.Huancun2");
                        intent1.putExtra("pos",list.get(i));
                        sendBroadcast(intent1);
                        downloadingTaskId.remove(i);
                        list.remove(i);
                        downloader.start().pause();
                        return;
                    }
                }
            }
            list.add(pos);

            downloader.start().start();
            downloadingTaskId.add(downloader.start().getId());


        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getApplicationContext().unregisterReceiver(myreceiver);//取消注册
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.cwb.MyService");
        getApplicationContext().registerReceiver(myreceiver, filter);

        return super.onStartCommand(intent, flags, startId);
    }



    /**
     * 下载监听
     */
    private DownloadListener downListener = new DownloadListener() {
        
        Intent intent = new Intent();

        @Override
        public void onSuccess(BaseDownloadTask task) {
            for (int i = 0; i < downloadingTaskId.size(); i++) {
                if (task.getId() == downloadingTaskId.get(i)){
                    final int finalI = i;
                    HttpRequest.POST(DownloadService.this, changeDownload, new Parameter()
                                    .add("token", Preferences.getInstance().getString(DownloadService.this, "TOKEN", "token"))
                                    .add("lesson_id", dataa.getData().get(list.get(i)).getLesson_id())
                                    .add("eposode_id", dataa.getData().get(list.get(i)).getId())
                                    .add("download_status", 3)
                                    .add("file_path",new File(uri).getPath())
                            , new ResponseListener() {
                                @Override
                                public void onResponse(String response, Exception error) {
                                    if (error == null) {
                                        Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                                        if (map.get("code").equals("1")){
                                            intent.setAction("com.cwb.Huancun1");
                                            intent.putExtra("pos",list.get(finalI));
                                            sendBroadcast(intent);
                                        }

                                    }
                                }
                            });

                }
            }



        }

        @Override
        public void onStart(int fileByteSize) {
            Log.e("开始了","kaishile");
        }

        @Override
        public void onResume1() {
        }

        @Override
        public void onProgress(int receivedBytes,BaseDownloadTask task) {
            
            for (int i = 0; i < downloadingTaskId.size(); i++) {
                if (task.getId() == downloadingTaskId.get(i)){
                    intent.setAction("com.cwb.Huancun");
                    intent.putExtra("progress", receivedBytes);
                    intent.putExtra("pos",list.get(i));
                    sendBroadcast(intent);
                }
            }
        }

        @Override
        public void onPause1() {

        }

        @Override
        public void onFail() {
//            intent.setAction(MainActivity.ACTION_DOWNLOAD_FAIL);
//            sendBroadcast(intent);
//            flag = Flag_Init;
        }

        @Override
        public void onCancel() {
        }
    };

}

 

之后就是下载得代码了

public class Downloader {

    String urlStr;// 下载链接
    String filePath;// 下载路径

    DownloadListener downloadListener;
    public void setDownloadListener(DownloadListener listener) {
        this.downloadListener = listener;
    }

    public Downloader(Context context, String url, String filePath) {
        this.urlStr = url;
        this.filePath = filePath;
    }


    /**
     * 开始下载
     */
    public BaseDownloadTask start() {
        
        final BaseDownloadTask baseDownloadTask = FileDownloader.getImpl().create(urlStr).setPath(new File(filePath).getPath()).setListener(new FileDownloadLargeFileListener() {
            @Override
            protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                downloadListener.onStart(111);
            }

            @Override
            protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                downloadListener.onProgress((int) (soFarBytes * 100 / totalBytes),task);
            }

            @Override
            protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {
            }

            @Override
            protected void completed(BaseDownloadTask task) {

                downloadListener.onSuccess(task);

            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                Log.e("", "error: ", e);
            }

            @Override
            protected void warn(BaseDownloadTask task) {

            }
        });

        return baseDownloadTask;
    }

    private boolean isPause;

    public void pause() {
        isPause = true;
    }

    public void resume() {
        isPause = false;
        isCancel = false;
        downloadListener.onResume1();
    }

    private boolean isCancel;

    public void cancel() {
        isCancel = true;
    }
}

 

在之后就是Listener了

public interface DownloadListener {

    void onStart(int fileByteSize);

    void onPause1();

    void onResume1();

    void onProgress(int receivedBytes,BaseDownloadTask task);

    void onFail();

    void onSuccess(BaseDownloadTask task);

    void onCancel();

}

后台下载得代码就完成了,之后就是广播,我在这用得是两个动态得广播,我是在mainAty里面接收service传过来得动态,之后在从mainAty里面把动态传到你下载得页面去更新UI,为什么要这么做呢,主要是动态得广播是跟随activity得生命周期得ondestory而结束,但是我们得需求是退出了这个页面还是能够下载得,所以我把接收service得动态放到了mainAty里面  因为app如果退出了,下载肯定是停止得,但是要是退出下载页面或者直接点击home键的话,下载还是会继续运行的,有人肯定会问要是退出下载页面  那下载页面的广播不久停了吗,没错 !是停了,但是我们还是在接收这service的动态,因为mainAty没有退出,当在此点击进去下载页面,下载页面的广播又继续接收mainAty发来的广播,所以后台下载视频的流程就结束了

mainAty广播:

huancunreceiver = new Huancunreceiver();

IntentFilter filter = new IntentFilter();
filter.addAction("com.cwb.Huancun");
filter.addAction("com.cwb.Huancun1");
filter.addAction("com.cwb.Huancun2");
registerReceiver(huancunreceiver, filter);
public class Huancunreceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        switch (intent.getAction()){
            case "com.cwb.Huancun":
                int progress = intent.getIntExtra("progress",0);
                int pos = intent.getIntExtra("pos", 0);
                Log.e("posssqqqqq",pos+"               "+progress);
                Intent intent1 = new Intent();
                intent1.setAction("com.cwb.main");
                intent1.putExtra("progress", progress);
                intent1.putExtra("pos",pos);
                sendBroadcast(intent1);
                break;
            case "com.cwb.Huancun1":
                int pos1 = intent.getIntExtra("pos", 0);
                Intent intent2 = new Intent();
                intent2.setAction("com.cwb.main1");
                intent2.putExtra("pos",pos1);
                sendBroadcast(intent2);
                break;
            case "com.cwb.Huancun2":
                int pos2= intent.getIntExtra("pos", 0);
                Intent intent3 = new Intent();
                intent3.setAction("com.cwb.main2");
                intent3.putExtra("pos",pos2);
                sendBroadcast(intent3);
                break;
        }
    }
}

下载页面的广播:

huancunreceiver = new Huancunreceiver();

IntentFilter filter = new IntentFilter();
filter.addAction("com.cwb.main");
filter.addAction("com.cwb.main1");
filter.addAction("com.cwb.main2");
registerReceiver(huancunreceiver, filter);
public class Huancunreceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        switch (intent.getAction()){
            case "com.cwb.main":
                if (ll.getChildCount() != 0) {
                    int progress = intent.getIntExtra("progress", 0);
                    int pos = intent.getIntExtra("pos", 0);
                    Log.e("posss", pos + "               " + progress);
                    View childAt = ll.getChildAt(pos);
                    ImageView iv = childAt.findViewById(R.id.iv);
                    iv.setImageResource(R.mipmap.ic_zanting);
                    ProgressBar progressBar = childAt.findViewById(R.id.pb);
                    progressBar.setProgress(progress);
                }
                break;
            case "com.cwb.main1":
                int pos1 = intent.getIntExtra("pos", 0);
                View childAt1 = ll.getChildAt(pos1);
                ProgressBar progressBar1 = childAt1.findViewById(R.id.pb);
                TextView status = childAt1.findViewById(R.id.tv_staus);
                ImageView iv1 = childAt1.findViewById(R.id.iv);
                status.setText("已缓存");
                progressBar1.setProgress(100);
                iv1.setImageResource(R.mipmap.ic_zanting);
                break;
            case "com.cwb.main2":
                int pos2= intent.getIntExtra("pos", 0);
                View childAt2 = ll.getChildAt(pos2);
                ImageView iv2 = childAt2.findViewById(R.id.iv);
                iv2.setImageResource(R.mipmap.icon_start_cache);
                break;
        }
    }
}

不懂得可以咨询

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值