Android Thread Action Object Asynctask threading mechanism

Source: Internet
Author: User
Tags abstract log log xmlns

Simply put, a program has only one main thread, and can have multiple main threads. The same is true in the Android world, Android is a single-threaded model, and time-consuming operations must be performed in a non main thread, so Google provides us with a asynctask multithreaded operation to facilitate our use of threads.

for Android Threads There is also a need to pay special attention to that Android is not allowed to update the UI in the child thread, I believe many beginners must have encountered this problem, how to solve it? In the activity, we can pass the


New Thread (new Runnable () {@Override public void run () {LOG.V ("abc", "Child Thread Execution");   Runonuithread (New Runnable () {@Override public void run () {LOG.V ("abc", "Return main thread Execution");   }   }); }). Start ();


to achieve our results, but one thing to note is that in the Fragement, Runonuithread () can not be used, so everyone in the use of a little attention can be. Of course, Android we can also through the Handler+messager to complete multithreading, for the use of this, in the previous blog has been introduced for you, not to repeat, the following we begin to introduce the focus of this article: the use of asynctask.


Asynctask<parans, Progress, Result> is an abstract class, we need to first implement this abstract class before we can use, for its three parameters: Parans: Parameter types entered when starting a task ; progress: The type of the return value in the background task execution; Result: the type of results returned after the background execution of a task completes.


To build a callback method for the Asynctask subclass: 1, Doinbackground: You must override, asynchronously perform the tasks that the background thread will complete, 2, OnPreExecute: be called before the background time-consuming operation is performed, and some initialization can be done by the user; 3. OnPostExecute: When Doinbackground () is finished, the system automatically invokes and passes the return value of Doinbackground () to the OnPostExecute () method, in simple terms, Doinbackground () completes the time-consuming operation, resulting in a onpostexecute () method to update ui;4, Onprogressupdate: In the Doinbackground () method, invoke the Publishprogress () method , the method is triggered when the task's execution progress is updated.


said so much, I believe you still have some doubts in mind, below we through two simple Android applet, for you to give a specific introduction to the use of Asynctask:


A, Asynctask is an abstract method in the order of execution:


1, create a Asynctask subclass object:


public class Myasynctask extends asynctask<void, void, void> {@Override protected void OnPreExecute () {Super   . OnPreExecute ();   LOG.V ("abc", "OnPreExecute");   } @Override protected void Doinbackground (void ... arg0) {LOG.V ("abc", "Doinbackground");   Publishprogress (arg0);   return null;   } @Override protected void onpostexecute (void result) {Super.onpostexecute (result);   LOG.V ("abc", "OnPostExecute");   } @Override protected void onprogressupdate (void ... values) {super.onprogressupdate (values);   LOG.V ("abc", "Onprogressupdate"); }   }


2, call to child thread in Mainactivity, execute:


public class Mainactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) {   Super.oncreate (savedinstancestate);   Setcontentview (R.layout.activity_main); New Myasynctask (). Execute ()//Start execution}


3, log log after execution:


Android Thread manipulation object Asynctask threading mechanism


through this log information, is not to solve the doubts in your mind, below we look at a use of Asynctask load network image example.


b, load network Picture:


1, first create an XML that hosts the activity layout file:


<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://" Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android: Layout_margin= "10DP" tools:context= ". Mainactivity "> <imageview android:id=" @+id/img "android:layout_width=" Match_parent "android:layout_height=" Match_parent "/> <progressbar android:id= @+id/progressbar" android:layout_width= "Wrap_content" Android:la yout_height= "Wrap_content" android:visibility= "Gone" android:layout_centerinparent= "true"/> </RelativeLayou T>


layout file is very simple, is a imageview+progressbar, in loading ImageView is we through ProgressBar to remind users to wait.


2, create our Activity object


  public class Asynctaskimager extends activity {private ProgressBar PB;   Private ImageView image;   Private static final String URL = "Bdlogo.png";   @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);   Setcontentview (R.layout.imager);   Init ();   New Imageasynctask (). Execute (URL);   private void Init () {PB = (ProgressBar) Findviewbyid (R.id.progressbar);   Image = (ImageView) Findviewbyid (r.id.img); Class Imageasynctask extends asynctask<string, void, bitmap>{@Override protected void OnPreExecute () {su   Per.onpreexecute ();   Pb.setvisibility (view.visible);   } @Override protected Bitmap doinbackground (String ... params) {Bitmap Bitmap = null;   URLConnection conn = null;   String URL = params[0];   try {conn = new URL (URL). OpenConnection ();   InputStream in = Conn.getinputstream ();   Bufferedinputstream bis = new Bufferedinputstream (in);   Bitmap = Bitmapfactory.decodestream (bis); } CatCH (malformedurlexception e) {e.printstacktrace ();   catch (IOException e) {e.printstacktrace ();   return bitmap;   @Override protected void OnPostExecute (Bitmap result) {Super.onpostexecute (result);   Pb.setvisibility (View.gone);   Image.setimagebitmap (result); }   }   }


here Our work has been basically completed, and finally do not forget in the androidmanifest.xml to make a statement.


3, add network operation permission:


<uses-permission android:name= "Android.permission.INTERNET"/> Because we need to use a network connection, So we need to add a network access right in the androidmanifest.xml.

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.