0
我緩存我的圖片Android和不知道如何重複使用位圖作爲Android的建議在這裏: https://developer.android.com/training/displaying-bitmaps/manage-memory.html 這裏是我的代碼的OutOfMemoryError位圖的Android
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;但我不遵循如何實現這一點。
它的工作方式是將圖像緩存到設備的硬內存中,然後當它們沒有被查看一段時間後再回收它們,然後它從設備中獲取它們或互聯網時,再次需要圖像。 –
圖像緩存在設備上的某個地方?該庫具有不同的配置,因此您可以將其設置爲將設備上的圖像保存在設備上,但不能使用該設備。我很確定你必須告訴它將圖像存儲在設備上,當你不使用默認行爲時,是使用默認設置中給定的分配數量的運行時內存,所以它的圖像可能會進入並被回收,因爲它們沒有更多房間。 –
這似乎像一個魅力工作,讓我繼續測試它 – Jake