Application starts with 86% memory usage(HeapSize) - android

I'm developing application for Android(Xamarin). At current moment is like prototype(inside nothing heavy).
I added app7compat support library and also implemented toolbar with navigation Drawer Layout.
I make some test on real device(Samsung Galaxy S4 Active) and it's an like glitch/bug,because when application started,android device monitor showing this :
How that is possible? My activity contains:
Toolbar(with Drawer layout)
Some different controls,like imageView and imageButtons
As i said,that comes from start(i mean that this 86% used memory allocated with strange items,because there is no computing logic).
Why this happens? Thanks!

As guys explained for me,that is ok,because from start application eats 86% of allocated memory(after that if needed, will grow up).
Anothers tip was,to put flag largeHeap and via RunTime(),to see how much memory can be allocated:
Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory/1024/1024));
and my result(Samsung Galaxy S4 Active) was :
512MB
Hope that helps!

Related

WebView eating up too much memory

In my app there are two activities viz A and B.
Activity A:
It has a list which displays information about an item briefly. When an item on A is clicked, it loads Activity B.
Activity B:
It has two web views and several listviews. Top of the activity is occupied by header web view. Lower part of activity has tab host, this hosts the second web view in first tab and remaining tab each hosts a list view.
Problem:
When user navigates from A to B, the heap size increases significantly. Even after I navigate back from B to A, heap size continues to be the same. There is not even a byte decrease, in fact it increases sometimes. Yes its because of these web views. I have read about web view memory leaks on SO and other sites. I followed approach mentioned here
Added web view dynamically inside a container[RelativeLayout]. Removed webview on activities onDestroy
Sub classed web view as suggested in the SO article
Cleared web view cache every time etc
No matter what heap size does not come back to what it was before navigating to B.
Really appreciate if someone can guide me to a possible fix
Note:
I have already read this and followed this issue on SO.
Memory leak in WebView
Edit:
I have tried without web views in B and the increase in heap size is very very less around 0.5 MB but with web views it creases by 4-5 MB
Heap size logs ( got by following suggestion mentioned here )
onCreate B
debug.heap native: allocated 4.11MB of 4.17MB (0.01MB free) in []
debug.memory: allocated: 12.00MB of 96.00MB (1.00MB free)
onDestroy B
debug.heap native: allocated 8.66MB of 10.08MB (0.48MB free) in []
debug.memory: allocated: 12.00MB of 96.00MB (1.00MB free)
on Resume A
debug.heap native: allocated 7.94MB of 10.08MB (1.32MB free) in []
debug.memory: allocated: 12.00MB of 96.00MB (0.00MB free)
I cross checked the numbers by taking heap dump before and after B is started and destoryed, heap size are quite close to the one I get it in logs
I followed series of steps and got the memory footprint reduced. This is what I did,
instead of creating webview statically via xml I now create webview programmatically and add it to a container. Once webview is no longer needed I remove the webview from the container then I remove all views from webview and call destroy on it. Eventually memory allocated reduces.
private void releaseWebView() {
webViewContainerRelView.removeAllViews();
if(mWebView != null){
mWebView.setTag(null);
mWebView.clearHistory();
mWebView.removeAllViews();
mWebView.clearView();
mWebView.destroy();
mWebView = null;
}
}
I call releaseWebView() from onDetachedFromWindow method of Activity as below.
#Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
releaseWebViews();
}

Possible bug in dalvik of Android 2.x during Bitmap allocation?

