我使用 DownloadManager 从 URL 下载 xml 文件。然后我使用线程等待 2 秒以完成将文件保存到 sd 卡。
我想要一个活动圈,如图所示。实现这一点的最简单方法是什么?我需要实施一个AsyncTask
吗?
我要下载并等待的代码:
//Download XML file from URL
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setTitle("Download von "+Name+".xml");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(FileSeperator+"XML"+FileSeperator, Name + FileExtension);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
File file = new File(Environment.getExternalStorageDirectory()+ FileSeperator
+"XML"+FileSeperator+ Name + FileExtension);
System.out.println("File existiert "+file.exists());
//insert delay after download to finish save progress before starting to parse the xml
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
更新 这是我实现的 AsyncTask
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
//Download XML file from URL
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setTitle("Download von "+Name+".xml");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(FileSeperator+"XML"+FileSeperator, Name + FileExtension);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
File file = new File(Environment.getExternalStorageDirectory()+ FileSeperator
+"XML"+FileSeperator+ Name + FileExtension);
System.out.println("File existiert "+file.exists());
//insert delay after download to finish save progress before starting to parse the xml
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (Exception e) {
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
protected void onPostExecute() {
super.onPreExecute();
pDialog.dismiss();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
}
我这样称呼它:
// instantiate it within the onCreate method
pDialog = new ProgressDialog(CreateProject.this);
pDialog.setMessage("Lädt...");
pDialog.setIndeterminate(true);
// execute this when the downloader must be fired
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute();