拿到url后实现下载
先基于下载编写一个service类
public class DownloadOfflineGdService extends Service {
private final HashMap<String, DownloadTask> activeDownloads = new HashMap<>();
private final ExecutorService executor = Executors.newFixedThreadPool(5);
private MutableLiveData<DownloadProgress> downloadProgressLiveData = new MutableLiveData<>();
public LiveData<DownloadProgress> getDownloadProgressLiveData() {
return downloadProgressLiveData;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
String taskId = intent.getStringExtra("taskId");
List<String> urls = new ArrayList<>();
for (OffLineGaoDeMapApplyListResponseBean bean : AppAplication.getInstance().getBeans()) {
if (taskId.equals(bean.getCreateUserName())) {
urls = bean.getUrls();
}
}
if ("com.axnx.ddsn.tool.DOWNLOAD_ACTION".equals(action)) {
enqueueDownload(taskId, urls);
}
}
return START_STICKY;
}
public void enqueueDownload(String taskId, List<String> url) {
if (activeDownloads.containsKey(taskId)) {
return;
}
DownloadTask downloadTask = new DownloadTask(taskId, url);
activeDownloads.put(taskId, downloadTask);
executor.execute(downloadTask);
}
private class DownloadTask implements Runnable {
private final String taskId;
private final List<String> url;
private final int totalFiles; // 总文件数
private int downloadedFiles; // 已下载文件数
public DownloadTask(String taskId, List<String> url) {
this.taskId = taskId;
this.url = url;
this.totalFiles = url.size();
this.downloadedFiles = 0;
}
@Override
public void run() {
for (String s : url) {
Map<String, String> params = parseUrlParameters(s);
String x = params.get("x");
String y = params.get("y");
String z = params.get("z");
String style = params.get("style");
String filePath = getOffLineMapPath() + "/" + taskId + "/" + z + "/" + x;
String fileName = y + style + ".tile";
//下载
File directory = new File(filePath);
if (!directory.exists()) {
directory.mkdirs();
}
// 下载文件
try {
downloadFile(s, new File(directory, fileName));
downloadedFiles++;
DownloadProgress progress = new DownloadProgress(taskId, downloadedFiles, totalFiles);
downloadProgressLiveData.postValue(progress);
//更新进度
if (downloadedFiles == totalFiles) {
activeDownloads.remove(taskId);
}
} catch (IOException e) {
Log.e("szf", "Error downloading file: ", e);
}
}
}
}
public class LocalBinder extends Binder {
public DownloadOfflineGdService getService() {
return DownloadOfflineGdService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new LocalBinder();
}
public static String getOffLineMapPath() {
String str = getPackagePath();
if (TextUtils.isEmpty(str)) {
return str;
}
return str + File.separator + "GaoDeOffLineMap";
}
public static Map<String, String> parseUrlParameters(String url) {
Map<String, String> parameters = new HashMap<>();
String[] parts = url.split("\\?");
if (parts.length > 1) {
String query = parts[1];
for (String param : query.split("&")) {
String[] keyValue = param.split("=");
if (keyValue.length == 2) {
parameters.put(keyValue[0], keyValue[1]);
}
}
}
return parameters;
}
private static final OkHttpClient httpClient = new OkHttpClient();
private static void downloadFile(String urlString, File outputFile) throws IOException {
Request request = new Request.Builder()
.url(urlString)
.build();
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
fos.write(response.body().bytes());
}
}
static class DownloadProgress {
private final String taskId;
private final int current;
private final int total;
public DownloadProgress(String taskId, int current, int total) {
this.taskId = taskId;
this.current = current;
this.total = total;
}
// 提供getters方法
public String getTaskId() {
return taskId;
}
public int getCurrent() {
return current;
}
public int getTotal() {
return total;
}
}
}
在地块勾画成功后 启动该服务
private void startDownloadTasks(String taskId) {
Intent intent = new Intent(getActivity(), DownloadOfflineGdService.class);
intent.setAction("com.axnx.ddsn.tool.DOWNLOAD_ACTION");
intent.putExtra("taskId", taskId);
getActivity().startService(intent);
}
在该页面绑定服务进行数据的下载进度更新
@Override
public void onStart() {
super.onStart();
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
DownloadOfflineGdService.LocalBinder iBinder1 = (DownloadOfflineGdService.LocalBinder) iBinder;
downloadService = iBinder1.getService();
downloadService.getDownloadProgressLiveData().observe(getViewLifecycleOwner(), progressObserver);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
downloadService = null;
}
};
Intent intent = new Intent(getActivity(), DownloadOfflineGdService.class);
getActivity().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
int status = 0;
private final Observer<DownloadOfflineGdService.DownloadProgress> progressObserver = new Observer<DownloadOfflineGdService.DownloadProgress>() {
@Override
public void onChanged(DownloadOfflineGdService.DownloadProgress downloadProgress) {
status = downloadProgress.getCurrent() == downloadProgress.getTotal()?3:2;
adapter.setNewInstance(AppAplication.getInstance().updateBeans(downloadProgress.getTaskId(), downloadProgress.getCurrent(), status));
adapter.notifyDataSetChanged();
if (status == 3) {
EventBus.getDefault().post(new UrlsEvents(3));
}
}
};
@Override
public void onStop() {
super.onStop();
if (serviceConnection != null) {
getActivity().unbindService(serviceConnection);
serviceConnection = null;
}
}