Android實(shí)現(xiàn)文件下載
前言
總體思路:下載文件到應(yīng)用緩存路徑,在相冊(cè)創(chuàng)建文件夾,Copy過(guò)去,通知相冊(cè)刷新。
下載文件到APP緩存路徑,這樣可避免Android高版本讀取本地權(quán)限問(wèn)題,
準(zhǔn)備
implementation 'com.squareup.okhttp3:okhttp:3.6.0' implementation 'com.squareup.okio:okio:1.11.0'
調(diào)用
url:文件url
path:儲(chǔ)存的路徑
應(yīng)用緩存路徑:getExternalCacheDir().getPath()
DownloadUtil.get().download(url, path, new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
//下載成功
handler.sendEmptyMessage(1);
}
@Override
public void onDownloading(int progress) {
//進(jìn)度條
handler.sendEmptyMessage(progress);
}
@Override
public void onDownloadFailed() {
//下載失敗
handler.sendEmptyMessage(-1);
}
});
復(fù)制到相冊(cè)目錄
DownloadUtil.createFiles(downLoadFile);
通知相冊(cè)刷新
DownloadUtil.updateDCIM(this,downloadFile);
工具類(lèi)
/**
* 下載工具類(lèi)
* martin
* 2021.7.21
*/
public class DownloadUtil {
private static final String TAG = DownloadUtil.class.getName();
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();
}
/**
* 復(fù)制單個(gè)文件
*
* @param oldPath$Name String 原文件路徑+文件名 如:data/user/0/com.test/files/abc.txt
* @param newPath$Name String 復(fù)制后路徑+文件名 如:data/user/0/com.test/cache/abc.txt
* @return <code>true</code> if and only if the file was copied;
* <code>false</code> otherwise
*/
public static boolean copyFile(String oldPath$Name, String newPath$Name) {
try {
File oldFile = new File(oldPath$Name);
if (!oldFile.exists()) {
Log.e("--Method--", "copyFile: oldFile not exist.");
return false;
} else if (!oldFile.isFile()) {
Log.e("--Method--", "copyFile: oldFile not file.");
return false;
} else if (!oldFile.canRead()) {
Log.e("--Method--", "copyFile: oldFile cannot read.");
return false;
}
/* 如果不需要打log,可以使用下面的語(yǔ)句
if (!oldFile.exists() || !oldFile.isFile() || !oldFile.canRead()) {
return false;
}
*/
FileInputStream fileInputStream = new FileInputStream(oldPath$Name);
FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
byte[] buffer = new byte[1024];
int byteRead;
while (-1 != (byteRead = fileInputStream.read(buffer))) {
fileOutputStream.write(buffer, 0, byteRead);
}
fileInputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 通知相冊(cè)更新
*
* @param context
* @param newFile
*/
public void updateDCIM(Context context, File newFile) {
File cameraPath = new File(dcimPath, "Camera");
File imgFile = new File(cameraPath, newFile.getAbsolutePath());
if (imgFile.exists()) {
Uri uri = Uri.fromFile(imgFile);
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(uri);
context.sendBroadcast(intent);
}
}
/**
* url 下載連接
* saveDir 儲(chǔ)存下載文件的SDCard目錄
* listener 下載監(jiān)聽(tīng)
*/
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;
// 儲(chǔ)存下載文件的目錄
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(file);
} catch (Exception e) {
listener.onDownloadFailed();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
});
}
/**
* saveDir
* 判斷下載目錄是否存在
*/
private static String isExistDir(String saveDir) throws IOException {
// 下載位置
File downloadFile = new File(saveDir);
if (!downloadFile.mkdirs()) {
downloadFile.createNewFile();
}
String savePath = downloadFile.getAbsolutePath();
return savePath;
}
//系統(tǒng)相冊(cè)路徑
static String dcimPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
/**
* 創(chuàng)建文件夾
*/
public static void createFiles(File oldFile) {
try {
File file = new File(isExistDir(dcimPath + "/xxx"));
String newPath = file.getPath() + "/" + oldFile.getName();
Log.d("TAG", "createFiles111: " + oldFile.getPath() + "--" + newPath);
if (copyFile(oldFile.getPath(), newPath)) {
Log.d("TAG", "createFiles222: " + oldFile.getPath() + "--" + newPath);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* url
* 從下載連接中解析出文件名
*/
@NonNull
public static String getNameFromUrl(String url) {
return url.substring(url.lastIndexOf("/") + 1);
}
public interface OnDownloadListener {
/**
* 下載成功
*/
void onDownloadSuccess(File file);
/**
* @param progress 下載進(jìn)度
*/
void onDownloading(int progress);
/**
* 下載失敗
*/
void onDownloadFailed();
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android文件下載進(jìn)度條的實(shí)現(xiàn)代碼
- Android zip文件下載和解壓實(shí)例
- Android實(shí)現(xiàn)文件下載進(jìn)度顯示功能
- Android 文件下載三種基本方式
- Android實(shí)現(xiàn)簡(jiǎn)單的文件下載與上傳
- Android Retrofit文件下載進(jìn)度顯示問(wèn)題的解決方法
- Android 將文件下載到指定目錄的實(shí)現(xiàn)代碼
- Android文件下載功能實(shí)現(xiàn)代碼
- Android基于HttpUrlConnection類(lèi)的文件下載實(shí)例代碼
- android實(shí)現(xiàn)文件下載功能
相關(guān)文章
Android App開(kāi)發(fā)中Gradle構(gòu)建過(guò)程的配置方法
這篇文章主要介紹了Android App開(kāi)發(fā)中Gradle構(gòu)建過(guò)程的配置方法,包括在Gradle中配置manifest的方法,需要的朋友可以參考下2016-06-06
Android運(yùn)用BroadcastReceiver實(shí)現(xiàn)強(qiáng)制下線(xiàn)
本篇文章主要介紹了Android運(yùn)用BroadcastReceiver實(shí)現(xiàn)強(qiáng)制下線(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
Android Studio下Flutter環(huán)境搭建圖文教程
這篇文章主要為大家詳細(xì)介紹了Android Studio下Flutter環(huán)境搭建圖文教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07
Android 組合控件實(shí)現(xiàn)布局的復(fù)用的方法
本篇文章主要介紹了Android 組合控件實(shí)現(xiàn)布局的復(fù)用的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08
Android實(shí)現(xiàn)兩臺(tái)手機(jī)屏幕共享和遠(yuǎn)程控制功能
在遠(yuǎn)程協(xié)助、在線(xiàn)教學(xué)、技術(shù)支持等多種場(chǎng)景下,實(shí)時(shí)獲得另一部移動(dòng)設(shè)備的屏幕畫(huà)面,并對(duì)其進(jìn)行操作,具有極高的應(yīng)用價(jià)值,本項(xiàng)目旨在實(shí)現(xiàn)兩臺(tái) Android 手機(jī)之間的屏幕共享與遠(yuǎn)程控制,需要的朋友可以參考下2025-04-04
Android如何動(dòng)態(tài)改變App桌面圖標(biāo)
這篇文章主要介紹了 Android動(dòng)態(tài)改變App桌面圖標(biāo)的方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下2017-01-01
解決Android studio中關(guān)于模擬器的/data目錄不能顯示的問(wèn)題
這篇文章主要介紹了解決Android studio中關(guān)于模擬器的/data目錄不能顯示的問(wèn)題,主要原因還是我們權(quán)限不夠,當(dāng)前的用戶(hù)沒(méi)有權(quán)限訪(fǎng)問(wèn)data目錄。具體解決方法大家跟隨腳本之家小編一起看看吧2018-06-06
Android Studio 3.3.2 正式版的安裝教程圖解
這篇文章主要介紹了Android Studio 3.3.2 正式版的安裝教程圖解,本文分步驟通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友可以參考下2020-02-02
Android中RecyclerView實(shí)現(xiàn)Item添加和刪除的代碼示例
本篇文章主要介紹了Android中RecyclerView實(shí)現(xiàn)Item添加和刪除的代碼示例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-09-09

