The BitmapFactory.decode*
methods, discussed in the Load Large Bitmaps Efficiently lesson, should 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).
在"高效加载大位图"这节课我们讨论了BitmapFactory.decode*方法,如果数据来源是读取网络或者磁盘不要在主UI线程处理(或则确认是除了内存的其他源)。
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.).
加载数据的时间是无法预测的,而且取决于各种因素(网络和磁盘的读取速度,图像尺寸,CPU功率,等等)。
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).
如果这些事物中的一个阻塞UI线程,系统会停止你的应用提示无响应和用户会有一个关闭它的选项()
This lesson walks you through processing bitmaps in a background thread using AsyncTask
and shows you how to handle concurrency issues.
这节课让你了解处理位图在一个后台线程使用AsyncTask和展示怎样处理并发问题。
Use an AsyncTask(使用异步任务)
AsyncTask
class provides an easy way to execute some work in a background thread and publish the results back on the UI thread.
ImageView
using AsyncTask
and decodeSampledBitmapFromResource()
:- 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
- // 使用一个弱引用来确保ImageView无用的时候被回收
- 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.
- // 一旦完成,查看ImageView如果还在设置位图
- @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.
ImageView使用弱引用,确保AsyncTask不能阻止ImageView和任何他的引用被垃圾回收。
There’s no guarantee the ImageView
is still around when the task finishes, so you must also check the reference in onPostExecute()
.
这不能确保当任务完成时ImageView还在,所以你还必须检查引用在onPostExeute()方法里。
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.
ImageView可能不会长时间存在,例如,如果用户退出activity或者布局发生了改变在任务结束前。
To start loading the bitmap asynchronously, simply create a new task and execute it:
异步开始加载位图,简单的创建一个新的任务并且执行它:
- public void loadBitmap(int resId, ImageView imageView) {
- BitmapWorkerTask task = new BitmapWorkerTask(imageView);
- task.execute(resId);
- }
Handle 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.
普通的视图控件例如listview和gridview会有其他的问题,当联合AsyncTask使用的时候在之前的章节演示过。
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.
如果每个子视图启动一个AsyncTask,这不能完全保证,关联的视图没有准备回收给其他视图中使用。
Furthermore, there is no guarantee that the order in which asynchronous tasks are started is the order that they complete.
此外,不能保证异步任务的完成顺序和开始顺序一样。
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 can later be checked when the task completes.
博客发布《多线程性能》详细讨论了并发处理,并且提供一个解决方法,ImageView储存一个标记在最近的AsyncTask,过后当任务完成时被检查。
Using a similar method, the AsyncTask
from the previous section can be extended to follow a similar pattern.
使用类似的方法,前面部分的AsyncTask可以扩展成同样的模型。
Create a dedicated Drawable
subclass to store a reference back to the worker task.
创建一个专门储存标记的Drawable子类回调工作任务。
In this case, a BitmapDrawable
is used so that a placeholder image can be displayed in the ImageView
while the task completes:
在这个方案中,当任务完成时一个使用BitmapDrawable的位置标记的图像被显示在ImageView.
- 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
:
- 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.execute(resId);
- }
- }
The
cancelPotentialWork
method referenced in the code sample above checks if another running task is already associated with the ImageView
.
cancel()
.
cancelPotentialWork
:
- 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 cancelled
- return true;
- }
A helper method,
getBitmapWorkerTask()
, is used above to retrieve the task associated with a particular ImageView
:
- 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 cancelled and if the current task matches the one associated with the ImageView
:
- 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.
loadBitmap
where you normally set an image to your ImageView
.
GridView
implementation this would be in the getView()
method of the backing adapter.