1.引入依赖:
implementation 'com.liulishuo.filedownloader:library:1.7.6'
2.在自定义的Application子类的onCreate中初始化
public void onCreate() {
super.onCreate();
app = this;
// FileDownload初始化
FileDownloader.setupOnApplicationOnCreate(this)
.connectionCreator(new FileDownloadUrlConnection
.Creator(new FileDownloadUrlConnection.Configuration()
.connectTimeout(15_000) // set connection timeout.
.readTimeout(15_000) // set read timeout.
))
.commit();
}
3.创建一个下载任务
String directory= Environment.getExternalStorageDirectory()+ File.separator+CAMERA+File.separator;
String path = directory+ System.currentTimeMillis()+".png";
BaseDownloadTask downloadTask = FileDownloader.getImpl().create(uri.toString())
.setPath(path, false)
.setListener(new FileDownloadListener() {
@Override
protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
}
@Override
protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
}
@Override
protected void completed(BaseDownloadTask task) {
Toast.makeText(UIUtils.getContext(),"图片已保存到:"+directory+" 文件夹",Toast.LENGTH_SHORT).show();
}
@Override
protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
}
@Override
protected void error(BaseDownloadTask task, Throwable e) {
}
@Override
protected void warn(BaseDownloadTask task) {
}
});
downloadTask.start(); //开始下载
over.结束
网友评论