Android advanced 2 asynctask implements asynchronous Processing Tasks

Source: Internet
Author: User

<1> asynctask: asynchronous processing of tasks

In development Android The single-thread model principles must be observed for applications: Android UI Operations are not thread-safe and must be performed in UI In the thread. In a single-threaded model, you must always remember the following two rules:
1. Do not block UI Thread
2. Make sure that only UI Access in thread Android UI Toolkit
WhenProgramAt the first startup, Android Starts a corresponding main thread at the same time. (Main thread) The main thread is mainly responsible for processing and UI Related Events, such as user button events, user touch screen events, and Screen Drawing events, and distribute related events to corresponding components for processing. Therefore, the main thread is often called UI Thread.
For example, to obtain a webpage from the Internet Textview Set itSource codeIt is shown that this type of program involving network operations generally requires a thread to complete network access, but after obtaining the page source code, it cannot be called directly in the Network Operation thread. Textview. settext () Of . Because other threads cannot directly access the master UI Thread Member


<2> Android provides some access from other threads UI thread method
activity. runonuithread (runnable)
View. post (runnable)
View. postdelayed (runnable, long)
hanlder
but these classes or methods have some problems. It makes your Code complex and hard to understand. Implement complex operations and frequently update UI This will become worse.
to solve this problem, Android provides a tool class: asynctask , it makes it easier to create long-running tasks that need to interact with the user interface. No need to use the thread and handler .

<3>AsynctaskProcedure

AsynctaskEach step corresponds to a callback method, which should not be called by the application. What developers need to do is to implement these methods.

<1> SubclassAsynctask

AsynctaskIs an abstract class,We must write a class to inherit the class.Asynctask class

<2>ImplementationAsynctaskThe following method defined in
(Critical)

Onpreexecute ()This method will beUi threadCall. This method only makes some preparation work, such as displaying a progress bar on the interface.

Doinbackground (Params ...),InOnpreexecuteThe method is executed immediately after it is executed. The method runs in the background thread. Here, we will primarily perform those time-consuming background computing tasks.

Publishprogress thisMethod to update the real-time task progress. This method is an abstract method and must be implemented by sub-classes.

Onprogressupdate (Progress ...),InPublishprogressAfter a method is called,Ui threadThis method is called to display the progress of the task on the interface. You can use a progress bar to display the progress of the task.

Onpostexecute (result ),InDoinbackgroundAfter the execution is complete,OnpostexecuteThe method will beUi threadCall. the backend computing result is passedUi thread.

<4>AsynctaskCompliance rules

For proper use Asynctask Class:
<1> Task The instance must be in Ui thread Create
<2> Execute The method must be in Ui thread Calling
<3> Do not manually call Onpreexecute (), onpostexecute (result) , Doinbackground (Params...), onprogressupdate (Progress ...) These methods
<4>   The Task It can only be executed once. Otherwise, an exception occurs during multiple calls.

<5> generic asynctask

Asynctask Three generic types are defined. Params , SS And Result .
Params Input parameters for starting a task, such HTTP Requested URL .
SS Percentage of backend tasks executed.
Result The final result returned by the background task execution, such String .

Not all types are always used by asynchronous tasks. If you do not need to mark a parameter, you can simply use void instead.

Private class mytask extends asynctask <void, void, void> {...}<6> cancel an asynchronous task

You only need to callCancel (Boolean) method,An asynchronous task can be canceled at any time. If you call this method, iscancelled () will return true.

Make sure the task is canceled as quickly as possible, you should alwaysRegularly from doinbackground (object [])Check the iscancelled () returned value.




Specific implementation:

