Android AsyncTask示例及解释

47

我想在我的应用程序中使用 AsyncTask,但是我很难找到一个简单说明事物如何运作的代码片段。我只想快速地恢复速度而不必再次浏览文档或大量的问答。


3
这个网址(http://developer.android.com/reference/android/os/AsyncTask.html)有什么问题? - Selvin
2
使用AsyncTask。 - codeMagic
2
它的原始形式实际上更好。现在,它看起来对于SO来说太广泛了。感谢您想要分享和帮助。但即使是自我回答的问题也应遵守SO准则。原始的问答很好,只是一个重复问题,这没有什么不对的。请参阅此元帖 - codeMagic
1个回答

226

AsyncTask是在Android中实现并行计算最简单的方法之一,无需处理更复杂的线程等方法。虽然它提供了与UI线程的基本级别的并行处理,但不应用于长时间操作(例如,不超过2秒)。

AsyncTask有四种方法:

  • onPreExecute()
  • doInBackground()
  • onProgressUpdate()
  • onPostExecute()

doInBackground()是最重要的方法,因为它是在后台执行计算的地方。

代码:

这里是一个带有解释的代码概述:

public class AsyncTaskTestActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);  

        // This starts the AsyncTask
        // Doesn't need to be in onCreate()
        new MyTask().execute("my string parameter");
    }

    // Here is the AsyncTask class:
    //
    // AsyncTask<Params, Progress, Result>.
    //    Params – the type (Object/primitive) you pass to the AsyncTask from .execute() 
    //    Progress – the type that gets passed to onProgressUpdate()
    //    Result – the type returns from doInBackground()
    // Any of them can be String, Integer, Void, etc. 

    private class MyTask extends AsyncTask<String, Integer, String> {

        // Runs in UI before background thread is called
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            // Do something like display a progress bar
        }

        // This is run in a background thread
        @Override
        protected String doInBackground(String... params) {
            // get the string from params, which is an array
            String myString = params[0];

            // Do something that takes a long time, for example:
            for (int i = 0; i <= 100; i++) {

                // Do things

                // Call this to update your progress
                publishProgress(i);
            }

            return "this string is passed to onPostExecute";
        }

        // This is called from background thread but runs in UI
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);

            // Do things like update the progress bar
        }

        // This runs in UI when background thread finishes
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            // Do things like hide the progress bar or change a TextView
        }
    }
}

流程图:

这里有一张图表,帮助解释所有参数和类型的去向:

enter image description here

其他有用的链接:


非常酷的人,文档通常是不存在的,我一直在使用它,却不知道为什么要这样做。 - becker
2
将数据流可视化到构造函数中会使图像更加美观! - Mohammed H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接