Introduction to Asynctask_android in Android

Source: Internet
Author: User
Tags function definition

Asynctask is a very common API, especially when processing data asynchronously and applying the data to the view's operational context. In fact, Asynctask is not so good, even some bad. In this article I'll talk about the issues that asynctask can cause, how to fix them, and some alternatives to asynctask.

Asynctask

Starting with the Android API 3 (1.5 cupcake), Asynctask was introduced to help developers manage threads more simply. In fact, there is a similar implementation in Android 1.0 and 1.1, which is usertask. Usertask and Asynctask have the same APIs and implementations, but because of the negligible share of 1.0 and 1.1 devices, the concept here is not about Usertask.

Life cycle

There is one such widespread misconception about asynctask that many people believe that a asynctask in activity will be destroyed as the activity is destroyed. And that's not the case. Asynctask always executes the Doinbackground () method until the method execution is finished. Once the above method is finished, different actions will be performed depending on the situation.

If Cancel (Boolean) is invoked, the oncancelled (result) method is executed

If Cancel (Boolean) is not invoked, the OnPostExecute (result) method is executed
The Asynctask Cancel method requires a Boolean parameter named Mayinterruptifrunning, which means if the execution can be interrupted, if this value is set to True, the task can be interrupted, otherwise The program you are executing will continue to execute until it is completed. If there is a circular operation in the Doinbackground () method, we should use iscancelled () in the loop to determine that if we return to true, we should avoid performing subsequent useless loops.

In short, we use Asynctask to make sure Asynctask is properly canceled.

Comparison of Asynctask and handler

1 The principle of asynctask implementation, and the applicable advantages and disadvantages

Asynctask, a lightweight asynchronous class provided by Android, can directly inherit Asynctask, implement asynchronous operations in a class, and provide the degree to which interface feedback is currently performed asynchronously (UI progress updates can be implemented through the interface), and the final feedback is executed to the UI main thread.

Advantages of Use:

Simple, fast

Process controllable

Disadvantages of using:

it becomes complicated when you use multiple asynchronous operations and need to make UI changes.

2) The principle of handler asynchronous implementation and the advantages and disadvantages of its application

In Handler asynchronous implementation, involving Handler, Looper, Message,thread four objects, asynchronous process is the main thread start thread (child thread) àthread (child thread) Run and generate Message-àlooper get the message and pass it to Handleràhandler to get the messages in Looper and make UI changes.

Advantages of Use:

Clear structure and clear function definition

For multiple background tasks, simple, clear

Disadvantages of using:

In a single background asynchronous processing, it appears too much code, too complex (relativity)

Asynctask Introduction

Android's asynctask is lighter than handler and is suitable for simple asynchronous processing.

First of all, the reason Android has handler and Asynctask is to not block the main thread (UI thread), and the UI updates can only be done in the main thread, so asynchronous processing is unavoidable.

Android provides asynctask to reduce the difficulty of this development. Asynctask is a encapsulated background task class, as the name implies is asynchronous task.

Asynctask directly inherits from the object class, and the position is android.os.AsyncTask. To work with Asynctask we provide three generic parameters and overload several methods (at least one at a load).

Asynctask defines three generic types of params,progress and result.

params the input parameters that start the task execution, such as the URL of the HTTP request.

progress the percentage of background task execution.

result the result of the final return of a task, such as String.

The students who have used Asynctask know that an asynchronous load of data must at least override the following two methods:

Doinbackground (Params ...) in the background, more time-consuming operations can be placed here. Note that the UI cannot be directly manipulated here. This method is performed in the background thread, and it usually takes a long time to complete the task. Publicprogress can be invoked during execution (Progress ...) To update the progress of the task.

OnPostExecute (Result) corresponds to the way handler handles the UI, where you can use the results obtained in Doinbackground to manipulate the UI. This method executes on the main thread, and the result of the task execution is returned as a parameter of this method

If necessary, you will have to rewrite these three methods, but not necessarily:

onprogressupdate (Progress ...) can use the progress bar to increase the user experience degree. This method executes on the main thread to show the progress of the task execution.

OnPreExecute () This is the interface that the end user calls Excute, and this method is called before the task executes, and the progress dialog box can be displayed here.

oncancelled () The action to be done when the user calls Cancel

Using the Asynctask class, here are a few guidelines to follow:

