facebook tricks for image handling in android
DESCRIPTION
One of the hardest parts of writing an Android application is dealing with images. They take up a lot of memory, and are a leading cause of crashes and slowdowns. This talk goes into the architecture of Android’s image processing libraries and how they have evolved over the years. It presents the different options available in the API for better image handling – bitmap recycling and pooling most prominently. I then go into more detail into work currently underway at Facebook to improve image handling. I discuss some poorly documented features in the Android SDK and NDK that offer keys to faster and safer image handling.TRANSCRIPT
Tips and Tricks for handling images in Android
Tyrone NicholasSoftware Engineer8 May 2014
Memory is Scarce
▪~ 1/10 device RAM
▪480 x 800 = 1.5 MB
java.lang.OutOfMemoryError
Android’s solutions
Android heaps
Dalvik
▪JDK
▪Limited
▪Slow
▪Safe
Other
▪Certain system calls
▪Like native
Native
▪NDK
▪Unlimited
▪Fast
▪Unsafe
Put bitmaps in the native heap!
Bitmap.java:
Called from Bitmap.createBitmap()
▪ Eliminated in Android 3.0
Android’s Solution #1
Android’s Solution #2 Need memory
?
Look for unpinne
d memory
Free it
Ashmem
• ashmem_create_region
• ashmem_pin_region
• ashmem_unpin_region
Android’s Solution #2
Draw Allocate Pin Decod
e
Stop drawing
Unpin
Purgeable bitmaps
Android’s Solution #2Howto
Android’s “Solution” #2 • Er, wait a minute…
Android’s Solution #3Bitmap pooling
▪ When doing a decode, specify an old Bitmap object to re-use
Android’s Solution #3Hang on…
Our solution
From the Android NDK…Screw purging. Just screw it.
How to do it (1)
How to do it (2)
Docs can lie
Without a GC…
Caveats• When are you ‘done’ with an image?
• Application-specific
• Nontrivial
• Scrolling
• Caches
ListViews and GridViews
• Beware of flickering!
Other tips
An Image Pipeline
RequestMemoryCacheRead
DiskCacheRead
Network
DiskCacheWrite
Decode
MemoryCacheWrite
Render Transform
WebP
BMP
BMP JPG
JPG
JPG
UI thread Non-UI threads
Using native memory“Naïve native”
• Can’t use for decodes!
▪Devices suck. Servers don’t
▪Consider
Resizing, scaling, and cropping
(c) 2009 Facebook, Inc. or its licensors. "Facebook" is a registered trademark of Facebook, Inc.. All rights reserved. 1.0