Android簡(jiǎn)單實(shí)現(xiàn)文件下載
本文實(shí)例為大家分享了Android簡(jiǎn)單實(shí)現(xiàn)文件下載的具體代碼,供大家參考,具體內(nèi)容如下
權(quán)限
<!-- 文件讀寫(xiě)權(quán)限 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- 訪問(wèn)內(nèi)存 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
DownloadOkHttp 使用(無(wú)顯示)
下載完成地址: /storage/emulated/0/小紅書(shū)/xiaohongshu.apk
DownloadUtil.DownloadOkHttp.get().download(apk, Environment.getExternalStorageDirectory() + "/" + "小紅書(shū)", new DownloadUtil.DownloadOkHttp.OnDownloadListener() {
@Override
public void onDownloadSuccess() {
Log.e("下載","成功");
}
@Override
public void onDownloading(int progress) {
Log.e("下載", String.valueOf(progress));
}
@Override
public void onDownloadFailed() {
Log.e("下載","失敗");
}
});
Download 使用(有顯示)
下載完成地址: /小紅書(shū)/小紅書(shū).apk
new DownloadUtil.Download(this, apk, "小紅書(shū).apk", "小紅書(shū)");
dialog_progress
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/dp_20"
android:orientation="vertical">
<ProgressBar
android:id="@+id/id_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/id_text"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:gravity="right"
android:text="0 %"
android:layout_height="wrap_content"/>
</LinearLayout>
**工具類(lèi)DownloadUtil(兩個(gè)實(shí)現(xiàn)方法,自己悟?。。。?/p>
package com.simon.util;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.simon.app.R;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import androidx.annotation.NonNull;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* 創(chuàng)建者: Simon
* 創(chuàng)建時(shí)間:2021/6/7 13:58
* 描述:文件下載
*/
public class DownloadUtil {
public static class DownloadOkHttp {
private static DownloadOkHttp downloadUtil;
private final OkHttpClient okHttpClient;
public static DownloadOkHttp get() {
if (downloadUtil == null) {
downloadUtil = new DownloadOkHttp();
}
return downloadUtil;
}
private DownloadOkHttp() {
okHttpClient = new OkHttpClient();
}
/**
*
* @param url 下載連接
* @param saveDir 儲(chǔ)存下載文件的SDCard目錄
* @param listener 下載監(jiān)聽(tīng)
*/
public void download( 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();
} 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;
}
/**
* url
* 從下載連接中解析出文件名
*/
@NonNull
public static 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();
}
}
public static class Download {
private String fileSavePath = "";//保存文件的本地路徑
private String fileDownLoad_path = "";//下載的URL
private String mfileName = "";//下載的文件名字
private boolean mIsCancel = false;
private int mProgress;
private ProgressBar mProgressBar;
private TextView text;
private Dialog mDownloadDialog;
private final Context context;
private static final int DOWNLOADING = 1;
private static final int DOWNLOAD_FINISH = 2;
private Handler mUpdateProgressHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWNLOADING:
// 設(shè)置進(jìn)度條
mProgressBar.setProgress(mProgress);
text.setText(String.valueOf(mProgress));
break;
case DOWNLOAD_FINISH:
// 隱藏當(dāng)前下載對(duì)話框
mDownloadDialog.dismiss();
}
}
};
/**
* 下載初始化
* @param context 上下文
* @param fileDownLoad_path 下載的URL
* @param mfileName 下載的文件名字
* @param fileSavePath 保存文件的本地路徑
*/
public Download(Context context, String fileDownLoad_path, String mfileName, String fileSavePath) {
this.context = context;
this.fileDownLoad_path = fileDownLoad_path;
this.mfileName = mfileName;
this.fileSavePath = Environment.getExternalStorageDirectory() + "/" + fileSavePath;
showDownloadDialog();
}
/**
* 顯示正在下載的對(duì)話框
*/
protected void showDownloadDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("下載中");
View view = LayoutInflater.from(context).inflate(R.layout.dialog_progress, null);
mProgressBar = (ProgressBar) view.findViewById(R.id.id_progress);
text = view.findViewById(R.id.id_text);
builder.setView(view);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 隱藏當(dāng)前對(duì)話框
dialog.dismiss();
// 設(shè)置下載狀態(tài)為取消
mIsCancel = true;
}
});
mDownloadDialog = builder.create();
mDownloadDialog.show();
// 下載文件
downloadFile();
}
/**
* 下載文件
*/
private void downloadFile() {
new Thread(new Runnable() {
@Override
public void run() {
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File dir = new File(fileSavePath);
if (!dir.exists()){
dir.mkdirs();
}
// 下載文件
HttpURLConnection conn = (HttpURLConnection) new URL(fileDownLoad_path).openConnection();
conn.connect();
InputStream is = conn.getInputStream();
int length = conn.getContentLength();
File apkFile = new File(fileSavePath, mfileName);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
byte[] buffer = new byte[1024];
while (!mIsCancel) {
int numread = is.read(buffer);
count += numread;
// 計(jì)算進(jìn)度條當(dāng)前位置
mProgress = (int) (((float) count / length) * 100);
// 更新進(jìn)度條
mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);
// 下載完成
if (numread < 0) {
mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
fos.write(buffer, 0, numread);
}
fos.close();
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}
以上就是本文的全部?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自動(dòng)化獲取卡頓信息的實(shí)現(xiàn)方法
自動(dòng)化獲取卡頓信息就像給App裝 “行車(chē)記錄儀” —— 實(shí)時(shí)記錄主線程的“駕駛狀態(tài)”,一旦發(fā)現(xiàn)“急剎車(chē)”(卡頓),立刻保存現(xiàn)場(chǎng)(堆棧),事后回看錄像(日志)精準(zhǔn)定位問(wèn)題,本文給大家介紹了Android自動(dòng)化獲取卡頓信息的實(shí)現(xiàn)方法,需要的朋友可以參考下2025-02-02
Android?webView加載數(shù)據(jù)時(shí)內(nèi)存溢出問(wèn)題及解決
這篇文章主要介紹了Android?webView加載數(shù)據(jù)時(shí)內(nèi)存溢出問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
Android獲得當(dāng)前正在顯示的activity類(lèi)名的方法
這篇文章主要介紹了Android獲得當(dāng)前正在顯示的activity類(lèi)名的方法,分析了權(quán)限的修改與Java代碼的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-01-01
Android通過(guò)ViewModel保存數(shù)據(jù)實(shí)現(xiàn)多頁(yè)面的數(shù)據(jù)共享功能
這篇文章主要介紹了Android通過(guò)ViewModel保存數(shù)據(jù)實(shí)現(xiàn)多頁(yè)面的數(shù)據(jù)共享功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-11-11
Android中AutoCompleteTextView與TextWatcher結(jié)合小實(shí)例
這篇文章主要為大家詳細(xì)介紹了Android中AutoCompleteTextView與TextWatcher結(jié)合的小實(shí)例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05
Android編程調(diào)用系統(tǒng)自帶的拍照功能并返回JPG文件示例【附demo源碼下載】
這篇文章主要介紹了Android編程調(diào)用系統(tǒng)自帶的拍照功能并返回JPG文件,結(jié)合實(shí)例形式分析了Android的拍照功能調(diào)用及圖形文件操作技巧,并附帶demo源碼供讀者下載參考,需要的朋友可以參考下2017-07-07

