Downloading pictures in the background, updating the UI after the download is complete is a common requirement. In the absence of the Asynctask class, we need to write a lot of thread and handler code to implement this function, with asynctask, everything becomes simple. The following excerpt Google official introduction:
Asynctask is designed-a helper class around and Thread and Handler does not constitute a generic threading framework. A Synctasks should ideally is used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it's highly recommended you use the various APIs provided B Y java.util.concurrent the pacakge such Executor as, and ThreadPoolExecutor FutureTask .
It can be seen that Asynctask does not introduce the underlying thread technology, only the use of thread and handler. And the use of occasions are limited, up to a few seconds running in the background, too long run should not be used (what will be the problem?). )。
Using Asynctask, you must create a subclass that specifies methods for replication. Among them, Doinbackground and OnPostExecute are the 2 main methods. Doinbackground is executed in the sub-thread, it should write a time-consuming method, OnPostExecute is called in the main thread after the Doinbackground is completed. Doinbackground,onpostexecute, respectively, in the sub-thread and the main thread call, is the Asynctask feature.
There is a few threading rules that must being followed for this class to work properly:
- the Asynctask class must is loaded on the UI thread. This was done automatically as of
Jelly_bean . The
- the task instance must is created on the UI thread.
-
Execute (Params ...) must is invoked on the UI thread.
- do not call
OnPreExecute () , onpostexecute (Result) , Doinbackground (Params ...) , onprogressupdate (Progress ...) manually.
- The task can be executed only once (an exception would be thrown if a second execution is attempted.)