在Android中下载文件的进度条可以通过使用AsyncTask或者OkHttp库来实现。以下是一个示例代码:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private ProgressDialog progressDialog;
public DownloadTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Downloading file...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
String fileUrl = params[0];
String fileName = params[1];
String filePath = Environment.getExternalStorageDirectory().getPath() + "/" + fileName;
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
FileOutputStream output = new FileOutputStream(filePath);
byte[] data = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("DownloadTask", "Error: " + e.getMessage());
}
return filePath;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(String filePath) {
super.onPostExecute(filePath);
progressDialog.dismiss();
// 下载完成后的操作,例如打开文件等
}
}
使用方法:
DownloadTask downloadTask = new DownloadTask(context);
downloadTask.execute(fileUrl, fileName);
首先,添加OkHttp库的依赖到你的项目中。
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
然后,使用以下代码实现下载文件的进度条:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class DownloadManager {
private Context context;
private ProgressDialog progressDialog;
public DownloadManager(Context context) {
this.context = context;
}
public void downloadFile(String fileUrl, String fileName) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Downloading file...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.show();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(fileUrl)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("DownloadManager", "Error: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
InputStream input = response.body().byteStream();
long fileLength = response.body().contentLength();
File outputFile = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream output = new FileOutputStream(outputFile);
byte[] data = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
});
}
private void publishProgress(int progress) {
progressDialog.setProgress(progress);
}
}
使用方法:
DownloadManager downloadManager = new DownloadManager(context);
downloadManager.downloadFile(fileUrl, fileName);
以上是在Android中实现下载文件的进度条的示例代码。在实际使用中,你需要根据自己的需求进行适当的修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云