Android AsyncTask的例子和解释

我想在我的应用程序中使用一个AsyncTask ,但是我无法find一个简单的解释代码片断如何工作的代码片段。 我只是想要一些东西来帮助我快速恢复速度,而不必再次通过文档或大量问答。

Solutions Collecting From Web of "Android AsyncTask的例子和解释"

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


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




 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 paramater"); } // 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 } } } 





  • 什么参数传入AsyncTask <arg1,arg2,arg3>?
  • Slidenerd Android AsyncTask教程:初学者的Android教程
  • Android:为什么,何时以及如何使用AsyncTask来举例
  • 了解AsyncTask – 一劳永逸
  • 处理AsyncTask和屏幕方向
  • 如何将多个parameter passing给AsynkTask
  • 如何将两种不同的数据types传递给AsyncTask,Android