这个想法很简单。创建一个新的 TextView,将其附加到 ListView,然后开始从服务器下载内容。当没有内容下载时,ListView 会立即更新。但是将 TextView 添加到我开始下载的 ListView 后,下载完成后刷新屏幕上的 listView 完成。
主功能
TextView startingDownloadingText = createTextView("Downloading started");
linearLayout.addView(startingDownloadingText);
boolean success = downloadFromUrl(stringUri, fileName, context);
if (success) {......
下载功能
public boolean downloadFromUrl(String stringURL, String fileName, Context myContext) {
try {
URL url = new URL(stringURL);
Resources res = myContext.getResources();
String envDirectory = Environment.getExternalStorageDirectory().toString();
String zipDirectory = envDirectory.concat(res.getString(R.string.zipDirectory));
File fileDirectory = new File(zipDirectory);
fileDirectory.mkdirs();
ZipDownloader zipDownloader = new ZipDownloader(zipDirectory, fileName);
AsyncTask<URL, Void, Boolean> asynZipDownloader = zipDownloader.execute(url);
Boolean success = null;
try {
success = asynZipDownloader.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (success){
Log.d("DownloadFromUrl", "file ready");
return true;
}
return false;
} catch (IOException e) {
Log.e("DownloadFromUrl", "Error: " + e);
return false;
}
}
为什么会这样?
更新
AsyncTask<...>.get() 是 UI 阻塞,在 AsyncTask 中使用 onPostExecute() 将以非阻塞方式完成工作。示例:android asynctask 向 ui 发送回调