The phenomenon: First do allocation some big memory blocks in the Java side until we catche OutOfMemoryError, then free them all. Now, weird things happen: load even a small picture(e.g. width:200, height:200) by BitmapFactory.decodeXXX(decodeResource, decodeFile, ...) will throw an OutOfMemoryError! But its OK to alloc any pure Java big Object(e.g. new byte[2*1024*1024]) now!
Verifying: I wrote some simple codes to verify the problem that can download here, press "Alloc" button many times and you will got an OOF Error, then press "Free All", now the environment is set up. Now you can press "LoadBitmap" and you will see its not work on most of Android 2.x phone.(But in the emulator its just OK, odd)
Digging deeper: I try to dig into some dalvik code to find out why, and find a possible bug in function externalAllocPossible in HeapSource.c which called by dvmTrackExternalAllocation who print the "xxx-byte external allocation too large for this process" messages in LogCat.
In externalAllocPossible it simply wrote:
if (currentHeapSize + hs->externalBytesAllocated + n <=
heap->absoluteMaxSize)
{
return true;
}
return false;
Which means once if the native Bitmap allocation size plus the currentHeapSize(NOT the actually allocated size as shown below, in this case, it's keeping the max size of the heap we bumped up but then freed them all) exceeds the limits, native Bitmap allocation will always fail, but the currentHeapSize in Java seems NOT decrease even when 91.3% Java objects' memory have been freed(set to null and trigger GC)!
Is there anybody else met this problem too?
I think this is correct. Its forcing the entire app (Java+native) take no more than a certain amount of memory from the OS. To do this it has to use the current heap size, because that amount of memory is still allocated to the app (it is not returned to the OS when freed by GC, only returned to the application's memory pool).
At any rate, 2.x is long dead so they're not going to fix it there. They did change how bitmaps store their memory in 3.x and 4.x. Your best bet is to allocate all the bitmaps you use first, then allocate those large structures. Or better yet- throw those large structures into a fixed size LRUCache, and don't use the grow until out of memory idea, instead load new data only when needed.
The class Bitmap has the recycle() method, described as:
Free the native object associated with this bitmap...
The reason behind this method is that there are two heaps: the Java heap and the heap used by native code. The GC only sees the Java heap sizes; for GC, a bitmap may look as a small object because it's size on the Java heap is small, despite the fact that it references a large memory block in the native heap.

Android Heap Memory size doesn't looks correct

i have an Android app that displays alot of images, it works, the images are gatherd from an url, added to a que and gathered by 4 threads,stored in a cache and then displayed in a listview view 4 images for row, there are abot six rows at each time on the screen. There is a total of usually 90 images.
The rows(and imageviews) are always recycled, so the amount of items is always the same and i'm not initializing anything.
This seems to work quite fine, i have always an average used heap size of 13MB.
The problem i have is that at the beginning mi max heap size is quite small and i get GC messages like:
01-20 16:48:39.191: D/dalvikvm(9743): GC_FOR_ALLOC freed <1K, 31% free 12048K/17351K, paused 25ms
but the more i scroll up down the view the heap size grows more and more untile i get things like
01-20 17:02:05.339: D/dalvikvm(11730): GC_FOR_ALLOC freed 544K, 72% free 13871K/49159K, paused 35ms
as you see even if the used is the same the maximum is increased even if i never got to that limit. and the true problem is that at this point i start to get outofmemory errors.
Can someone explain me what's wrong?
Thanks!
What version of Android are you using? If you're testing on pre 3.0 (ie 2.x), the byte arrays that store most of the information in Bitmaps are allocated and stored in native memory. This means that in heap dumps and in the GC notifications, you only see the small amount of memory used for pointers in Bitmaps, rather than the actual size.
For more information check out this google IO talk on memory management and detecting memory leaks: http://www.youtube.com/watch?v=_CruQY55HOk
Also I've worked on several apps doing similar things. My guess is that either your cache size is way too large, or (more likely) the images you're displaying and storing in the cache are much larger than the size you actually want. If you display a bitmap in an image view, the imageview will store the original bitmap in memory, even if it is significantly larger than what would actually fit in the view. Try resizing the images from disk to at least closer to the appropriate size before trying to display them: How do I scale a streaming bitmap in-place without reading the whole image first?
To cache my Images I use Map<String, Drawable> drawableMap. On a OutOfMemoryError I call this function:
private void cacheLeeren()
{
int size = drawableMap.size();
int del = (int) (size * 0.3);
Set<String> s = drawableMap.keySet();
for (String t : s)
{
if (del >= 0)
{
drawableMap.put(t, null);
del--;
}
}
}
I think it's not the best way...but it works ;-)
My guess is that your app reaches a very high peak of memory usage for a short time. It's true that on average you only use 13MB but if your heap grows to as much as 50MB, it means that momentarily you've consumed much more memory than you're thinking.
Let's try to figure out where this is happening. You've mentioned that you're using an LRU cache. This cache frees memory as soon as it fills up. My guess is that you're starting to free memory too late, and this memory isn't freed immediately - since it depends on the system GC. Whenever you're freeing some items from the cache, try to call System.gc() manually.
You've also mentioned that you're calling Bitmap.recycle(). To the best of my knowledge this is useless on Android 3+ because the native heap is no longer used for bitmaps. Since all bitmaps are on the dalvik heap, they will be freed by the GC.. You can't rush this like before unless you call System.GC() yourself.
Another idea for your source of problems is heap fragmentation. See my previous SO answer to a similar issue in this question.

Android: Out of memory (VM budget...) on startup, on small percent of total installs

I get a clasical "VM budget excedees memory - out of memory" type error crash report from the Android Market.
I checked the app for memory leaks over and over again. This error happens on a very small percent of total application installs, around 1-2% and it always happens on start-up. The app loads some bitmaps from internal memory for each activity, but does not crash on most devices. I thought all applications had a guaranteed minimum stack size for bitmaps so this should work for every device. Min SDK is 7.
Any reason why ? Does this sound familiar to anyone ?
I had quite a similar problem, and my images were simply too big for some devices.
I have read that you have one image per Activity and I guess this happens when switching from one to another as the newly allocated Drawable cannot fit. What you could do, to save some memory, would be to unload the background image of the Activities that are not shown:
#Override
protected void onResume() {
super.onResume();
Drawable d = loadMyDrawableFromDisk();
setBackgroundDrawable(d);
}
#Override
protected void onPause {
setBackgroundDrawable(null);
super.onPause();
}
It may help as the memory will be freed a few after onPause() is called, and not when the underlying View of your Activity will be unallocated by the system.

Determining available heap space for Activity (preventing OutOfMemoryException)

I've read How do I discover memory usage of my application in Android? and a bunch of other answers, but can't quite nail this down...
I have an Activity that will load a file from external storage into memory and do some parsing/manipulation/etc in-memory. Before I load it I want to guess whether or not doing so will cause an OutOfMemoryException and crash the Activity (I understand that exact answers aren't possible, an estimate is better than nothing.)
From the above-linked answer, I came up with:
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
int pid [] = {android.os.Process.myPid()};
android.os.Debug.MemoryInfo[] mi = activityManager.getProcessMemoryInfo(pid);
// calculate total_bytes_used using mi...
long available_bytes = activityManager.getMemoryClass()*1024*1024 - total_bytes_used;
So, the questions:
1) am I crazy?
2) how to total the values from the MemoryInfo object to estimate the heap usage of the activity/task? (The above link gives an overview of pss/private-dirty/shared-dirty, but not enough info to guess how to do the total.)
3) does Debug always exist or only when debugging?
4) is there a smarter way?
Answers like these: Two questions about max heap sizes and available memory in android seem to imply that there isn't a better way than this?
I know that using less memory is a good thing, and I am. I'm interested to know how to code defensively, here. Seems weird to just wait for an exception to know that you're out of memory.
Thanks!
you may refer to this link.. A complete reserach on the same problem you are facing.
OOMRESEACH

Categories

Resources