Android Simple Implementation File Download
- 2021-12-19 06:42:40
- OfStack
This article example for everyone to share Android simple implementation of the specific file download code, for your reference, the specific content is as follows
Authority
<!-- File read and write permissions -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Access memory -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
DownloadOkHttp use (no display)
Download completion address:/storage/emulated/0/Xiaohongshu/xiaohongshu. apk
DownloadUtil.DownloadOkHttp.get().download(apk, Environment.getExternalStorageDirectory() + "/" + " Little Red Book ", new DownloadUtil.DownloadOkHttp.OnDownloadListener() {
@Override
public void onDownloadSuccess() {
Log.e(" Download "," Success ");
}
@Override
public void onDownloading(int progress) {
Log.e(" Download ", String.valueOf(progress));
}
@Override
public void onDownloadFailed() {
Log.e(" Download "," Failure ");
}
});
Download use (on display)
Download completion address:/Xiaohongshu/Xiaohongshu. apk
new DownloadUtil.Download(this, apk, " Little Red Book .apk", " Little Red Book ");
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>
** Tool class DownloadUtil (two implementation methods, self-realization!!!)
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;
/**
* Creator: Simon
* Creation time: 2021/6/7 13:58
* Description: File download
*/
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 Download connection
* @param saveDir That stores the downloaded file SDCard Directory
* @param listener Download monitor
*/
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) {
// Download failed
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;
// Directory to store downloaded files
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);
// Downloading
listener.onDownloading(progress);
}
fos.flush();
// Download complete
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) {
}
}
}
});
}
/**
* Determining whether the download directory exists
* @param saveDir
* @return
* @throws IOException
*/
private String isExistDir(String saveDir) throws IOException {
// Download location
File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
if (!downloadFile.mkdirs()) {
downloadFile.createNewFile();
}
String savePath = downloadFile.getAbsolutePath();
return savePath;
}
/**
* url
* Parse the file name from the download connection
*/
@NonNull
public static String getNameFromUrl(String url) {
return url.substring(url.lastIndexOf("/") + 1);
}
public interface OnDownloadListener {
/**
* Download succeeded
*/
void onDownloadSuccess();
/**
* @param progress
* Download progress
*/
void onDownloading(int progress);
/**
* Download failed
*/
void onDownloadFailed();
}
}
public static class Download {
private String fileSavePath = "";// Save the local path of the file
private String fileDownLoad_path = "";// Downloaded URL
private String mfileName = "";// Name of downloaded file
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:
// Set the progress bar
mProgressBar.setProgress(mProgress);
text.setText(String.valueOf(mProgress));
break;
case DOWNLOAD_FINISH:
// Hide the current download dialog box
mDownloadDialog.dismiss();
}
}
};
/**
* Download initialization
* @param context Context
* @param fileDownLoad_path Downloaded URL
* @param mfileName Name of downloaded file
* @param fileSavePath Save the local path of the file
*/
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();
}
/**
* Displays the dialog box being downloaded
*/
protected void showDownloadDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(" Downloading ");
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(" Cancel ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Hide the current dialog box
dialog.dismiss();
// Set the download status to Cancel
mIsCancel = true;
}
});
mDownloadDialog = builder.create();
mDownloadDialog.show();
// Download a file
downloadFile();
}
/**
* Download a file
*/
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();
}
// Download a file
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;
// Calculate the current position of the progress bar
mProgress = (int) (((float) count / length) * 100);
// Update progress bar
mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);
// Download complete
if (numread < 0) {
mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
fos.write(buffer, 0, numread);
}
fos.close();
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}