Android: RunOnUiThread vs AsyncTask

前端 未结 5 1055
渐次进展
渐次进展 2020-12-01 00:50

I believe Google suggests developers to use AsyncTask. However, I would like to know how is it different from using \'new Thread\' and then calling \'RunOnUiThread\' in perf

5条回答
  •  猫巷女王i
    2020-12-01 01:31

    These are HUGELY different.

    • First ALL user interaction is done on the main thread as well as all graphics work.
    • Second AsyncTask is designed for short spurts of dedicated activity, such as downloading a file or uploading some data.
    • Third because all UI and user interactions is done in the main thread, if you start pushing stuff to this thread, the device will appear to lag and be less responsive to the user's commands.

    The only reason you want to run something in the UI thread is to interact with widgets. Other than that, if you want to do long processing, use an AsyncTask.

    Edit:

    You could download your data in a separate thread, and I have no issues with that. The problem comes when you want to update the UI. Alone, it is impossible to modify the UI from a child thread. Instead, you will have to create either a handler tied to the UI thread or create a new thread that is destined to run in the UI thread (as in your example). This is not only tedious, but a tragic waste of resources. The AsyncTask takes care of this simply and efficiently.

    To address your last point, you are correct. The AsyncTask does have access to the main thread in pre/postExecute. However, the processing (the primary source of the UI lag) that the task is preforming is not. With the Task, the UI will only be impacted based on what you are drawing, as opposed to having to wait for the Task to finish its job and whatever drawing it wants to do.

提交回复
热议问题