Android Training精要(六)如何防止Bitmap对象出现OOM
1.使用AsyncTask異步加載bitmap圖片避免OOM:
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);
}
}
}
}
decodeSampledBitmapFromResource方法具体的实现见上一篇 Android
Training精要(五)讀取Bitmap對象實際的尺寸和類型
如果有多个Task执行如何處理task的幷發问题:在imageview組件中存一個AsyncTask
的引用,之後用來判斷task是否執行完成:
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();
}
}
在執行task之前,創建一個AsyncDrawable用來綁定imageView和加載其bitmap
的task
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);
}
} 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;
} 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;
}
最後在onPostExecute方法中判斷task是否被取消或者不是同一個task
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);
}
}
}
}
2.使用LruCache構建Bitmap緩存(內存緩存)
private LruCache<String, Bitmap> mMemoryCache; @Override
protected void onCreate(Bundle savedInstanceState) {
...
// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
...
} public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
} public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
} 從緩存中得到bitmap.
public void loadBitmap(int resId, ImageView imageView) {
final String imageKey = String.valueOf(resId); final Bitmap bitmap = getBitmapFromMemCache(imageKey);
if (bitmap != null) {
mImageView.setImageBitmap(bitmap);
} else {
mImageView.setImageResource(R.drawable.image_placeholder);
BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
task.execute(resId);
}
}
之前的BitmapWorkerTask需要修改加入bitmap到緩存
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
...
// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
final Bitmap bitmap = decodeSampledBitmapFromResource(
getResources(), params[0], 100, 100));
addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
return bitmap;
}
}
3.使用硬盤緩存Use a Disk Cache:
如果加載的圖片太多或者app被系統應用打斷,內存被清掉重新加載。就需要使用硬盤上緩存,讀寫硬盤緩存比較耗時,需起線程處理
private DiskLruCache mDiskLruCache;
private final Object mDiskCacheLock = new Object();
private boolean mDiskCacheStarting = true;
private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
private static final String DISK_CACHE_SUBDIR = "thumbnails"; @Override
protected void onCreate(Bundle savedInstanceState) {
...
// Initialize memory cache
...
// Initialize disk cache on background thread
File cacheDir = getDiskCacheDir(this, DISK_CACHE_SUBDIR);
new InitDiskCacheTask().execute(cacheDir);
...
} class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
@Override
protected Void doInBackground(File... params) {
synchronized (mDiskCacheLock) {
File cacheDir = params[0];
mDiskLruCache = DiskLruCache.open(cacheDir, DISK_CACHE_SIZE);
mDiskCacheStarting = false; // Finished initialization
mDiskCacheLock.notifyAll(); // Wake any waiting threads
}
return null;
}
} class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
...
// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
final String imageKey = String.valueOf(params[0]); // Check disk cache in background thread
Bitmap bitmap = getBitmapFromDiskCache(imageKey); if (bitmap == null) { // Not found in disk cache
// Process as normal
final Bitmap bitmap = decodeSampledBitmapFromResource(
getResources(), params[0], 100, 100));
} // Add final bitmap to caches
addBitmapToCache(imageKey, bitmap); return bitmap;
}
...
} public void addBitmapToCache(String key, Bitmap bitmap) {
// Add to memory cache as before
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
// Also add to disk cache
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null && mDiskLruCache.get(key) == null) {
mDiskLruCache.put(key, bitmap);
}
}
} public Bitmap getBitmapFromDiskCache(String key) {
synchronized (mDiskCacheLock) {
// Wait while disk cache is started from background thread
while (mDiskCacheStarting) {
try {
mDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mDiskLruCache != null) {
return mDiskLruCache.get(key);
}
}
return null;
} // Creates a unique subdirectory of the designated app cache directory. Tries to use external
// but if not mounted, falls back on internal storage.
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() : context.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}
4.MemoryCache和Fragment結合
private LruCache<String, Bitmap> mMemoryCache;
@Override
protected void onCreate(Bundle savedInstanceState) {
RetainFragment retainFragment =
RetainFragment.findOrCreateRetainFragment(getFragmentManager());
mMemoryCache = retainFragment.mRetainedCache;
if (mMemoryCache == null) {
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
// Initialize cache here as usual
}
retainFragment.mRetainedCache = mMemoryCache;
} } class RetainFragment extends Fragment {
private static final String TAG = "RetainFragment";
public LruCache<String, Bitmap> mRetainedCache;
public RetainFragment() {} public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
if (fragment == null) {
fragment = new RetainFragment();
fm.beginTransaction().add(fragment, TAG).commit();
}
return fragment;
} @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}
Android Training精要(六)如何防止Bitmap对象出现OOM的更多相关文章
- android——获取ImageView上面显示的图片bitmap对象
获取的函数方法为:Bitmap bitmap=imageView.getDrawingCache(); 但是如果只是这样写我们得到的bitmap对象可能为null值,正确的方式为: imageView ...
- Android Training精要(五)讀取Bitmap對象實際的尺寸和類型
讀取Bitmap對象實際的尺寸和類型 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecode ...
- Android Training精要(七)内存管理
在2.3.3及以下版本: 通過定義兩個整形變量來檢測bitmap是否display過或者已經在緩存中 下面的代碼當bitmap滿足兩個條件就被回收掉: 1. 兩個整形變量都變為0 2. bitmap不 ...
- Android Training精要(二)開啟ActionBar的Overlay模式
在3.0上的實現 <resources> <!-- the theme applied to the application or activity --> <style ...
- Android Training精要(一)ActionBar上级菜单导航图标
Navigation Up(ActionBar中的上级菜单导航图标) 在android 4.0中,我们需要自己维护activity之间的父子关系. 导航图标ID为android.R.id.home @ ...
- Android Training精要(四) Intent注意事项
判断有处理Intent的Activity PackageManager packageManager = getPackageManager(); List<ResolveInfo> ac ...
- Android Training精要(三)不同分辨率图片缩放倍数
各DPI图片倍率 xhdpi: 2.0 hdpi: 1.5 mdpi: 1.0 (baseline) ldpi: 0.75 这就意味着如果有一张xhdpi下200*200的图片, 你应该提供同样的图片 ...
- Android特效专辑(六)——仿QQ聊天撒花特效,无形装逼,最为致命
Android特效专辑(六)--仿QQ聊天撒花特效,无形装逼,最为致命 我的关于特效的专辑已经在CSDN上申请了一个专栏--http://blog.csdn.net/column/details/li ...
- Android Training - 管理应用的内存
http://hukai.me/android-training-managing_your_app_memory/ Random Access Memory(RAM)在任何软件开发环境中都是一个很宝 ...
随机推荐
- js 字符串编码转换函数
escape 方法 对 String 对象编码以便它们能在所有计算机上可读, escape(charString) 必选项 charstring 参数是要编码的任意 String 对象或文字. 说明 ...
- 如何用eclipse搭建Android的开发环境
l开发主要应用Eclipse 3.7版本. l辅助工具为jdk.Androidsdk Android环境搭建 –1.1.JDK安装 –1.2.Eclipse安装 –1.3.Android SDK安 ...
- JS操作CSS样式
一.样式表(css) 使用样式表可以更好的显示WEB文档,也可以结合javascript从而实现很好的控制样式表. 样式(css)与内容(html): HTML是处理文档结构的,HTML可以实现如何把 ...
- 20160329javaweb之JSP -cookie入门
一.什么是会话? •会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. 会话过程中要解决的一些问题? •每个用户在使用浏览器与服务器 ...
- Angularjs中使用$location获取url参数时,遇到的坑~~~
今天在开发时候,需要用到Angularjs1.4.6获取url参数,网上查了一下,有部分文章提到用$location来获取.大致方法如下 var app = angular.module('myApp ...
- 学习重点:1、金典的设计模式在实际中应用2、JVM原理3、jui源代码
学习重点:1.金典的设计模式在实际中应用 2.JVM原理 3.jui源代码
- RD / RMDIR Command
Quote from: http://ss64.com/nt/rd.html RD Delete folder(s) Syntax RD pathname RD /S pathname RD /S / ...
- Linux的关机与重启命令
Linux的关机与重启命令 作者: Aillo, 发布于2009-05-10, 在系统分类下, 1条留言. 重启命令:1.reboot2.shutdown -r now 立刻重启(root用户使用)3 ...
- thinkphp 整合 ucenter
http://xcodebox.com/2013/06/8855.html 参考 1 ucenter源码目录下 /advanced/examples/api目录 copy到thinkphp项目根目 ...
- 【实习记】2014-09-26恢复linux下误删的ntfs盘中的文件
情景,ubuntu下把NTFS格式的盘中的“实习记”文件夹彻底删除了,追毁莫及,粗心觉不是一件好的事情. linux下回复ntfs盘下的文件不能用ext3grep,而使用debugfs命令实在 ...