Android:从AsyncTask获取返回值而不阻塞UI线程

时间:2013-02-27 19:43:35

标签: java android android-asynctask

onCreate的{​​{1}}内,我执行以下操作:

Activity

这有效,但我阻止了使用@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AsyncTask<String, Integer, String[]> asynctask = new DownloadFilesTask(this.getActivity()).execute(url); String[] values = null; try { values = asynctask.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } Log.d("AsyncTask", "DONE!"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values); setListAdapter(adapter); } 的UI线程,这阻止我在执行后台任务期间显示任何新的UI元素,如对话框。

所以我的问题:如何在不阻止给定此代码的UI线程的情况下从AsyncTask获取结果值?

3 个答案:

答案 0 :(得分:5)

将其移至onPostExecute

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
        android.R.layout.simple_list_item_1, values);

setListAdapter(adapter);

答案 1 :(得分:1)

<击>

<击>

get()旨在从onPostExecute(Result result)内部调用。基本上后者是在doInBackground()完成之后在UI线程上执行的,或者抛出异常。

例如:

class DownloadFilesTask extends AsyncTask<Params, Progress, Result>
{
    @Override
    public Result doInBackground(Params... params)
    {
        // ...
    }

    @Override
    public void onPostExecute(Result result)
    {
        try
        {
            Result result = get();

            // we are fine here, do something with the result
        }
        catch(CancellationException e){/* if cancel() is called on this instance */}
        catch(ExecutionException e){/* if doInBackground() throws some exception */}
        catch(InterruptedException e){/* If the current thread was interrupted while waiting */}
    }
}

<击>


编辑:我必须与SwingWorker混淆:\

doInBackground()完成后,在UI线程上执行onPostExecute(Result result),并将结果从doInBackground()传递为方法参数。

class DownloadFilesTask extends AsyncTask<Params, Progress, Result>
{
    @Override
    public Result doInBackground(Params... params)
    {
        // ...
    }

    @Override
    public void onPostExecute(Result result)
    {
        // do something with the result
    }
}

答案 2 :(得分:0)

1-你能发布DownloadFilesTask吗?

2-当asyncTask执行时,它不会被加载或者你正在做什么,这不会马上发生,对吧?所以在你调用asynctask之后你可能无法从中得到结果......所以我建议你使用asyncTask的onPostExecute方法