【发布时间】:2023-03-20 15:36:01
【问题描述】:
我在 android 中缓存我的图像,但不知道如何重用位图,因为 android 在这里建议: https://developer.android.com/training/displaying-bitmaps/manage-memory.html 这是我的代码
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
this.imageCache= 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;
}
};
this.m_adapter = new ImageScreenAdapter(this, R.layout.imagelist_item, items, imageCache);
setListAdapter(this.m_adapter);
这是我用来下载位图的方法
private Bitmap downloadBitmap(String url, ProgressBar progress, int position) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
if(progress!=null)
{
RemoveImageResults(position);
return null;
}
return BitmapFactory.decodeResource(getResources(), R.drawable.missingpic);
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inDither = true;
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream,null, options);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or
// IllegalStateException
getRequest.abort();
//Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
client.close();
}
}
return null;
}
在我的 AsyncTask 中
@Override
protected void onPostExecute(Bitmap result) {
final Bitmap Image=result;
if(Image!=null)
imageCache.put(imageUrl, Image);
myActivity.runOnUiThread(new Runnable() {
public void run() {
imageView.setImageBitmap(Image);
imageView.setVisibility(View.VISIBLE);
}
});
}
private Bitmap download_Image(String url) {
return downloadBitmap(url, progress, position);
}
但是,如果它在我的列表适配器中获得多达 1000 个图像,这可能会耗尽内存,那么如何重用位图或回收未使用的位图?我的目标是 android 3.0 或更高版本,正如 android 建议的那样,我可以使用 Set> mReusableBitmaps;但我不知道如何实现这一点。
【问题讨论】:
标签: java android caching bitmap out-of-memory