在Android中同时下载多个文件可以通过多线程的方式实现。以下是一个实现该功能的示例代码:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String FILE_URL1 = "https://example.com/file1.txt";
private static final String FILE_URL2 = "https://example.com/file2.txt";
private static final String FILE_URL3 = "https://example.com/file3.txt";
private Button downloadButton;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadButton = findViewById(R.id.download_button);
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
downloadFiles();
}
});
}
private void downloadFiles() {
List<String> fileUrls = new ArrayList<>();
fileUrls.add(FILE_URL1);
fileUrls.add(FILE_URL2);
fileUrls.add(FILE_URL3);
DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(fileUrls);
}
private class DownloadTask extends AsyncTask<List<String>, Integer, Boolean> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Downloading files...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected Boolean doInBackground(List<String>... params) {
List<String> fileUrls = params[0];
int count = fileUrls.size();
int progress = 0;
try {
for (String fileUrl : fileUrls) {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
File directory = new File(Environment.getExternalStorageDirectory().getPath() + "/Download");
if (!directory.exists()) {
directory.mkdirs();
}
File outputFile = new File(directory, fileUrl.substring(fileUrl.lastIndexOf("/") + 1));
FileOutputStream outputStream = new FileOutputStream(outputFile);
InputStream inputStream = new BufferedInputStream(url.openStream());
byte[] data = new byte[1024];
int total = 0;
int count;
while ((count = inputStream.read(data)) != -1) {
total += count;
outputStream.write(data, 0, count);
int progressPercentage = (int) ((total * 100) / fileLength);
publishProgress(progressPercentage);
}
outputStream.flush();
outputStream.close();
inputStream.close();
progress++;
}
} catch (Exception e) {
Log.e(TAG, "Error downloading files: " + e.getMessage());
return false;
}
return true;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressDialog.dismiss();
if (result) {
// All files downloaded successfully
// TODO: Add your code here
} else {
// Error occurred while downloading files
// TODO: Add your code here
}
}
}
}
上述代码中,我们首先定义了要下载的文件的URL列表,然后在downloadFiles()
方法中创建并执行一个DownloadTask
异步任务。DownloadTask
类继承自AsyncTask
,在doInBackground()
方法中,我们使用多线程的方式同时下载多个文件。每个文件的下载进度通过publishProgress()
方法发布,然后在onProgressUpdate()
方法中更新进度条。下载完成后,通过onPostExecute()
方法进行相应的处理。
请注意,上述代码仅为示例,实际使用时需要根据具体需求进行适当的修改和优化。
推荐的腾讯云相关产品:腾讯云对象存储(COS),提供高可靠、低成本的云端存储服务,适用于存储和处理大规模非结构化数据,支持多种数据访问方式。产品介绍链接地址:https://cloud.tencent.com/product/cos
领取专属 10元无门槛券
手把手带您无忧上云