How to prevent Out of memory error in LRU Caching android

六月ゝ 毕业季﹏ 提交于 2019-12-03 08:59:10

If your app uses android:largeheap="true",

Never use Runtime.getRuntime().maxMemory() as you will most likely use more memory than availabe and OOM more often, instead use the memory class and calculate the size of the cache as follows:

    /** Default proportion of available heap to use for the cache */
    final int DEFAULT_CACHE_SIZE_PROPORTION = 8;

    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    int memoryClass = manager.getMemoryClass();
    int memoryClassInKilobytes = memoryClass * 1024;
    int cacheSize = memoryClassInKilobytes / DEFAULT_CACHE_SIZE_PROPORTION;
    bitmapHashMap = new LruCache<String, Bitmap>(cacheSize)
Jorgesys

Out of Memory Exception is caused when bitmaps exceeds the virtual memory available, a good practice is the Recycle of bitmaps.

  bitmap.recycle();

Read more here

When should I recycle a bitmap using LRUCache?

a question answered by Mr. Mark Murphy.

Have you follow these guide ? http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html This is a good tutorial to know how to implement storage of bitmaps.

you should have to clear cache and download again when you got Exception . Check below function to clear cache when memory exceeds

    private Bitmap getBitmap(String url)
            {
     File f=fileCache.getFile(url);
     //from SD cache
    Bitmap b = decodeFile(f);
    if(b!=null)
        return b;

    //from web
    try {
        Bitmap bitmap=null;
      //  URL imageUrl = new URL(url);

        /***/

        HttpURLConnection conn = null;
        URL imageUrl = new URL(url);
        if (imageUrl.getProtocol().toLowerCase().equals("https")) {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) imageUrl.openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        } else {
            conn = (HttpURLConnection) imageUrl.openConnection();
        }
        /***/



       // HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex){
       ex.printStackTrace();
       if(ex instanceof OutOfMemoryError)
           memoryCache.clear();
       return null;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!