首页 > 代码库 > 文件下载工具类

文件下载工具类

先依赖

compile ‘com.liulishuo.filedownloader:library:1.3.0‘

 

import android.content.Context;

import com.hyphenate.chat.EMMessage;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.xuehu365.xuehu.data.DynamicDownLoadData;
import com.xuehu365.xuehu.model.DynamicModel;
import com.xuehu365.xuehu.model.event.DynamicDownLoadProgress;
import com.xuehu365.xuehu.utils.PathUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

/**
 * Created by Administrator on 2017/1/13.
 */
public class DynamicDownLoader {
    public static void downLoad(Context context, final DynamicModel dynamicModel) {
        String fileName = dynamicModel.getLinkUrl().substring(dynamicModel.getLinkUrl().lastIndexOf("/") + 1);
        String filePath = PathUtil.getInstance().getVideoPath() + File.separator + fileName;

        BaseDownloadTask task = FileDownloader.getImpl().create(dynamicModel.getLinkUrl()).setPath(filePath)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        dynamicModel.setDownLoadPercent(Math.round(((float) (soFarBytes * 100)) / totalBytes));
                        dynamicModel.setDownLoadStatus(EMMessage.Status.INPROGRESS.ordinal());
                        DynamicDownLoadData.saveView(dynamicModel);
                        EventBus.getDefault().post(new DynamicDownLoadProgress());
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        dynamicModel.setLoadlUrl(task.getPath());
                        dynamicModel.setDownLoadStatus(EMMessage.Status.SUCCESS.ordinal());
                        DynamicDownLoadData.saveView(dynamicModel);
                        EventBus.getDefault().post(new DynamicDownLoadProgress());
                    }

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

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        dynamicModel.setDownLoadStatus(EMMessage.Status.FAIL.ordinal());
                        DynamicDownLoadData.saveView(dynamicModel);
                        EventBus.getDefault().post(new DynamicDownLoadProgress());
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                });
        task.start();
    }

}

 

文件下载工具类