My activity simply displays an image:
public class PhotoFrameActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File externalStorageDir = Environment.getExternalStorageDirectory();
File picturesDir = new File(externalStorageDir, "DCIM/Camera");
File[] files = picturesDir.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".jpg");
}});
List<File> photoFiles = Arrays.asList(files);
if (!photoFiles.isEmpty()) {
try {
Bitmap currentPhoto = BitmapFactory.decodeStream(new FileInputStream(photoFiles.get(3)));
ImageView view = (ImageView) findViewById(R.id.photo);
view.setImageBitmap(currentPhoto);
} catch (FileNotFoundException e) {
Log.e("SHOWPIC", "Could not find photo", e);
}
}
}
}
If the activity is restarted, memory is not reclaimed. i.e. if I turn the phone twice I get the following FC:
10-01 17:29:06.011: ERROR/AndroidRuntime(8446): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
10-01 17:29:06.011: ERROR/AndroidRuntime(8446): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
10-01 17:29:06.011: ERROR/AndroidRuntime(8446): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:470)
10-01 17:29:06.011: ERROR/AndroidRuntime(8446): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:525)
10-01 17:29:06.011: ERROR/AndroidRuntime(8446): at net.badgerhunt.photoframe.PhotoFrameActivity.onCreate(PhotoFrameActivity.java:34)
How am I leaking?
As Yashwanth Kumar suggested, it’s NOT due to your image being too large. Even if you reduce the sample size you will still (eventually) get an OOM. The memory leak you have will not get fixed by reducing sample size.
It seems you have a memory leak. Either you can go on a memory leak hunt and try to find the root of your problem, or you could just override the ondestroy method of your activity and do
This will make sure your bitmap gets recycled and the memory gets freed when you activity is being destroyed(as in the case of orientation switch). I would however advice you to watch this video and eventually finding the root to your leak: http://www.google.com/events/io/2011/sessions/memory-management-for-android-apps.html