"Turn" Pro Android Learning Note (74): HTTP Service (8): Use background thread asynctask

Source: Internet
Author: User

Directory (?) [-]

    1. 5-Second Timeout exception
    2. Asynctask
      1. Implementing Asynctask Abstract Classes
      2. A call to Asynctask
      3. Where to run
      4. Other important method

The article reproduced only for non-commercial nature, and can not be accompanied by virtual currency, points, registration and other conditions, reprint must indicate the source: http://blog.csdn.net/flowingflying/

Before, we directly in the activity to perform HTTP communication, in the process of communication may occur during connection timeout, socket timeout, etc., the timeout threshold is usually the second level, for example, set in Androidhttpclient 20 seconds, if a timeout occurs, it will be stopped in execute ( ) statement, the exception is given by waiting for 20 seconds and still no response. The entire activity UI freezes within 20 seconds, so the user experience is obviously unacceptable, so HTTP should be placed in a background thread. Background thread processing can refer to Android Learning Note (31): Threads: Message and runnable and Android learning Note (32): Threads: Background asynchronous task Asynctask. This time we will focus on how to implement HTTP communication in Asynctask, about Asynctask, and will be discussed in detail in the future.

5-Second Timeout exception

In the previous example, we used HTTP communication in OnCreate (), and if a connection timeout occurred, it would wait until the exception occurred, but what if we had the UI to interact with the user after OnStart ()?

We have changed the previous small example by pressing the button to trigger the HTTP traffic and connecting an empty IP address to test it. In the process of waiting for a connection, if the user has a UI action (such as pressing the back key or the menu key), the Android UI is processed in and only in the main thread (also a UI thread), and the system cannot respond to user UI actions for 5 seconds. The ANR (application not responsing) is processed, and the frame lets the user choose whether to force activity off.

Asynctask

If the background thread needs to update the UI, consider using Asynctask, which can provide callback to the main thread, which is handy for UI processing. Callback can start, middle, and end in a background thread.

The small example has an activity and a asynctask class consisting of a user pressing the activity button to trigger Asynctask in a background thread to download a large picture from the Internet. Asynctask in the download start, middle, and end background threads can interact with the main thread, displaying progress information and captured pictures in activity. (This fish is 1.27 years ago and colleagues in the outside dozen slain, 4.5 catty of grass carp fish, a fish a meal.) Hotel no one, said finish today on holiday, rare quiet, haha. )

Implementing Asynctask Abstract Classes

Asynctask is an abstract class that needs to be implemented specifically, the parameters of this class are special, that is, the type of the parameter can be set by itself. In several methods the parameter has "...", which means that the number of arguments is not fixed, for example (String ... arg), which can be ("Hello") or ("Hello", "World"), or three parameters, four parameters, respectively, with arg[0],arg[1], ... To express.

The asynctask is well suited to the process of performing a scenario where the intermediate and final results need to be returned to the user in the context of UI rendering.

The parameters of the class are three, in this case, <String,Integer,Bitmap>.

    1. The first represents a parameter that is passed by a background thread, in this case the Doinbackground (string ... arg) parameter type is String, which is used to pass the web address;
    2. The second argument is that during a background thread run, some intermediate values need to be returned to the main thread so that the intermediate values can be rendered in the interface, and the second parameter is the type of the intermediate value, in this case onprogressupdate (Interger ...).
    3. The third parameter is the data type that is returned to the final result of the main thread after the background thread finishes running, in this case the return value of bitmap doinbackground (String arg) bitmap.

/** Asynctask is an abstract class that needs to be implemented specifically. */
public class Downloadimagetaskextends Asynctask<string, integer,bitmap>{
//"Step 0" Asynctask is appropriate for feedback in the UI, so the handle to the corresponding activity to be obtained by the constructor
Private Context mcontext = null; Context is the activity through which you can manipulate the view in the activity in Asynctask
Public Downloadimagetask (context context){
Mcontext = context;
}

//Step 4: After the background thread finishes executing, bring the result to the Onpostexcute () of the main thread and process the results from the background running on the UI
protected voidOnPostExecute(Bitmap result) {
LOG.V ("Downloadimagetask", "OnPostExecute () is called, run in" + Thread.CurrentThread (). GetName ());
if (result! = null) {
ImageView image = (ImageView) (Activity) mcontext). Findviewbyid (R.id.image);
Image.setimagebitmap (result);
}else{
TextView Errortv = (TextView) (Activity) mcontext). Findviewbyid (R.ID.ERROR_MSG);
Errortv.settext ("Error:can ' t get image!");
}
}

//Step 1:override OnPreExecute (), the work required to process setup in. Note that this is run in the main thread.
protected void OnPreExecute () {
LOG.V ("Downloadimagetask", "OnPreExecute () is called, run in" + Thread.CurrentThread (). GetName ());
}

