Asynctask in Android

Source: Internet
Author: User

Android asynctask

InProgramProcessing will inevitably encounter time-consuming operations, such as accessing the network, downloading data, and accessing the database,How can time-consuming operations exist?

The interface display interaction cannot be affected.

In some situations where time consumption can be controlled, we can operate in batches and execute events cyclically. However, in some cases, if the network access is notMethod

The processing process is passive.This type of situation is usually executed in a new thread.

In Android, applications run in the main thread (ui thread) after startup to process interface interaction, control event distribution, and display interface settings;

These elements can only be operated on the UI thread.Therefore, ANR cannot process time-consuming actions in the UI thread, affecting smooth interface operations.

Time-consuming data processing operations must be performed in the background of the new thread. There are many forms of thread-based data processing: service,

Thread + handler, asynctask.Here, let's take a look at the use of asynctask.

Asynctask:

The UI thread is more appropriate and easy to use. The background operations are handed over to the asynctask class, and the operation results are returned to the UI thread.

ControlThread and handler operations. Therefore, it seems that the thread and handler are encapsulated to provide a fixed mode.

Background operations to perform background operations more securely and concisely.

Asynctask usage:

Asynctask is an abstract class.

Public abstract class asynctask <Params, progress, result> {}

Here is an example of subclassing:

 Private   Class Downloadfilestask Extends   Asynctask < URL,Integer,Long > {  Public   Void  Onpreexecute(){  Super . Onpreexecute ();}
Protected LongDoinbackground(URL... URLs ){ Int Count = URLs. length; Long Totalsize = 0 ;
For ( Int I = 0; I <count; I ++ ){
Totalsize + =Downloader. downloadfile (URLs [I]);Publishprogress(( Int ) (I /( Float ) Count) * 100 ));
// Escape early if cancel () is called If (Iscancelled ()) Break ;} Return Totalsize ;} Protected Void Onprogressupdate(Integer... Progress) {setprogresspercent (Progress [ 0 ]);} Protected Void Onpostexecute(LongResult) {showdialog ( "Downloaded" + Result + "bytes" );}}

 

 

Once created, a task is executed very simply:

New downloadfilestask(cmd.exe cute (url1, url2, url3 );

 

Generic Type of asynctask:

• Input parameters when the Params startup task is executed, such as the URL of the HTTP request.

• Progress of background tasks in progress.

• Result: The result returned when a task is executed in the background, such as string.

Of course, the specific functions of each parameter can be defined at will.

 

Asynctask:

    • Onpreexecute(): The task is executed after it is executed. You can make some preparations for the UI thread: the interface is displayed.
    • Doinbackground: After onpreexecute is called and executed, it is called by the background thread. This method runs in the background thread,

The time-consuming operations are all executed here. Use the publishprogress method to pass the execution progress result to the UI thread and call the interface to onprogressupdate.

    • Onprogressupdate: After the publishprogress method is called, the UI thread calls the publishprogress method to pass the background execution progress. You can update the UI display to indicate the background operation progress.
    • Onpostexecute: After the background computing is complete and doinbackground is executed, it is called by the UI thread to pass the results of background execution.

 

Cancel task:

The task can be canceled by using the cancel method. After cancellation, onpostexecute will not be called, but the oncancelled method will be called.

 

Asynctask usage rules:

    1. Asynctask must be loaded in the UI thread;
    2. The asynctask instance must be created in the UI thread;
    3. Execute (Params ...) The method must be called in the UI thread;
    4. Do not call Methods onpreexecute, doinbackground, onprogressupdate, onpostexecute;
    5. The task can only be executed once and then executed abnormally.

 

Related Article

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.