Android asynctask Asynchronous task using detailed instance (a) _android

Source: Internet
Author: User

Asynctask is a lightweight asynchronous class provided by Android that can directly inherit Asynctask, implement asynchronous operations in a class, and provide the degree to which interface feedback is currently performed asynchronously (UI progress updates can be implemented via interfaces), and the final feedback is performed to the UI main thread.

Use Asynctask to rewrite the following two methods at least:

1, Doinbackground (Params ...) in the background to perform, more time-consuming operations can be placed here. Note that the UI cannot be directly manipulated here. This method is performed in the background thread, and it usually takes a long time to complete the task. Publicprogress can be invoked during execution (Progress ...) To update the progress of the task.

2, OnPostExecute (result) in this can be used in the results of doinbackground processing operation UI. This method executes on the main thread, and the result of the task execution is returned as a parameter to this method.

Mainactivity is as follows:

Package com.example.asynctasktest;
Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.HttpStatus;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.impl.client.DefaultHttpClient;
Import android.app.Activity;
Import Android.os.AsyncTask;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.ProgressBar;
Import Android.widget.TextView;
Import Android.widget.Toast; public class Mainactivity extends activity {private button Satrtbutton; private button cancelbutton; private ProgressBar
ProgressBar;
Private TextView TextView;
Private Downloaderasynctask Downloaderasynctask; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.main);
Initview (); } public void InitviEW () {satrtbutton= (button) Findviewbyid (R.id.startbutton); cancelbutton= (Button) Findviewbyid (R.id.cancelbutton);
Satrtbutton.setonclicklistener (New Buttononclicklistener ());
Cancelbutton.setonclicklistener (New Buttononclicklistener ());
Progressbar= (ProgressBar) Findviewbyid (R.id.progressbar);
textview= (TextView) Findviewbyid (R.id.textview); Private class Buttononclicklistener implements onclicklistener{public void OnClick (View v) {switch (V.getid ()) {case
R.id.startbutton://Note://1 each time you need a new instance, the newly created task can only be executed once, otherwise an exception//2 an instance of the asynchronous task must be created in the UI thread//3 the Execute () method must be called in the UI thread.
Downloaderasynctask=new Downloaderasynctask ();
Downloaderasynctask.execute ("http://www.baidu.com");
Break
Case R.id.cancelbutton://Cancels an executing task, oncancelled () method will be invoked Downloaderasynctask.cancel (true);
Break
Default:break; }}//constructor asynctask<params, Progress, result> parameter description://params start task Execution input parameters//progress Background Task execution Progress//result background calculation result type P Rivate class Downloaderasynctask extends Asynctask<string, Integer, STRING&GT
The {//onpreexecute () method is used to do some preparation work @Override protected void OnPreExecute () {Super.onpreexecute () before performing an asynchronous task.
Textview.settext ("Call OnPreExecute () method---> Ready to start Asynchronous task");
System.out.println ("Call OnPreExecute () method---> Ready to start Asynchronous task");
The//doinbackground () method is used to perform an asynchronous task, and you cannot change the UI @Override protected string Doinbackground (String ... params) in the main thread.
System.out.println ("Invoke Doinbackground () method---> Start asynchronous Task");
try {httpclient client = new Defaulthttpclient ();
HttpGet get = new HttpGet (params[0]);
HttpResponse response = Client.execute (get);
if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {httpentity entity = response.getentity ();
InputStream is = Entity.getcontent ();
Long total = Entity.getcontentlength ();
Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
byte[] buffer = new byte[1024];
int count = 0;
int length =-1; while (length = is.read (buffer))!=-1) {bos.write (buffer, 0, length), count = length;//publishprogress () is in the Asynctask class. Method//Often calls this method in Doinbackground () to notify the main thread, background tasksImplementation of the situation.
The Onprogressupdate () method publishprogress ((int) ((Count/(float) total) * 100) in Asynctask is triggered.
To demonstrate progress, hibernate 1000 milliseconds thread.sleep (1000);
Return to New String (Bos.tobytearray (), "UTF-8");
The catch (Exception e) {return null;} return null;
The//onpostexecute () method is used to perform operations in the main thread after the completion of the asynchronous task execution @Override protected void OnPostExecute (String result) { 
Super.onpostexecute (result);
Toast.maketext (Getapplicationcontext (), "Invoke OnPostExecute () method---> Asynchronous task execution completed", 0). Show ();
TextView Display Network Request results textview.settext (result);
System.out.println ("Invoke OnPostExecute () method---> Asynchronous task Execution completed");
The//onprogressupdate () method is used to update asynchronous execution, handling the execution information of an asynchronous task in the main thread @Override protected void onprogressupdate (Integer ... values) {
Super.onprogressupdate (values);
Change the progress bar progressbar.setprogress (Values[0]);
Change TextView textview.settext ("Already loaded" +values[0]+ "%");
The//oncancelled () method is used to perform related operations in the main thread while the asynchronous task is canceled @Override protected void oncancelled () {super.oncancelled ();//Change progress bar progress to 0
Progressbar.setprogress (0); Change TextView textview.settext ("Call oncancelled" (Method---> Asynchronous task is canceled ");
System.out.println ("Invoke oncancelled () method---> Asynchronous task is canceled"); }
}
}

The

Main.xml is as follows:

<linearlayout 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:o" rientation= "vertical" > <button android:id= "@+id/startbutton" android:layout_width= "Fill_parent" Android: layout_height= "Wrap_content" android:text= "Start asynchronous Task"/> <button android:id= "@+id/cancelbutton" Android:layout_ Width= "Fill_parent" android:layout_height= "Wrap_content" android:text= "Cancel asynchronous task"/> <progressbar android:id= "@+ Id/progressbar "style=" "Android:attr/progressbarstylehorizontal" Android:layout_width= "Fill_parent" Android: layout_height= "Wrap_content" android:max= "android:progress=" 0 "/> <scrollview android:id=" @+id/ ScrollView "android:layout_width=" fill_parent "android:layout_height=" wrap_content "> <TextView android:id=" @ +id/textview "android:layout_width=" fill_parent "android:layout_height=" wrap_content "android:text=" "Test test"/ > &LT;/SCROllview> </LinearLayout> 

The above is a small series to introduce the Android Asynctask asynchronous task use detailed examples (i), I hope to help you!

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.