Android Official Development Document Training Series Course Chinese version: Efficient display of bitmaps processing pictures in non-UI threads

Source: Internet
Author: User

Original address: http://android.xsoftlab.net/training/displaying-bitmaps/process-bitmap.html

We discussed the Bitmapfactory.decode* method in the load Large Bitmaps efficiently in the last lesson, talking about the process of reading data in the UI thread, especially reading from the disk or the network ( or other places where the reading speed is secondary to memory). The time to read the data is unpredictable, depending on a variety of factors (speed of reading from disk or network, image size, CPU power, etc). If one of these factors blocks the UI thread, the system flags the program as an unresponsive flag and gives the user an option to turn off (see Designing for responsiveness for more information).

This lesson discusses working with bitmaps in non-UI threads by using Asynctask and showing how to handle concurrency problems.

Using Asynctask

Class Asynctask provides a brief way to handle the work of a background process and pushes the processed results into the UI thread. If you want to use this class, you need to create a subclass of the class, and then override the provided method. Here's an example of how to use Asynctask and Decodesampledbitmapfromresource () to load a large image onto a imageview:

Class Bitmapworkertask extends Asynctask<integer, Void, bitmap> {Private FinalWeakreference<imageview> imageviewreference;Private intdata =0; Public Bitmapworkertask(ImageView ImageView) {//Use a weakreference to ensure the ImageView can be garbage collectedImageviewreference =NewWeakreference<imageview> (ImageView); }//Decode image in background.    @Override    protectedBitmapDoinbackground(Integer ... params) {data = params[0];returnDecodesampledbitmapfromresource (Getresources (), data, -, -)); }//Once complete, see if ImageView is still around and set bitmap.    @Override    protected void OnPostExecute(Bitmap Bitmap) {if(Imageviewreference! =NULL&& Bitmap! =NULL) {FinalImageView ImageView = Imageviewreference.get ();if(ImageView! =NULL) {Imageview.setimagebitmap (bitmap); }        }    }}

ImageView's weakreference ensures that Asynctask does not prevent ImageView and the transactions it references from being reclaimed by the garbage collector. This does not guarantee that ImageView still exists when the task is completed, so you must also check its references in the OnPostExecute () method. ImageView may no longer exist, for example, when a user leaves the activity or at the end of a task some configuration changes.

To start an asynchronous task to load a picture, you need to simply create a new task and execute it:

publicvoidloadBitmap(int resId, ImageView imageView) {    new BitmapWorkerTask(imageView);    task.execute(resId);}
Handling concurrency

Some common view controls, such as the ListView and the GridView, can involve another problem, which is concurrency when used in conjunction with Asynctask. To be able to use memory effectively, these controls will recycle the child view as the user slides. If each sub-view triggers a asynctask, then there is no guarantee that the view associated with it will not be recycled when the task is completed. In addition, tasks that are initiated sequentially cannot be guaranteed to be completed sequentially.

Blog multithreading for performance a further discussion of how to handle concurrency, which provides a solution: a reference to the most recent asynctask is stored in ImageView, This reference can be used to check the most recent asynctask when the task is completed. In a similar way, the asynctask of the above chapters can be expanded into similar patterns.

Create a dedicated drawable subclass to store references to work tasks. In this case, bitmapdrawable will be used, so you can have a bitmap displayed on ImageView before the task is complete:

static class AsyncDrawable extends BitmapDrawable {    privatefinal WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;    publicAsyncDrawable(Resources res, Bitmap bitmap,            BitmapWorkerTask bitmapWorkerTask) {        super(res, bitmap);        bitmapWorkerTaskReference =            new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);    }    publicgetBitmapWorkerTask() {        return bitmapWorkerTaskReference.get();    }}

Before performing the Bitmapworkertask task, you can create a asyncdrawable and bind the task to the target ImageView:

publicvoidloadBitmap(int resId, ImageView imageView) {    if (cancelPotentialWork(resId, imageView)) {        finalnew BitmapWorkerTask(imageView);        final AsyncDrawable asyncDrawable =                new AsyncDrawable(getResources(), mPlaceHolderBitmap, task);        imageView.setImageDrawable(asyncDrawable);        task.execute(resId);    }}

The Cancelpotentialwork () method referenced by the above code is used to check if there is another task in progress that has been associated with the ImageView. If this is the case, it will attempt to cancel the original task by canceling (). In rare cases, the new task data may match the existing task, so there is no further action. Here is the implementation of the Cancelpotentialwork () method:

 Public Static Boolean cancelpotentialwork(intData, ImageView ImageView) {FinalBitmapworkertask bitmapworkertask = Getbitmapworkertask (ImageView);if(Bitmapworkertask! =NULL) {Final intBitmapData = Bitmapworkertask.data;//If BitmapData is not yet set or it differs from the new data        if(BitmapData = =0|| BitmapData! = data) {//Cancel Previous taskBitmapworkertask.cancel (true); }Else{//The same work was already in progress            return false; }    }//No task associated with the ImageView, or a existing task was cancelled    return true;}

There is an auxiliary method: Getbitmapworkertask (), which is used to receive tasks associated with the specified ImageView:

privatestaticgetBitmapWorkerTask(ImageView imageView) {   ifnull) {       final Drawable drawable = imageView.getDrawable();       ifinstanceof AsyncDrawable) {           final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;           return asyncDrawable.getBitmapWorkerTask();       }    }    returnnull;}

The final step is to update OnPostExecute () in Bitmapworkertask, so it checks whether the task has been canceled and checks whether the current task matches the ImageView associated with it:

Class Bitmapworkertask extends Asynctask<integer, Void, bitmap> {...@Override    protected void OnPostExecute(Bitmap Bitmap) {if(IsCancelled ()) {bitmap =NULL; }if(Imageviewreference! =NULL&& Bitmap! =NULL) {FinalImageView ImageView = Imageviewreference.get ();FinalBitmapworkertask bitmapworkertask = Getbitmapworkertask (ImageView);if( This= = Bitmapworkertask && ImageView! =NULL) {Imageview.setimagebitmap (bitmap); }        }    }}

Now this implementation is appropriate to use similar to the ListView and GridView will reclaim their child view of the component, simple call LoadBitmap () can be normal to ImageView set the picture. For example, in the implementation of a GridView, this method can be used in the GetView () method of the corresponding adapter.

Android Official Development Document Training Series Course Chinese version: Efficient display of bitmaps processing pictures in non-UI threads

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.