Asynctask in Android

Source: Internet
Author: User

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.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.