我使用AsyncTask将一些文件下载到我的应用程序,当我刷新它们时我希望可用文件的列表自行更新。从我在线阅读的部分下载部分将在“doInBackground”方法中完成,之后为了更新视图,我使用了“onPostExecute”方法。当我这样做时,视图不会自行更新,我必须更改活动,然后返回以更新它,这是我用来更新视图的方法,但似乎它在所有文件已完成下载,因此它们不会显示可用文件。Android异步任务方法执行顺序
请纠正我,如果我错了,但不是在doInBackground完全完成后调用onPostExecute?如果没有,我可以做些什么,以便在文件完成下载之前不会调用onPostExecute?
谢谢!
这里是我使用的代码:
private class Documents_Task extends AsyncTask<String, String, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... params) {
try {
// Downloading the documents and savign them
return true;
} catch (Exception e) {
return false;
}
}
@Override
protected void onPostExecute(Boolean success) {
if (success) {
// Displaying the list of available files
}
}
}
编辑:He're用于下载和保存文件
String result = HttpManager.getData(params[0]);
// Getting the names of the files I already have on my mobile
File folder = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/EHTProfs/Documents"));
File[] listOfFiles = folder.listFiles();
//String array, each element will correspond to a name of a file on my mobile
String[] names = new String[listOfFiles.length];
//Filling my array
if (listOfFiles.length > 0)
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile())
names[i] = listOfFiles[i].getName();
}
Context c = Documents.this;
// Taking null out of the string result containing the names of the files on my server
String sub_result = result.substring(1, result.length() - 6);
// Comparing each file name on the server with those on my mobile,
// if it exists do nothing, if not download it
StringTokenizer st = new StringTokenizer(sub_result, "\",\"");
Boolean exists;
while (st.hasMoreTokens()) {
exists = false;
String fileName = st.nextToken();
if (names.length > 0)
for (int i = 0; i < names.length; i++) {
if (names[i].equals(fileName)) {
i = names.length;
exists = true;
}
}
if (!exists) {
downloadDocument(fileName);
}
}
的代码下面是下载一个文件
方法public void downloadDocument(String fileName) {
DownloadManager mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse("http://" + IP_ADDRESS_PORT + "/EhtprofsWEB/ehtprofs/document/" + fileName);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri)
.setAllowedOverRoaming(false)
.setTitle(fileName)
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS + "/EHTProfs/Documents", fileName);
mManager.enqueue(request);
}
您可能需要做出详细的下载/保存代码。 – headuck
@headuck我添加了代码 –