Instances of task must be created in UI thread;

The Execute method must be invoked in UI thread;

• Do not manually invoke OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods;

• This task can only be executed once, otherwise there will be an exception on multiple calls;

An example of a super simple understanding of Asynctask:

Main.xml

<?xml version= "." Encoding= "utf-"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/res/ Android " 
android:orientation=" vertical " 
android:layout_width=" fill_parent " 
android:layout_height=" Fill_parent " 
> 
<textview 
android:id=" @+id/textview " 
android:layout_width=" Fill_parent " 
android:layout_height= "wrap_content" 
/> 
<progressbar 
android:id= "@+id/progressbar" 
android:layout_width= "fill_parent" 
android:layout_height= "wrap_content" 
style= "? android:attr/ Progressbarstylehorizontal " 
/> 
<button 
android:id=" @+id/button "Android:layout_width" 
= "Fill_parent" 
android:layout_height= "wrap_content" 
android:text= "update ProgressBar" 
/> 

Mainactivity.java

Package vic.wong.main; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.Button; 
Import Android.widget.ProgressBar; 
Import Android.widget.TextView; 
public class Mainactivity extends activity { 
Private button button; 
Private ProgressBar ProgressBar; 
Private TextView TextView; 
@Override public 
void OnCreate (Bundle savedinstancestate) { 
super.oncreate (savedinstancestate); 
Setcontentview (r.layout.main); 
Button = (button) Findviewbyid (R.id.button); 
ProgressBar = (ProgressBar) Findviewbyid (R.id.progressbar); 
TextView = (TextView) Findviewbyid (R.id.textview); 
Button.setonclicklistener (New Onclicklistener () { 
@Override public 
void OnClick (View v) { 
Progressbarasynctask asynctask = new Progressbarasynctask (TextView, ProgressBar); 
Asynctask.execute ();}} 
); 
} 

Netoperator.java

Package vic.wong.main; 
Analog network Environment Public 
class Netoperator {public 
void operator () { 
try { 
//Hibernate seconds 
thread.sleep (); 
} catch (Interruptedexception e) { 
//TODO auto-generated catch block 
e.printstacktrace (); 
} 
} 

Progressbarasynctask. java

Package vic.wong.main; 
Import Android.os.AsyncTask; 
Import Android.widget.ProgressBar; 
Import Android.widget.TextView; /** * Generates the object of the class, and after invoking the Execute method * First executes the Onproexecute method * Next executes the Doinbackgroup method */public class Progressbarasynctask Ext 
Ends Asynctask<integer, Integer, string> {private TextView TextView; 
Private ProgressBar ProgressBar; 
Public Progressbarasynctask (TextView TextView, ProgressBar ProgressBar) {super (); 
This.textview = TextView; 
This.progressbar = ProgressBar; /** * Here the integer parameter corresponds to the first parameter in the Asynctask * Here's the string return value corresponding to the third parameter of the Asynctask * The method is not running in the UI thread, primarily for asynchronous operations, all of which cannot be set on the UI in this method Set and modify * but you can invoke the Publishprogress method to trigger Onprogressupdate to manipulate the UI/@Override protected String doinbackground (Integer ... params 
) {Netoperator netoperator = new Netoperator (); 
int i =; 
for (i =; I <=; i+=) {netoperator.operator (); 
Publishprogress (i); 
return i + params[].intvalue () + ""; /** * The string parameter here corresponds to the third parameter in the Asynctask (that is, the return value of the receive Doinbackground) * in DoinbacThe Kground method runs after the execution and runs in the UI thread to set the UI space */@Override protected void OnPostExecute (String result) {Textview.settext 
("Execution end of asynchronous operation" + result); 
The method runs in the UI thread and is run in the UI thread to set the UI space @Override protected void OnPreExecute () {Textview.settext ("Start asynchronous Thread"); /** * Here the Intege parameter corresponds to the second parameter in the Asynctask * in the Doinbackground method, each call to the Publishprogress method triggers the onprogressupdate execution * onprogress 
Update is performed in the UI thread, all can operate on the UI space * * @Override protected void onprogressupdate (Integer ... values) {int vlaue = values[]; 
Progressbar.setprogress (Vlaue); } 
}

About Android Asynctask to introduce you here, I hope to help you!

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.