Search code examples
animationout-of-memoryimage-scalingandroid-2.1-eclair

Out of memory error when reloading activity several times


I am developping an app that has a main activity showing the app title (two animated imageviews overlayed), two animated pictures, also overlayed, and three buttons. This activity also has a background image, which is the same that is used by the other activities.

The app flows from one activity to another and, eventually, this main activity is launched again (with the FLAG_ACTIVITY_CLEAR_TOP). Everything works fine but, after reloading it several times, an Out Of Memory error happens on my Android 2.1 device.

At first, I had all the images in the drawable folder and the problem appeared after reaching the main activity 5 times. Then, I adjusted the bitmap sizes and put them in the approppriate folders depending on the density and the problem appeared after reaching the main activity 14 times. Now, I just removed the background image for test purposes and the Out Of Memory appears after more than 20 re-launches.

Also, if I press the Home button and then switch back to my app, the problem seems not to appear until much later.

Moreover, I tested the app in a Nexus 5 and the Out Of Memory never happens.

So... is that a problem with my phone? with Android 2.1?

Thanks!

[EDIT] I think that I have located the problem but, still, strange behavior.

For example, at one point, I need to recreate the activity. As the "recreate" method is not available for my min API level (7), I do it as follows:

Intent refresh = new Intent(getActivity(), getActivity().getClass());
refresh.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(refresh);  

Which, I think, is correct. I release the onClickListeners and clear the animations in onStop(). However, if I put a breakpoint in onStop(), it is not called when I expect it to happen. Sometimes it is called as soon as the activity is recreated but sometimes it is called several seconds later.

However, if I press the Home button, onStop is properly called and when I switch back to the application everything works fine.


Solution

  • The easiest solution is to add in manifest under application tag

    android:largeHeap="true" 
    

    But this is won't solve your problem, just delay it to a few more rounds This link will help you to analyze your application and see what cause this: http://blogs.innovationm.com/android-out-of-memory-error-causes-solution-and-best-practices/

    My Guess this is related to images because i had this issue also.. The android official link to this problem is: http://developer.android.com/training/displaying-bitmaps/index.html

    This the link that helped me.. Try it out http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

    Hope that helps