Note: Add network permissions: <textarea class="java" style="width: 329px; height: 149px; margin: 1.11111px;" name="code" readonly><Uses-Permission Android: Name = "android. Permission. Internet"/></textarea> Package xiaosi. asynctask; </P> <p> Import Java. io. inputstream; <br/> Import java.net. URL; <br/> Import java.net. urlconnection; <br/> Import Java. util. arraylist; <br/> Import Java. util. list; </P> <p> Import android. app. activity; <br/> Import android. content. context; <br/> Import android. graphics. bitmap; <br/> Import android. graphics. bitmapfactory; <br/> Import android. OS. asynctask; <br/> Import android. OS. bundle; <Br/> Import android. view. view; <br/> Import android. view. view. onclicklistener; <br/> Import android. widget. button; <br/> Import android. widget. imageview; <br/> Import android. widget. progressbar; <br/> Import android. widget. toast; </P> <p> public class asynctaskactivity extends activity <br/> {<br/> private imageviewimage = NULL; <br/> private buttonshow; <br/> private progressbarprogressbar = NULL; <br/> privat E intnumber = 0; <br/> List <string> imageurl = NULL; </P> <p> @ override <br/> Public void oncreate (bundle savedinstancestate) <br/>{< br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); <br/> progressbar = (progressbar) findviewbyid (R. id. processbar); <br/> image = (imageview) findviewbyid (R. id. image); <br/> show = (button) findviewbyid (R. id. show); <br/> show. setonclicklistener (new show Buttonlistener (); <br/> imageurl = new arraylist <string> (); // image address list <br/> imageurl. add ("http://image.tianjimedia.com/uploadImages/2011/266/AIO90AV2508S.jpg"); <br/> imageurl. add ("http://image.tianjimedia.com/uploadImages/2012/090/063N2L5N2HID.jpg"); <br/> imageurl. add ("http://comic.sinaimg.cn/2011/0824/U5237P1157DT20110824161051.jpg"); <br/> imageurl. add ("http://image.tianjimedia.com/uploadImages/ 2012/090/1429qo6389u8.jpg "); <br/> imageurl. add ("http://new.aliyiyao.com/UpFiles/Image/2011/01/13/nc_129393721364387442.jpg "); </P> <p >}</P> <p> public class showbuttonlistener implements onclicklistener <br/>{< br/> @ override <br/> Public void onclick (View v) <br/>{< br/> Number ++; <br/> myasynctask = new myasynctask (asynctaskactivity. this); <br/> myasynctask.exe cute (imageurl. get (Number % 5); <Br/> system. out. println ("url:" + imageurl. get (Number % 5); <br/>}</P> <p> class myasynctask extends asynctask <string, integer, bitmap> <br/>{< br/> // variable length input parameter, with asynctask. exucute () corresponds to <br/> Public myasynctask (context) <br/>{< br/> progressbar. setvisibility (view. visible); <br/> image. setvisibility (view. gone); <br/>}</P> <p> @ override <br/> protected bitmap doinbackground (string... params) <br />{< Br/> Bitmap bitmap = NULL; <br/> try <br/> {<br/> // enter the URL of the new URL object <br/> URL url = new URL (Params [0]); <br/> // get link <br/> urlconnection conn = URL. openconnection (); <br/> Conn. connect (); <br/> // get the returned inputstream <br/> inputstream = Conn. getinputstream (); <br/> // change inputstream to bitmap <br/> bitmap = bitmapfactory. decodestream (inputstream); <br/> If (image = NULL) <br/>{< br/> toast. mak Etext (getapplicationcontext (), "Download exception", toast. length_short ). show (); <br/>}< br/> inputstream. close (); <br/>}< br/> catch (exception e) <br/>{< br/> E. printstacktrace (); <br/>}< br/> return bitmap; <br/>}</P> <p>/** <br/> * after doinbackground is executed, the onpostexecute method is called by the UI thread, the background computing result is passed to the UI thread through this method. <br/> */<br/> @ override <br/> protected void onpostexecute (Bitmap bitmap) <br/>{< br/> progressbar. setvis Ibility (view. Gone); <br/> image. setvisibility (view. Visible); <br/> If (Bitmap! = NULL) <br/>{< br/> image. setimagebitmap (Bitmap); <br/>}< br/> else <br/>{< br/> toast. maketext (getapplicationcontext (), "network exception", toast. length_short ). show (); <br/>}</P> <p>/** <br/> * this method is called by the UI thread before the actual background operations are performed. This method only makes some preparation work, such as displaying a progress bar on the interface. <Br/> */<br/> @ override <br/> protected void onpreexecute () <br/>{< br/> // start the task <br/> toast. maketext (getapplicationcontext (), "task start ...... ", toast. length_short ). show (); <br/>}< br/>

mian. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "fill_parent" <br/> Android: Orientation = "vertical"> </P> <p> <button <br/> Android: id = "@ + ID/Show" <br/> Android: layout_width = "wrap_content" <br/> Android: layout_height = "wrap_content" <br/> Android: TEXT = "Next"/> </P> <p> <progressbar <br/> Android: Id = "@ + ID/processbar" <br/> Android: layout_width = "wrap_content" <br/> Android: layout_height = "wrap_content" <br/> Android: visibility = "gone"/> <br/> <porizontalscrollview <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: scrollbars = "NONE"> </P> <p> <imageview <br/> Android: id = "@ + ID/image" <br/> Android: layout_width = "wrap_content" <br/> Android: layout_height = "wrap_content"/> <br/> </porizontalscrollview> </P> <p> </linearlayout>

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.