OSDN Git Service

Displaying Bitmaps Efficiently Training - Change memory calculation
authorAdam Koch <akoch@google.com>
Fri, 11 Jan 2013 21:53:37 +0000 (16:53 -0500)
committerAdam Koch <akoch@google.com>
Fri, 11 Jan 2013 21:53:37 +0000 (16:53 -0500)
When calculating memory cache size, use Runtime.maxMemory() instead
of getMemoryClass() which is a more accurate value of available VM
heap size.

Bug: 7988323
Change-Id: Iaa9681a11aad5cad3857dfe76f0b8e4811b2243c

docs/downloads/training/BitmapFun.zip
docs/html/training/displaying-bitmaps/cache-bitmap.jd

index c4ea7aa..882ce03 100644 (file)
Binary files a/docs/downloads/training/BitmapFun.zip and b/docs/downloads/training/BitmapFun.zip differ
index 2a333cc..417ec5b 100644 (file)
@@ -101,19 +101,20 @@ private LruCache&lt;String, Bitmap&gt; mMemoryCache;
 &#64;Override
 protected void onCreate(Bundle savedInstanceState) {
     ...
-    // Get memory class of this device, exceeding this amount will throw an
-    // OutOfMemory exception.
-    final int memClass = ((ActivityManager) context.getSystemService(
-            Context.ACTIVITY_SERVICE)).getMemoryClass();
+    // 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 = 1024 * 1024 * memClass / 8;
+    final int cacheSize = maxMemory / 8;
 
     mMemoryCache = new LruCache&lt;String, Bitmap&gt;(cacheSize) {
         &#64;Override
         protected int sizeOf(String key, Bitmap bitmap) {
-            // The cache size will be measured in bytes rather than number of items.
-            return bitmap.getByteCount();
+            // The cache size will be measured in kilobytes rather than
+            // number of items.
+            return bitmap.getByteCount() / 1024;
         }
     };
     ...