Android development tool Class 15_ Myasynctask

Source: Internet
Author: User

Asynctask is a good solution for background operations that have a short life cycle and need to show progress and results on the UI. However, when activity restarts, this operation will not persist, that is, the Asynctask will be canceled when the device's direction changes, causing activity to be destroyed and recreated. For background operations with long lifecycles, such as downloading data from the Internet, using service components is a better choice.

1 Private classMyasynctaskextendsAsynctask<string, Integer, string> {2 @Override3     protectedstring Doinbackground (String ... parameter) {4       //Moved to a background thread.5String result = "";6       intmyprogress = 0;7       8       intInputlength = parameter[0].length ();9 Ten       //Perform Background Processing task, update myprogress] One        for(inti = 1; I <= inputlength; i++) { AMyprogress =i; -result = result + Parameter[0].charat (inputlength-i); -         Try { theThread.Sleep (100); -}Catch(Interruptedexception e) {} - publishprogress (myprogress); -       } +  -       //Return The value to being passed to OnPostExecute +       returnresult; A     } at  - @Override -     protected voidOnprogressupdate (Integer ... progress) { -       //Synchronized to UI thread. -       //Update progress bar, Notification, or other UI elements -Asyncprogress.setprogress (progress[0]); in     } -  to @Override +     protected voidOnPostExecute (String result) { -       //Synchronized to UI thread. the       //Report results via UI Update, Dialog, or notifications * Asynctextview.settext (result); $     }Panax Notoginseng   } -   

Executes an asynchronous task. Each Asynctask instance can be executed only once. If you try to invoke execute for the second time, an exception is thrown.

1 Private void Executeasync () {2     /** 3      * Listing 9-12:executing an asynchronous task4      */ 5     String input = "Redrum ... redrum"; 6     New  7   }

Android development tool Class 15_ Myasynctask

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.