Android AsyncTask 示例及说明

标签 android android-asynctask

我想在我的应用程序中使用 AsyncTask,但我无法找到一个简单解释事情工作原理的代码 fragment 。我只是想要一些东西来帮助我快速恢复速度,而不必涉水the documentation或再次进行大量问答。

最佳答案

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

其他有用的链接:

关于Android AsyncTask 示例及说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25647881/

相关文章:

java - AsyncTask 得到一个错误的字符串参数

java - 当未选择任何内容时,PlacePicker Activity 不会调用 `onActivityResult`

android - 在 ViewModel 类中使用新线程

java - 无法创建和复制文件

android - 动态隐藏 viewPager 选项卡

Android:每个 session 运行一次 asynctask

java - BusProvider 未返回@Subscribe

android - 更新数据库时没有错误或响应

android - 我可以在 dimens.xml 中进行计算吗?

android - 表达式不能是 Kotlin 中的选择器(出现在点之后)