Android asynchronous task learning notes

Source: Internet
Author: User

Android asynchronous task learning notes

Android asynchronous tasks can easily complete time-consuming operations and update the UI. Unlike multithreading, message queues are used, subthreads send messages to the main thread to update the UI. In short, android asynchronous tasks further encapsulate multi-thread interaction for convenience.

The following is the asynchronous task demo code:

Download the image asynchronously and update the interface.

Package com. example. android_async_task2; import java. io. byteArrayOutputStream; import java. io. IOException; import java. io. inputStream; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. client. clientProtocolException; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. util. entityUtils; import android. app. activity; import android. app. progressDialog; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. asyncTask; import android. OS. bundle; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. imageView; public class MainActivity extends Activity {private Button btn = null; private ImageView image = null; private String image_path = "http://f2.sjbly.cn/m13/0729/1459/6947edn_690x459_ B .jpg"; private ProgressDialog dialog; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn = (Button) this. findViewById (R. id. button1); dialog = new ProgressDialog (this); dialog. setTitle ("prompt message"); dialog. setMessage ("Download in progress. Please wait ...... "); // set the Style dialog of the progress bar. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); // The screen does not lose the focus dialog. setCancelable (false); image = (ImageView) this. findViewById (R. id. imageView1); btn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {new mytask(cmd.exe cute (image_path) ;}});} public class MyTask extends AsyncTask
 
  
{@ Overrideprotected void onPreExecute () {dialog. show (); super. onPreExecute () ;}@ Overrideprotected Bitmap doInBackground (String... params) {// define a memory stream. You do not need to disable ByteArrayOutputStream out = new ByteArrayOutputStream (); // define an input stream InputStream in = null; Bitmap bitmap = null; // obtain the network resource HttpClient = new DefaultHttpClient () through the httpClient class; // set the Request Method (note that the request URL must be written !!!) HttpGet httpGet = new HttpGet (params [0]); try {// get the Request status HttpResponse httpResponse=httpClient.exe cute (httpGet); // determine the Request status result code if (httpResponse. getStatusLine (). getStatusCode () = 200) {/* // obtain the response object HttpEntity httpEntity = httpResponse through an object class. getEntity (); // obtain the object byte array byte [] data = EntityUtils through an object tool class. toByteArray (httpEntity); // create Bitmap object BitmapFactory through the factory class. decodeByteArray (data, 0, data. length); * // get the input stream in = httpResponse. getE Ntity (). getContent (); // get the total length of the object long file_length = httpResponse. getEntity (). getContentLength (); // calculate the total length of int total_len = 0; int len = 0; byte [] buffer = new byte [1024]; try {while (len = in. read (buffer ))! =-1) {total_len + = len; // scale calculation formula int value = (int) (total_len/(float) file_length) * 100 ); // hprogress (value) of the publish progress bar; // write the output stream out. write (buffer, 0, len);} // The Memory output is converted into a byte array bitmap = BitmapFactory. decodeByteArray (out. toByteArray (), 0, out. toByteArray (). length);} catch (Exception e) {} finally {if (in! = Null) {in. close () ;}}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return bitmap;} @ Overrideprotected void onPostExecute (Bitmap result) {super. onPostExecute (result); image. setImageBitmap (result); dialog. dismiss () ;}@ Overrideprotected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values); dialog. setProgress (values [0]) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}
 
Where
publishProgress(value);
Yes, several objects can be sent
OnProgressUpdate () method.

DEMO download: http://download.csdn.net/detail/u014600432/8175337

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.