Due to my limited English skills, please understand at the beginning
This blog is original as long as it does not indicate "Conversion". For the post, please indicate the link to this blog.
Processing Bitmaps Off the UI Thread
Processing Bitmap outside the UI thread
The BitmapFactory. decode * methods, discussed in the Load Large Bitmaps Efficiently lesson, shocould not be executed on the main UI thread if the source data is read from disk or a network location (or really any source other than memory ).
The time this data takes to load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc .).
If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it (see Designing for Responsiveness for more information ).
Methods Starting with BitmapFactory. decode * have been discussed in "Load Large Bitmaps Efficiently". If the data source is on a disk or network, these methods should not be executed in the main UI thread.
This lesson walks you through processing bitmaps in a background thread using AsyncTask and shows you how to handle concurrency issues.
Here we will teach you how to use AsyncTask to process bitmap in the background thread and show you how to handle concurrency issues.
Use an AsyncTask
The AsyncTask class provides an easy way to execute some work in a background thread and publish the results back on the UI thread.
To use it, create a subclass and override the provided methods.
Here's an example of loading a large image into an ImageView using AsyncTask and decodeSampledBitmapFromResource ():
Use AsyncTask
The AsyncTask class provides a simple method to execute some work in the background thread and publish the result to the UI thread.
To use it, create a subclass and override the methods in it.
Here is an example of using AsyncTask and decodeSampledBitmapFromResource () to load large images to ImageView.
[Java]
Class BitmapWorkerTask extends AsyncTask <Integer, Void, Bitmap> {
Private final WeakReference <ImageView> imageViewReference;
Private int data = 0;
Public BitmapWorkerTask (ImageView imageView ){
// Use a WeakReference to ensure the ImageView can be garbage collected
ImageViewReference = new WeakReference <ImageView> (imageView );
}
// Decode image in background.
@ Override
Protected Bitmap doInBackground (Integer... params ){
Data = params [0];
Return decodeSampledBitmapFromResource (getResources (), data, 100,100 ));
}
// Once complete, see if ImageView is still around and set bitmap.
@ Override
Protected void onPostExecute (Bitmap bitmap ){
If (imageViewReference! = Null & bitmap! = Null ){
Final ImageView imageView = imageViewReference. get ();
If (imageView! = Null ){
ImageView. setImageBitmap (bitmap );
}
}
}
}
Class BitmapWorkerTask extends AsyncTask <Integer, Void, Bitmap> {
Private final WeakReference <ImageView> imageViewReference;
Private int data = 0;
Public BitmapWorkerTask (ImageView imageView ){
// Use a WeakReference to ensure the ImageView can be garbage collected
ImageViewReference = new WeakReference <ImageView> (imageView );
}
// Decode image in background.
@ Override
Protected Bitmap doInBackground (Integer... params ){
Data = params [0];
Return decodeSampledBitmapFromResource (getResources (), data, 100,100 ));
}
// Once complete, see if ImageView is still around and set bitmap.
@ Override
Protected void onPostExecute (Bitmap bitmap ){
If (imageViewReference! = Null & bitmap! = Null ){
Final ImageView imageView = imageViewReference. get ();
If (imageView! = Null ){
ImageView. setImageBitmap (bitmap );
}
}
}
} The WeakReference to the ImageView ensures that the AsyncTask does not prevent the ImageView and anything it references from being garbage collected.
There's no guarantee the ImageView is still around when the task finishes, so you must also check the reference in onPostExecute ().
The ImageView may no longer exist, if for example, the user navigates away from the activity or if a configuration change happens before the task finishes.
The WeakReference associated with ImageView ensures that AsyncTask does not prevent ImageView from being reclaimed from any reference to it.
When the task ends, the ImageView still exists. Therefore, you must check this reference in onPostExecute ().
For example, if you navigate outside the activity or if a configuration change occurs before the task ends, the ImageView may no longer exist.
To start loading the bitmap asynchronously, simply create a new task and execute it:
To load bitmap asynchronously, you can create a new task and execute it.
[Java]
Public void loadBitmap (int resId, ImageView imageView ){
BitmapWorkerTask task = new BitmapWorkerTask (imageView );
Task.exe cute (resId );
}
Public void loadBitmap (int resId, ImageView imageView ){
BitmapWorkerTask task = new BitmapWorkerTask (imageView );
Task.exe cute (resId );
}
Handle Concurrency
Processing concurrency
Common view components such as ListView and GridView introduce another issue when used in conjunction with the AsyncTask as demonstrated in the previous section.
In order to be efficient with memory, these components recycle child views as the user scrolls.
If each child view triggers an AsyncTask, there is no guarantee that when it completes, the associated view has not already been recycled for use in another child view. furthermore, there is no guarantee that the order in which asynchronous tasks are started is the order that they complete.
Common view components, for example, when ListView and GridView are used together with AsyncTask (as shown in the previous section), another problem is introduced.
To improve the memory efficiency, these components collect sub-views when you scroll the screen.
If each sub-view triggers an AsyncTask, the associated view is not recycled for use in another sub-view.
In addition, the order in which the asynchronous task starts is not guaranteed to be consistent with that at completion.
The blog post Multithreading for Performance further discusses dealing with concurrency, and offers a solution where the ImageView stores a reference to the most recent AsyncTask which later be checked when the task completes.
Using a similar method, the AsyncTask from the previous section can be extended to follow a similar pattern.
This blog has published Multithreading for Performance to further discuss concurrent processing, in addition, it provides a solution for ImageView to store a reference to the nearest AsyncTask that can be checked after the task is completed.
Using a similar method, the AsyncTask mentioned in the previous section can be extended to follow a similar form
Create a dedicated Drawable subclass to store a reference back to the worker task.
In this case, a BitmapDrawable is used so that a placeholder image can be displayed in the ImageView while the task completes:
Create a dedicated Drawable subclass to store a reference associated with a work task
In this way, BitmapDrawable is used. When the task is completed, the image at a position can be displayed in ImageView.
[Java]
Static class AsyncDrawable extends BitmapDrawable {
Private final WeakReference <BitmapWorkerTask> bitmapWorkerTaskReference;
Public AsyncDrawable (Resources res, Bitmap bitmap,
BitmapWorkerTask bitmapWorkerTask ){
Super (res, bitmap );
BitmapWorkerTaskReference =
New WeakReference <BitmapWorkerTask> (bitmapWorkerTask );
}
Public BitmapWorkerTask getBitmapWorkerTask (){
Return bitmapWorkerTaskReference. get ();
}
}
Static class AsyncDrawable extends BitmapDrawable {
Private final WeakReference <BitmapWorkerTask> bitmapWorkerTaskReference;
Public AsyncDrawable (Resources res, Bitmap bitmap,
BitmapWorkerTask bitmapWorkerTask ){
Super (res, bitmap );
BitmapWorkerTaskReference =
New WeakReference <BitmapWorkerTask> (bitmapWorkerTask );
}
Public BitmapWorkerTask getBitmapWorkerTask (){
Return bitmapWorkerTaskReference. get ();
}
} Before executing the BitmapWorkerTask, you create an AsyncDrawable and bind it to the target ImageView:
Before executing BitmapWorkerTask, you can create an AsyncDrawable and bind it to the target ImageView.
[Java]
Public void loadBitmap (int resId, ImageView imageView ){
If (cancelPotentialWork (resId, imageView )){
Final BitmapWorkerTask task = new BitmapWorkerTask (imageView );
Final AsyncDrawable asyncDrawable =
New AsyncDrawable (getResources (), mPlaceHolderBitmap, task );
ImageView. setImageDrawable (asyncDrawable );
Task.exe cute (resId );
}
}
Public void loadBitmap (int resId, ImageView imageView ){
If (cancelPotentialWork (resId, imageView )){
Final BitmapWorkerTask task = new BitmapWorkerTask (imageView );
Final AsyncDrawable asyncDrawable =
New AsyncDrawable (getResources (), mPlaceHolderBitmap, task );
ImageView. setImageDrawable (asyncDrawable );
Task.exe cute (resId );
}
} The cancelPotentialWork method referenced in the code sample above checks if another running task is already associated with the ImageView.
If so, it attempts to cancel the previous task by calling cancel ().
In a small number of cases, the new task data matches the existing task and nothing further needs to happen.
Here is the implementation of cancelPotentialWork:
The cancelPotentialWork method in the preceding example checks whether another running task has been associated with this ImageView.
If yes, it tries to cancel the previous task by calling cancel ()
In rare cases, the new task data matches the existing task data
The following is the implementation of cancelPotentialWork.
[Java]
Public static boolean cancelPotentialWork (int data, ImageView imageView ){
Final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask (imageView );
If (bitmapWorkerTask! = Null ){
Final int bitmapData = bitmapWorkerTask. data;
If (bitmapData! = Data ){
// Cancel previous task
BitmapWorkerTask. cancel (true );
} Else {
// The same work is already in progress
Return false;
}
}
// No task associated with the ImageView, or an existing task was canceled
Return true;
}
Public static boolean cancelPotentialWork (int data, ImageView imageView ){
Final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask (imageView );
If (bitmapWorkerTask! = Null ){
Final int bitmapData = bitmapWorkerTask. data;
If (bitmapData! = Data ){
// Cancel previous task
BitmapWorkerTask. cancel (true );
} Else {
// The same work is already in progress
Return false;
}
}
// No task associated with the ImageView, or an existing task was canceled
Return true;
} A helper method, getBitmapWorkerTask (), is used above to retrieve the task associated with a special ImageView:
The preceding getBitmapWorkerTask () method is used to obtain the task associated with a specific ImageView.
[Java]
Private static BitmapWorkerTask getBitmapWorkerTask (ImageView imageView ){
If (imageView! = Null ){
Final Drawable drawable = imageView. getDrawable ();
If (drawable instanceof AsyncDrawable ){
Final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
Return asyncDrawable. getBitmapWorkerTask ();
}
}
Return null;
}
Private static BitmapWorkerTask getBitmapWorkerTask (ImageView imageView ){
If (imageView! = Null ){
Final Drawable drawable = imageView. getDrawable ();
If (drawable instanceof AsyncDrawable ){
Final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
Return asyncDrawable. getBitmapWorkerTask ();
}
}
Return null;
} The last step is updating onPostExecute () in BitmapWorkerTask so that it checks if the task is canceled and if the current task matches the one associated with the ImageView:
The last step is to update onPostExecute () in BitmapWorkerTask to check whether the task is canceled and whether the current task matches the task associated with ImageView.
[Java]
Class BitmapWorkerTask extends AsyncTask <Integer, Void, Bitmap> {
...
@ Override
Protected void onPostExecute (Bitmap bitmap ){
If (isCancelled ()){
Bitmap = null;
}
If (imageViewReference! = Null & bitmap! = Null ){
Final ImageView imageView = imageViewReference. get ();
Final BitmapWorkerTask bitmapWorkerTask =
GetBitmapWorkerTask (imageView );
If (this = bitmapWorkerTask & imageView! = Null ){
ImageView. setImageBitmap (bitmap );
}
}
}
}
Class BitmapWorkerTask extends AsyncTask <Integer, Void, Bitmap> {
...
@ Override
Protected void onPostExecute (Bitmap bitmap ){
If (isCancelled ()){
Bitmap = null;
}
If (imageViewReference! = Null & bitmap! = Null ){
Final ImageView imageView = imageViewReference. get ();
Final BitmapWorkerTask bitmapWorkerTask =
GetBitmapWorkerTask (imageView );
If (this = bitmapWorkerTask & imageView! = Null ){
ImageView. setImageBitmap (bitmap );
}
}
}
} This implementation is now suitable for use in ListView and GridView components as well as any other components that recycle their child views.
Simply call loadBitmap where you normally set an image to your ImageView.
For example, in a GridView implementation this wocould be in the getView () method of the backing adapter.
This implementation applies to ListView and GridView components, and to any other component that recycles their child views.
You can call loadBitmap to set images for ImageView.
For example, in a GridView implementation, you should call loadBitmap in the getView () method of the adapter.