Android thread model and AsyncTask

Source: Internet
Author: User

Thread model: When an android Application runs, a main thread of the UI starts. This is a very important thread, which is responsible for dispatching events to corresponding controls, this includes screen plotting events, which are also threads for user interaction with android controls. For example, when you input text in EditText on the screen, the UI thread will distribute the event to the EditText of the text you just entered, and then send an update (invalidate) request to the event queue. The UI thread will remove this request from the event queue and notify EditText to redraw itself on the screen.

This single-thread model will make the android Application inferior in performance. If you perform some time-consuming operations in this single-thread, such as accessing the database or downloading images from the network, the entire user interface is blocked. For example:

1 Bitmap B = loadImageFromNetwork ();

 


EE
This operation is very time-consuming. In this case, you will find that the interface is frozen and android does not respond after 5 seconds in the system, and an error of disabling or waiting will be displayed. Www.2cto.com

Maybe we can use a new Thread to solve it.

1 new Thread (new Runnable (){

2 public void run (){

3 Bitmap B = loadImageFromNetwork ();

4 mImageView. setImageBitmap (B );

5}

6}). start ();

But this will cause some very imperceptible errors, because we know that the UI thread is NOT thread-safe. Of course there are many ways to deal with this problem:

Android provides several methods to access the UI thread in other threads.

• Activity. runOnUiThread (Runnable)
• View. post (Runnable)
• View. postDelayed (Runnable, long)
• Hanlder

1 new Thread (new Runnable (){

2 public void run (){

3 final Bitmap B = loadImageFromNetwork ();

4 mImageView. post (new Runnable (){

5 mImageView. setImageBitmap (B );

6 });

7}

8}). start ();

This method is cumbersome. It also gets worse when you need to implement complicated operations and update the UI frequently. To solve this problem, android provides a tool class: AsyncTask, which makes it easier to create long-running tasks that need to interact with the user interface.

For example, attach a network image:

01 ublic class CanvasImageTask extends AsyncTask <ImageView, Void, Bitmap> {

02 private ImageView gView;

03

04 protected Bitmap doInBackground (ImageView... views ){

05 Bitmap bmp = null;

06 ImageView view = views [0];

07 // obtain and render the Image Based on iconUrl. The iconUrl url is placed in the view tag.

08 if (view. getTag ()! = Null ){

09 try {

10 URL url = new URL (view. getTag (). toString ());

11 HttpURLConnection conn = (HttpURLConnection) url. openConnection ();

12 conn. setDoInput (true );

13 conn. connect ();

14 InputStream stream = conn. getInputStream ();

15 bmp = BitmapFactory. decodeStream (stream );

16 stream. close ();

17} catch (Exception e ){

18 Log. v ("img", e. getMessage ());

19 return null;

20}

21}

22 this. gView = view;

23 return bmp;

24}

25 protected void onPostExecute (Bitmap bm ){

26 if (bm! = Null ){

27 this. gView. setImageBitmap (bm );

28 this. gView = null;

29}

30}

31

32}

33 directly called in Activity

34 if (! Img. isDrawingCacheEnabled () |! Holder. image. getTag (). equals (imgpath )){

35 img. setImageResource (R. drawable. icon_app );

36 img. setTag (imgpath );

37 try {

38 new canvasimagetask(cmd.exe cute (img );

39 img. setDrawingCacheEnabled (true );

40} catch (Exception e ){

41 Log. e ("error", "RejectedExecutionException in content_img:" + imgpath );
In this way, the asynchronous thread is used for image loading without blocking. We can also use callback for callback after image loading.


01 public class CanvasImageTaskCall extends AsyncTask <ImageView, Void, Bitmap> implements Callback {

02 private ImageView gView;

03

04 protected Bitmap doInBackground (ImageView... views ){

05 Bitmap bmp = null;

06 ImageView view = views [0];

07 // obtain and render the Image Based on iconUrl. The iconUrl url is placed in the view tag.

08 if (view. getTag ()! = Null ){

09 try {

10 URL url = new URL (view. getTag (). toString ());

11 HttpURLConnection conn = (HttpURLConnection) url. openConnection ();

12 conn. setDoInput (true );

13 conn. connect ();

14 InputStream stream = conn. getInputStream ();

15 bmp = BitmapFactory. decodeStream (stream );

16 stream. close ();

17} catch (Exception e ){

18 e. printStackTrace ();

19 Log. v ("img", e. getMessage ());

20 Message msg = new Message ();

21 msg. what = 0;

22 handleMessage (msg );

23 return null;

24}

25}

26 this. gView = view;

27 return bmp;

28}

29 protected void onPostExecute (Bitmap bm ){

30 if (bm! = Null ){

31 this. gView. setImageBitmap (bm );

32 this. gView. setTag (bm );

33 this. gView = null;

34 Message msg = new Message ();

35 msg. what = 1;

36 handleMessage (msg );

37}

38}

39 public boolean handleMessage (Message msg ){

40 // TODO Auto-generated method stub

41 return false;

42}

43

44}
Directly call in Activity


01 new CanvasImageTaskCall (){

02 @ Override

03 public boolean handleMessage (Message msg ){

04 switch (msg. what ){

05 case 0:

06 Log. I ("test", "image loading failed ");

07 break;

08 case 1:

09 Log. I ("test", "image loaded successfully ");

10 break;

11 default:

12 break;

13}

14 saveButton. setTextColor (Color. WHITE );

15 saveButton. setClickable (true );

16 bitmap = (Bitmap) imageView. getTag ();

17 return super. handleMessage (msg );

18}

19. cmd.exe cute (img );

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.