Android AsyncTask示例和解释

Sur*_*gch 39 android android-asynctask

我想AsyncTask在我的应用程序中使用一个,但我无法找到一个代码片段,其中简单解释了工作原理.我只想要一些东西来帮助我快速恢复速度,而不必再次浏览文档或大量的问答.

Sur*_*gch 191

AsyncTask是在Android中实现并行性的最简单方法之一,而不必处理像Threads这样的更复杂的方法.虽然它提供了与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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

流程图:

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

AsyncTask流程

其他有用的链接:

  • 可视化到构造函数的数据流将使图像更漂亮! (2认同)