刷新ListView时Android延迟?

时间:2013-01-21 16:20:57

标签: android android-asynctask

这个想法很简单。创建一个新的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&lt; ...&gt; .get()是UI阻止,在AsyncTask中使用onPostExecute()将以非阻塞方式执行。示例:android asynctask sending callbacks to ui

1 个答案:

答案 0 :(得分:1)

您似乎是从UI Thread下载,请查看AsyncTask并尝试实施该功能。见here

当您请求下载时,它会在UI Thread上阻止,直到完成为止。如果您将其放入单独的AsyncTask,那么这会释放您的UI Thread,您可以回调UI Thread以提供结果并更新您的用户界面