admin管理员组文章数量:1606523
前几天项目中遇到了下载的问题,就在网上找了一下关于用okHttp下载文件的知识点。
下面这个是一个工具类,直接看代码吧。
/**
* 文件下载工具类(单例模式)
*/
public class DownloadUtil {
private static DownloadUtil downloadUtil;
private final OkHttpClient okHttpClient;
public static DownloadUtil get() {
if (downloadUtil == null) {
downloadUtil = new DownloadUtil();
}
return downloadUtil;
}
public DownloadUtil() {
okHttpClient = new OkHttpClient();
}
/**
* @param url 下载连接
* @param destFileDir 下载的文件储存目录
* @param destFileName 下载文件名称,后面记得拼接后缀,否则手机没法识别文件类型
* @param listener 下载监听
*/
public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
Request request = new Request.Builder()
.url(url)
.build();
OkHttpClient client = new OkHttpClient();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
//异步请求
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下载失败监听回调
listener.onDownloadFailed(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
//储存下载文件的目录
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, destFileName);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
//下载中更新进度条
listener.onDownloading(progress);
}
fos.flush();
//下载完成
listener.onDownloadSuccess(file);
} catch (Exception e) {
listener.onDownloadFailed(e);
}finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
}
}
}
});
}
public interface OnDownloadListener{
/**
* 下载成功之后的文件
*/
void onDownloadSuccess(File file);
/**
* 下载进度
*/
void onDownloading(int progress);
/**
* 下载异常信息
*/
void onDownloadFailed(Exception e);
}
}
单例模式:主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。 使用Singleton的好处还在于可以节省内存,因为它限制了实例的个数,有利于Java垃圾回收(garbage collection)
下面是具体的使用方法:
Environment.getExternalStorageDirectory().getAbsolutePath() 拿到的应该是一个手机内存的根目录
后面的文件名记得添加后缀,否则的话手机可能不会自己识别并到相册的视频文件夹里。
/**
* 文件下载
*/
private void downFile(String url) {
DownloadUtil.get().download(url, Environment.getExternalStorageDirectory().getAbsolutePath(), "文件名",
new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
//下载完成进行相关逻辑操作
Message msg = mHandler.obtainMessage();
msg.what = 0;
mHandler.sendMessage(msg);
}
@Override
public void onDownloading(int progress) {
// progressDialog.setProgress(progress);
Message msg = mHandler.obtainMessage();
msg.what = 11;
msg.obj = progress;
mHandler.sendMessage(msg);
}
@Override
public void onDownloadFailed(Exception e) {
//下载异常进行相关提示操作
Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.obj = e;
mHandler.sendMessage(msg);
}
});
}
最后更新UI的操作还是要放回主线程里,关于handler和progressDialog对话框进度条之类的就不用说了吧。希望对大家有所帮助
版权声明:本文标题:使用okHttp下载文件到本地 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1728500384a1161104.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论