AsyncTask instance in Android

Source: Internet
Author: User

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; imp Ort 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 downL OaderAsyncTask; @ 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 ButtonOnClickListe Ner (); 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 a new instance is required, the new task can only be executed once, otherwise, an exception may occur. The // 2 asynchronous task instance must be created in the UI thread. The // 3 execute () method must be called in the UI thread. DownLoaderAsyncTask = new downloaderasynctask(downloaderasynctask.exe cute ("http://www.baidu.com"); break; case R. id. cancelButton: // cancel an ongoing task. The onCancelled () method will be called downLoaderAsyncTask. cancel (true); break; default: break ;}}// constructor AsyncTask <Params, Progress, Result> parameter description: // input parameter of Params startup task execution // Progress of the Progress background task execution // type of Result background calculation Result private class DownLoaderAsyncTask extends AsyncTask <String, Integer, Stri Ng> {// The onPreExecute () method is used to prepare the main thread for executing an asynchronous task @ Overrideprotected void onPreExecute () {super. onPreExecute (); textView. setText ("Call onPreExecute () method ---> prepare to start executing asynchronous tasks"); System. out. println ("Call onPreExecute () method ---> prepare to start executing asynchronous tasks");} // The doInBackground () method is used to execute asynchronous tasks, you cannot change the UI @ Overrideprotected String doInBackground (String... params) {System. out. println ("Call doInBackground () method ---> start to execute asynchronous task"); try {HttpClient client = new DefaultHttpClient (); HttpGet get = new HttpGet (params [0]); HttpResponse response = client.exe cute (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 a method in the AsyncTask class // usually in doInBackground () to notify the main thread about the execution of background tasks. // at this time, the onProgressUpdate () method publishProgress (int) (count/(float) total) * 100) in AsyncTask will be triggered; // to demonstrate the progress, sleep 1000 ms Thread. sleep (1000);} return new String (bos. toByteArray (), "UTF-8") ;}} catch (Exception e) {return null;} // After the onPostExecute () method is used for asynchronous task execution, the operation @ Overrideprotected void onPostExecute (String result) {super. onPostExecute (result); Toast. makeText (getApplicationContext (), "Call onPostExecute () method ---> asynchronous task execution completed", 0 ). show (); // textView displays the network request result textView. setText (result); System. out. println ("calling onPostExecute () method ---> asynchronous task execution completed");} // onProgressUpdate () method is used to update asynchronous execution, process the execution information of asynchronous tasks in the main thread @ Overrideprotected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values); // modify the progress bar. setProgress (values [0]); // modify TextViewtextView. setText ("loaded" + values [0] + "%");} // The onCancelled () method is used when an asynchronous task is canceled, execute related operations in the main thread @ Overrideprotected void onCancelled () {super. onCancelled (); // change the progress bar to 0progressBar. setProgress (0); // modify TextViewtextView. setText ("Call onCancelled () method ---> asynchronous task canceled"); System. out. println ("calling onCancelled () method ---> asynchronous task canceled ");}}}

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: orientation = "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" Ndroid: 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 =" 100 "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"/> </ScrollView> </LinearLayout>

Important references:

Http://blog.csdn.net/liuhe688/article/details/6532519

Thank you very much

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.