0
這個想法很簡單。創建一個新的TextView,將其附加到ListView,然後開始從服務器下載內容。當沒有內容下載時,ListView即時更新。但在將ListView添加到ListView後,我開始下載,下載完成後,屏幕上的刷新ListView完成。刷新ListView時的Android延遲?
主要功能
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;
}
}
這究竟是爲什麼?
UPDATE
的AsyncTask < ...>。get()方法是UI阻塞和使用的AsyncTask onPostExecute()將做非阻塞的方式工作。示例:android asynctask sending callbacks to ui
但在我的主要功能我首先調用創建視圖,然後異步下載。完成創建視圖後不應該調用異步下載嗎? –
這是無關緊要的,在UI上執行網絡操作線程會減慢它是否先到先得。在你的情況下,它意味着已經創建了ListView,但是你已經阻止了線程到達繪製週期的末端,在那裏它將調用onDraw()來在屏幕上實際呈現列表。你應該做所有的UI東西,然後開始一個異步任務,並等待它在回調中的返回 –
不要忘記,在2.3.3+ Android版本的StrictMode中,你不能在UI線程中使用網絡進程。爲此,總是使用AsyncTask或Thread – CinetiK