I am sporadically getting an OutOfMemoryError: (Heap Size=49187KB, Allocated=41957KB)
in one of my apps. What can I do to diagnose this?
01-09
This may happen if the bitmap resource is not disposed correctly. It is better to read the dimensions to see if it fits the memory. http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
Try using the appropiate context: For example since a Toast can be seen in many activities instead of in just one, use getApplicationContext()
for toasts, and since services can keep running even though an activity has ended start a service with:
Intent myService = new Intent(getApplicationContext(), MyService.class)
Use this table as a quick guide for what context is appropiate:
Original article on context here.
For example I have an intentService that use google location service api. And I forgot to call googleApiClient.disconnect();
:
//Disconnect from API onDestroy()
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, GoogleLocationService.this);
googleApiClient.disconnect();
}
If you are using square's library Picasso I found I was leaking memory by not using the .fit()
, that drastically reduced my memory footprint from 50MB in average to less than 19MB:
Picasso.with(ActivityExample.this) //Activity context
.load(object.getImageUrl())
.fit() //This avoided the OutOfMemoryError
.centerCrop() //makes image to not stretch
.into(imageView);
java.util.Observer
(Observer pattern):Make sure to to use deleteObserver(observer);