Android Notes (13) Asynctask

Source: Internet
Author: User

The primary role of asynchronous tasks is to handle time-consuming operations and to bring a good user experience to the user. Now let's create a new asynchronous task to complete the task of downloading the picture.

First, set up the layout, by clicking the button to perform the asynchronous task.

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Android:layout_width="Match_parent"android:layout_height="Match_parent"  Android:orientation="vertical" >                <button  android:id  = "@+id/button"  android:layout_width  =         "match_parent"  android:layout_height  = "wrap_content"  android:text  = "download picture" />     <ImageViewandroid:id= "@+id/image"android:layout_width="Match_ Parent "android:layout_height="wrap_content "android:src="@drawable/ic_ Launcher " />                                </linearlayout>

Second, Asynctask
Asynctask is an abstract class, so if we want to use it, we'll have to create a subclass to inherit it. In inheritance we can specify three generic parameters for the Asynctask class, and these three parameters are used as follows.
1. Params
Parameters that need to be passed in when executing asynctask can be used in a background task.
2. Progress
When a background task executes, the generic type specified here is used as the progress unit if you need to display the current progress on the interface.
3. Result
When the task finishes executing, if the result needs to be returned, the generic type specified here is used as the return value type.

We also need to rewrite several methods in Asynctask to complete the customization of the task. There are four ways to rewrite frequently.
1. OnPreExecute ()
This method is called before the background task begins execution, and is used for initialization of some interfaces, such as displaying a progress bar dialog box.
2. Doinbackground (Params ...)
All the code in this method will run in a sub-thread, and we should be here to handle all the time-consuming tasks. Once the task has been completed, it can return the result of the task using the return statement. Note that the UI action is not allowed in this method, and if you need to update the UI elements, such as feedback on the progress of the current task, you can call Publishprogress (Progress ...). method to complete.
3. Onprogressupdate (Progress ...)
When Publishprogress (Progress ...) is called in a background task Method, the method is called quickly, and the parameters that are carried in the method are passed in the background task. The UI can be manipulated in this method, and the interface elements can be updated accordingly using the values in the parameters.
4. OnPostExecute (Result)
This method is called quickly when the background task is completed and returned through a return statement. The returned data is passed as a parameter to this method, and the returned data can be used to perform some UI actions, such as reminding the result of the task execution, and closing the Progress Bar dialog box.

In addition, when using Asynctask, there are a few points that require extra attention:
1. An instance of an asynchronous task must be created in the UI thread.
The 2.execute (params ... params) method must be called in the UI thread.
3.onPreExecute (), Doinbackground (Params...params), onprogressupdate (Progress ... values), onpostexecute (result result) These methods should not be removed manually.
4. You cannot change the UI component information in the Doinbackground (params. params).
5. A task instance can only be executed once, and an exception will be thrown if the second execution occurs.

Third, mainacitivity
Before writing the code, you need to give the task a permission to implement the network download.
Adding permissions in the registration file
Uses-permission android:name= "Android.permission.INTERNET"

 Public  class mainactivity extends actionbaractivity {    PrivateButton button;PrivateImageView image;PrivateString image_path ="Http://img1.3lian.com/img2008/06/019/13.jpg";PrivateProgressDialog Dialog; @Overrideprotected voidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Button = (button) Findviewbyid (R.id.button);        Image = (ImageView) Findviewbyid (r.id.image); Dialog =NewProgressDialog ( This); Dialog.setmessage ("Downloading, please wait ..."); Button.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated method stub                NewMyTask (). Execute (image_path);    }        }); } Public  class mytask extends asynctask<String, Void,  Bitmap> {@OverrideprotectedBitmap doinbackground (String ... params) {//TODO auto-generated method stubHttpClient HttpClient =NewDefaulthttpclient (); HttpGet HttpGet =NewHttpGet (params[0]); Bitmap Bitmap =NULL;Try{HttpResponse HttpResponse = Httpclient.execute (HttpGet);if(Httpresponse.getstatusline (). Getstatuscode () = = $) {httpentity httpentity = httpresponse.getentity ();byte[] data = Entityutils.tobytearray (httpentity); Bitmap = bitmapfactory. Decodebytearray (Data,0, data.length); }            }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }returnBitmap } @Overrideprotected voidOnPreExecute () {//TODO auto-generated method stub            Super. OnPreExecute ();        Dialog.show (); } @Overrideprotected voidOnPostExecute (Bitmap result) {//TODO auto-generated method stub            Super. OnPostExecute (Result);            Image.setimagebitmap (result);        Dialog.dismiss (); }    }    }

Effect

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Notes (13) 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.