Go to Android asynctask

Source: Internet
Author: User
Android asynctask is more lightweight than handler and is suitable for simple asynchronous processing. Recommendation 3: asynctask Method for asynchronous Task Processing in Android development. Examples of asynctask usage in Android, and use of Android asynctask. First, it is clear that android has handler and asynctask to avoid blocking the main thread (ui thread), and UI Updates can only be completed in the main thread, so asynchronous processing is inevitable. Android 1.5 provides a tool class: asynctask, which makes it easier to create long-running tasks that need to interact with the user interface. It can be implemented without using threads and handler. The advantages of asynctask are as follows: • The thread overhead is high. If a thread is created for each task, the application process is much less efficient;
• Threads cannot be managed. Anonymous threads are not controlled by the program after they are created and started. If many requests are sent, many threads will be started and the system will be overwhelmed.
• As we can see earlier, handler must be introduced to update the UI in the new thread, which makes the Code look very bloated. Asynctask defines three generic types: Params, SS, and result.
• Input parameters for Params startup task execution, such as the URL of the HTTP request.
• Percentage of progress SS background tasks executed.
• Result: The result returned when a task is executed in the background, such as string. Asynctask is executed in four steps. Each step corresponds to a callback method. developers need to implement one or more methods. These methods are automatically called During task execution. Onpreexecute (), this method will be called by the UI thread before the actual background operation is executed. You can make some preparations in this method, such as displaying a progress bar on the interface. Doinbackground (Params...) will be executed immediately after the onpreexecute method is executed. This method runs in the background thread. Here, we will primarily perform those time-consuming background computing tasks. You can call publishprogress to update the real-time task progress. This method is an abstract method and must be implemented by sub-classes. Onprogressupdate (Progress...), after the publishprogress method is called, UI thread will call this method to display the progress of the task on the interface, for example, display through a progress bar. Onpostexecute (result). After doinbackground is executed, the onpostexecute method will be called by the UI thread, and the background computing result will be passed to the UI thread through this method. when using the asynctask class, the following guidelines must be followed: 1) The task instance must be created in the UI thread; 2) the execute method must be called in the UI thread. 3) do not manually call onpreexecute (), onpostexecute (result), doinbackground (Params ...), onprogressupdate (Progress ...) these methods 4) The task can only be executed once. Otherwise, a simple progress bar exception occurs during multiple calls: <? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: Orientation = "vertical" Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent">

<Progressbar Android: Id = "@ + ID/progress_bar"
Android: layout_width = "200dip" Android: layout_height = "10dip"
Android: layout_gravity = "center"
Android: max = "100" style = "? Android: ATTR/progressbarstylehorizontal"
Android: Progress = "0">
</Progressbar>

</Linearlayout> Import Android. App. activity;
Import Android. OS. asynctask;
Import Android. OS. Bundle;
Import Android. widget. progressbar;

Public class double extends activity {

Public progressbar pbar;

@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Pbar = (progressbar) findviewbyid (R. Id. progress_bar );
// Asynctask.exe cute () must be called in the main thread
New asyncloader(cmd.exe cute (void) null );
}

Public void initprogress (){
Pbar. setprogress (0 );
Try {
Thread. Sleep (1000 );
} Catch (interruptedexception e ){
E. printstacktrace ();
}
Pbar. setprogress (50 );
Try {
Thread. Sleep (1000 );
} Catch (interruptedexception e ){
E. printstacktrace ();
}
Pbar. setprogress (100 );
}

// Asynctask
Class asyncloader extends asynctask <void, void, integer> {
@ Override
Protected integer doinbackground (void... Params ){
Initprogress ();
Return NULL;
}
}
} Example of obtaining a webpage: Import java. Io. bytearrayoutputstream;
Import java. Io. inputstream;
Import org. Apache. http. httpentity;
Import org. Apache. http. httpresponse;
Import org. Apache. http. Client. httpclient;
Import org. Apache. http. Client. Methods. httpget;
Import org. Apache. http. impl. Client. defaulthttpclient;
Import Android. OS. asynctask;

// Set three types of parameters: String, integer, and string.
Class pagetask extends asynctask <string, integer, string> {

// Variable length input parameter, which corresponds to asynctask. exucute ()
@ Override
Protected string doinbackground (string... Params ){
Try {
Httpclient client = new defaulthttpclient ();
// Params [0] indicates the URL of the connection.
Httpget = new httpget (Params [0]);
Httpresponse response = client.exe cute (get );
Httpentity entity = response. getentity ();
Long length = entity. getcontentlength ();
Inputstream is = entity. getcontent ();
String S = NULL;
If (is! = NULL ){
Bytearrayoutputstream baos = new bytearrayoutputstream ();
Byte [] Buf = new byte [1, 128];
Int CH =-1;
Int COUNT = 0;
While (CH = is. Read (BUF ))! =-1 ){
Baos. Write (BUF, 0, CH );
Count + = CH;
If (length> 0 ){
// If you know the response length, call publishprogress () to update the progress.
Publishprogress (INT) (count/(float) length) * 100 ));
}
// To clearly view the progress in the simulator, sleep the thread for 100 ms
Thread. Sleep (100 );
}
S = new string (baos. tobytearray ());}
// Return results
Return S;
} Catch (exception e ){
E. printstacktrace ();
}
Return NULL;
}

@ Override
Protected void oncancelled (){
Super. oncancelled ();
}
@ Override
Protected void onpostexecute (string result ){
// Return the HTML page content
Message. settext (result );
}
@ Override
Protected void onpreexecute (){
// Start the task. A dialog box is displayed here, which is simple.
Message. settext (R. String. task_started );
}
@ Override
Protected void onprogressupdate (integer... values ){
// Update Progress
Message. settext (Values [0]);
}
} Reprinted: http://lichen.blog.51cto.com/697816/486868

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.