使用前先依賴 Okhttp:
compile 'com.squareup.okhttp3:okhttp:3.6.0'
直接復(fù)制代碼:
public class DownloadUtil {
private static DownloadUtil downloadUtil;
private final OkHttpClient okHttpClient;
public static DownloadUtil get() {
if (downloadUtil == null) {
downloadUtil = new DownloadUtil();
}
return downloadUtil;
}
private DownloadUtil() {
okHttpClient = new OkHttpClient();
}
/**
* @param url 下載連接
* @param saveDir 儲存下載文件的SDCard目錄
* @param listener 下載監(jiān)聽
*/
public void download(final String url, final String saveDir, final OnDownloadListener listener) {
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下載失敗
listener.onDownloadFailed();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
// 儲存下載文件的目錄
String savePath = isExistDir(saveDir);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
File file = new File(savePath, getNameFromUrl(url));
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();
} catch (Exception e) {
listener.onDownloadFailed();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
});
}
/**
* @param saveDir
* @return
* @throws IOException
* 判斷下載目錄是否存在
*/
private String isExistDir(String saveDir) throws IOException {
// 下載位置
File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
if (!downloadFile.mkdirs()) {
downloadFile.createNewFile();
}
String savePath = downloadFile.getAbsolutePath();
return savePath;
}
/**
* @param url
* @return
* 從下載連接中解析出文件名
*/
@NonNull
private String getNameFromUrl(String url) {
return url.substring(url.lastIndexOf("/") + 1);
}
public interface OnDownloadListener {
/**
* 下載成功
*/
void onDownloadSuccess();
/**
* @param progress
* 下載進(jìn)度
*/
void onDownloading(int progress);
/**
* 下載失敗
*/
void onDownloadFailed();
}
}
使用:
DownloadUtil.get().download(url, "download", new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess() {
Utils.showToast(MainActivity.this, "下載完成");
}
@Override
public void onDownloading(int progress) {
progressBar.setProgress(progress);
}
@Override
public void onDownloadFailed() {
Utils.showToast(MainActivity.this, "下載失敗");
}
});