Merge "Don't recycle bitmaps we don't own" into oc-dr1-dev
am: bc907cf9a8

Change-Id: Ib5533fdbcfba36fc1ed82e0089cc681e73a02f05
diff --git a/core/java/android/app/WallpaperColors.java b/core/java/android/app/WallpaperColors.java
index b9d3e75..d0791cf 100644
--- a/core/java/android/app/WallpaperColors.java
+++ b/core/java/android/app/WallpaperColors.java
@@ -136,12 +136,12 @@
         }
 
         final int bitmapArea = bitmap.getWidth() * bitmap.getHeight();
+        boolean shouldRecycle = false;
         if (bitmapArea > MAX_WALLPAPER_EXTRACTION_AREA) {
+            shouldRecycle = true;
             Size optimalSize = calculateOptimalSize(bitmap.getWidth(), bitmap.getHeight());
-            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, optimalSize.getWidth(),
+            bitmap = Bitmap.createScaledBitmap(bitmap, optimalSize.getWidth(),
                     optimalSize.getHeight(), true /* filter */);
-            bitmap.recycle();
-            bitmap = scaledBitmap;
         }
 
         final Palette palette = Palette
@@ -181,6 +181,11 @@
         }
 
         int hints = calculateHints(bitmap);
+
+        if (shouldRecycle) {
+            bitmap.recycle();
+        }
+
         return new WallpaperColors(primary, secondary, tertiary, hints);
     }
 
diff --git a/tests/Internal/src/android/app/WallpaperColorsTest.java b/tests/Internal/src/android/app/WallpaperColorsTest.java
index 5bbd82b..fb529b9 100644
--- a/tests/Internal/src/android/app/WallpaperColorsTest.java
+++ b/tests/Internal/src/android/app/WallpaperColorsTest.java
@@ -77,4 +77,16 @@
         Assert.assertFalse("Light surface shouldn't support dark text "
                 + "when it contains dark pixels", supportsDarkText);
     }
+
+    /**
+     * WallpaperColors should not recycle bitmaps that it didn't create.
+     */
+    @Test
+    public void wallpaperRecycleBitmapTest() {
+        Bitmap image = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888);
+        WallpaperColors.fromBitmap(image);
+        Canvas canvas = new Canvas();
+        // This would crash:
+        canvas.drawBitmap(image, 0, 0, new Paint());
+    }
 }