//Step 3: Run code library in a background thread publicprogress () triggers the UI thread's onprogressupdate () to feed the information back to the UI.
protected voidonprogressupdate(Integer ... values) {
LOG.V ("Downloadimagetask", "onprogressupdate (" + values[0] + ") is called, run in" + Thread.CurrentThread (). GetName ());
TextView TV = (TextView) (Activity) mcontext). Findviewbyid (R.id.text);
Tv.settext ("Progress so far:" + values[0]);
}

//Step 2:overrideDoinbackground (), after the initialization is done, the thread is created and the Code in Doinbackground () is run in the thread, and the relevant code for threading establishment and operation is encapsulated and the developer does not need to process it. If the thread is running, we need some feedback to the UI, because it is not able to manipulate the UI of the main thread in the thread, through Publishprogress (), it will trigger to run in the main thread Onprogressupdate () for UI manipulation.
Protected Bitmap doinbackground (String ... arg0) {
LOG.V ("Downloadimagetask", "Doinbackground () is called, run in" + Thread.CurrentThread (). GetName ());
Return Downloadimage (arg0);
}

Private Bitmap downloadimage (String ... urls) {
HttpClient HttpClient = Customhttpclient.getcustomhttpclient ();
try{
HttpGet request = new HttpGet (urls[0]);
Httpparams params = new Basichttpparams ();
Httpconnectionparams.setconnectiontimeout (params, 60000);
Request.setparams (params);
publishprogress (25);

HttpResponse response = Httpclient.execute (request);
publishprogress (50);

...//here should be Resposne code judgment, small example of the goal is to examine Asynctask, basics, skip this Part

byte[] image = Entityutils.tobytearray (response.getentity ());
publishprogress ();

Bitmap Mbitmap = Bitmapfactory.decodebytearray (image, 0, image.length);
publishprogress (+);
return mbitmap;
}catch (Exception e) {
E.printstacktrace ();
}
return null;
}
}

A call to Asynctask

The activity code for the small example is as follows:

public class Downloadimageactivity extends activity{
private downloadimagetask download = null;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.layout_image);
}
//Trigger download image, avoid duplicate background thread creation through status monitoring. Also, it is important to note that Asynctask is executed once, that is, an object can only run the Execute () method once, otherwise it throws an exception. In this case, we can download the picture again, at which point we need to create a new object.
public void Onclickedaction (View v) {
if (download! = null) {
//Can obtain the operation of Asynctask, including running, PENDING, finished
asynctask.status Status = Download.getstatus ();
LOG.V ("Downloadimageactivity", "status is" + status);
if (Status! =AsyncTask.Status.FINISHED){
LOG.V ("Downloadimageactivity", "It is doing, not need to start again");
Return
}
}
ImageView image = (ImageView) Findviewbyid (r.id.image);
Image.setimagebitmap (NULL);
Create an instance of Asynctask and execute execute ().
download = new Downloadimagetask (this);
Download.execute
("Http://ww1.sinaimg.cn/large/5cf79a90jw1ecy18vfwlrj20xc18gtgd.jpg");
}
}

Where to run

We use Logcat to see which thread the code is running on.

Other important method

In some cases, we may need to terminate the run in the background so that we can call Cancel (), such as Task.cancel (true), and we can use task.iscanceled () To inquire whether the drug enterprise background thread Asyntask stopped, avoid repeated stop. Executing cancel () will trigger the oncanceled () in Aysntask, where we can set certain States, such as bool Iscancel=true, in Doinbackground () running in the background, Detects the status bit to determine whether to continue running.

In the above example, after the background thread runs, it is normal to return the result to the UI thread by Onpostexcute (). Asyntask also provides a get (), the way to actively obtain results. Let's change the small example:

public void Onclickedaction (View v) {
......
Checkdownload ();
}

This is the test main thread active query result
private void Checkdownload () {
try{
Bitmap bp = download.get ();//The main thread will be here to proactively get the results of running the background thread and wait until there is a result. So if the background thread has onprogressupdate () handling the UI at this point, the processing will be blocked until download () waits until the result, the blocking UI processing will be executed, including the last Onpostexcute (), so if a get () is not normally performed in the Onpostexcute () UI operation.
ImageView image = (ImageView) Findviewbyid (r.id.image);
Image.setimagebitmap (BP);
}catch (Exception e) {
E.printstacktrace ();
}
}

To avoid waiting too long in Get (), you can set the timeout as follows:

Bitmap bp = download.get (2000,timeunit.milliseconds);

The above example is that if the result is still not reached within 2 seconds, the java.uril.concurrent.TimeoutException exception will be thrown, and in exception handling, we may actively cancel the background thread.

The example code covered in this blog post can be downloaded in the Pro Android Learning: Http Service Small example.

RELATED Links: My Android development related articles

"Turn" Pro Android Learning Note (74): HTTP Service (8): Use background thread asynctask

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.