I spent 4 full days trying everything I can to figure out the memory leak in an app I'm developing, but things stopped making sense a long time ago.
The app I'm developing is of social nature, so think profile Activities (P) and list Activities with data - for example badges (B). You can hop from profile to a badge list to other profiles, to other lists, etc.
So imagine a flow like this P1 -> B1 -> P2 -> B2 -> P3 -> B3, etc. For consistency, I'm loading profiles and badges of the same user, so each P page is the same and so is each B page.
The general gist of the problem is: after navigating for a bit, depending on the size of each page, I get an out-of-memory exception in random places - Bitmaps, Strings, etc - it doesn't seem to be consistent.
After doing everything imaginable to figure out why I am running out of memory, I have come up with nothing. What I don't understand is why Android isn't killing P1, B1, etc if it runs out of memory upon loading and instead crashes. I would expect these earlier activities to die and be resurrected if I ever Back to them via onCreate() and onRestoreInstanceState().
Let alone this - even if I do P1 -> B1 -> Back -> B1 -> Back -> B1, I still get a crash. This indicates some sort of a memory leak, yet even after dumping hprof and using MAT and JProfiler, I can't pinpoint it.
I've disabled loading of images from the web (and increased the test data loaded to make up for it and make the test fair) and made sure the image cache uses SoftReferences. Android actually tries to free up the few SoftReferences it has, but right before it crashes out of memory.
Badge pages get data from the web, load it into an array of EntityData from a BaseAdapter and feed it to a ListView (I'm actually using CommonsWare's excellent MergeAdapter, but in this Badge activity, there is really only 1 adapter anyway, but I wanted to mention this fact either way).
I've gone through the code and was not able to find anything that would leak. I cleared and nulled everything I could find and even System.gc() left and right but still the app crashes.
I still don't understand why inactive activities that are on the stack don't get reaped, and I'd really love to figure that out.
At this point, I'm looking for any hints, advice, solutions... anything that could help.
Thank you.
I still don't understand why inactive activities that are on the stack
don't get reaped, and I'd really love to figure that out.
This is not how things work. The only memory management that impacts activity lifecycle is the global memory across all processes, as Android decides that it is running low on memory and so need to kill background processes to get some back.
If your application is sitting in the foreground starting more and more activities, it is never going into the background, so it will always hit its local process memory limit before the system ever comes close to killing its process. (And when it does kill its process, it will kill the process hosting all the activities, including whatever is currently in the foreground.)
So it sounds to me like your basic problem is: you are letting too many activities run at the same time, and/or each of those activities is holding on to too many resources.
You just need to redesign your navigation to not rely on stacking up an arbitrary number of potentially heavy-weight activities. Unless you do a serious amount of stuff in onStop() (such as calling setContentView() to clear out the activity's view hierarchy and clear variables of whatever else it may be holding on to), you are just going to run out of memory.
You may want to consider using the new Fragment APIs to replace this arbitrary stack of activities with a single activity that more tightly manages its memory. For example if you use the back stack facilities of fragments, when a fragment goes on the back stack and is no longer visible, its onDestroyView() method is called to completely remove its view hierarchy, greatly reducing its footprint.
Now, as far as you crashing in the flow where you press back, go to an activity, press back, go to another activity, etc and never have a deep stack, then yes you just have a leak. This blog post describes how to debug leaks: http://android-developers.blogspot.com/2011/03/memory-analysis-for-android.html
Some tips:
Make sure you are not leak activity context.
Make sure you are don't keep references on bitmaps. Clean all of your ImageView's in Activity#onStop, something like this:
Drawable d = imageView.getDrawable();
if (d != null) d.setCallback(null);
imageView.setImageDrawable(null);
imageView.setBackgroundDrawable(null);
Recycle bitmaps if you don't need them anymore.
If you use memory cache, like memory-lru, make sure it is not using to much memory.
Not only images take alot of memory, make sure you don't keep too much other data in memory. This easily can happens if you have infinite lists in your app. Try to cache data in DataBase.
On android 4.2, there is a bug(stackoverflow#13754876) with hardware acceleration, so if you use hardwareAccelerated=true in your manifest it will leak memory. GLES20DisplayList - keep holding references, even if you did step (2) and no one else is referencing to this bitmap. Here you need:
a) disable hardware acceleration for api 16/17;
or
b) detach view that holding bitmap
For Android 3+ you can try to use android:largeHeap="true" in your AndroidManifest. But it will not solve your memory problems, just postpone them.
If you need, like, infinite navigation, then Fragments - should be your choice. So you will have 1 activity, which will just switch between fragments. This way you will also solve some memory issues, like number 4.
Use Memory Analyzer to find out the cause of your memory leak.
Here is very good video from Google I/O 2011: Memory management for Android Apps
If you dealing with bitmaps this should be a must read: Displaying Bitmaps Efficiently
Bitmaps are often the culprit for memory errors on Android, so that would be a good area to double check.
Are you holding some references to each Activity? AFAIK this is a reason which keeps Android from deleting activities from the stack.
We're you able to reproduce this error on other devices as well? I've experienced some strange behaviour of some android devices depending on the ROM and/or hardware manufacturer.
I think the problem maybe a combination of many factors stated here in the answers are what is giving you problems. Like #Tim said, a (static) reference to an activity or an element in that activity can cause the GC to skip the Activity. Here is the article discussing this facet. I would think the likely issue comes from something keeping the Activity in an "Visible Process" state or higher, which will pretty much guaranty that the Activity and its associated resources never get reclaimed.
I went through the opposite problem a while back with a Service, so that's what got me going on this thought: there is something keeping your Activity high on the process priority list so that it won't be subject to the system GC, such as a reference (#Tim) or a loop (#Alvaro). The loop doesn't need to be an endless or long running item, just something that runs a lot like a recursive method or cascaded loop (or something along those lines).
EDIT: As I understand this, onPause and onStop are called as needed automatically by Android. The methods are there mainly for you to overide so that you can take care of what you need to before the hosting process is stopped (saving variables, manually saving state, etc.); but note that it is clearly stated that onStop (along with onDestroy) may not be called in every case. Additionally, if the hosting process is also hosting an Activity, Service, etc. that has a "Forground" or "Visible" status, the OS might not even look at stopping the process/thread. For example: an Activity and a Service are both luanched in the same process and the Service returns START_STICKY from onStartCommand() the process automatically takes at least a visible status. That might be the key here, try declaring a new proc for the Activity and see if that changes anything. Try adding this line to the declaration of your Activity in the Manifest as: android:process=":proc2" and then run the tests again if your Activity shares a process with anything else. The thought here is that if you've cleaned up your Activity and are pretty sure that the problem is not your Activity then something else is the problem and its time to hunter for that.
Also, I can't remember where I saw it (if I even saw it in the Android docs) but I remember something about a PendingIntentreferencing an Activity may cause an Activity to behave this way.
Here is a link for the onStartCommand() page with some insights on the process non-killing front.
One of the things that really helped the memory issue in my case ended up being setting inPurgeable to true for my Bitmaps. See Why would I ever NOT use BitmapFactory's inPurgeable option? and the answer's discussion for more info.
Dianne Hackborn's answer and our subsequent discussion (also thanks, CommonsWare) helped clarify certain things I was confused about, so thank you for that.
so the only thing i can really think of is if you have a static variable that references directly or indirectly to the context. Even something so much as a reference to part of the application. I'm sure you have already tried it but i will suggest it just in case, try just nulling out ALL of your static variables in the onDestroy() just to make sure the garbage collector gets it
The biggest source of memory leak I have found was caused by some global, high level or long-standing reference to the context. If you are keeping "context" stored in a variable anywhere, you may encounter unpredictable memory leaks.
Try passing getApplicationContext() to anything that needs a Context. You might have a global variable that is holding a reference to your Activities and preventing them from being garbage collected.
I encountered the same problem with you. I was working on a instant messaging app, for the same contact, it is possible to start a ProfileActivity in a ChatActivity, and vice versa.
I just add a string extra into the intent to start another activity, it takes the information of class type of starter activity, and the user id. For example, ProfileActivity starts a ChatActivity, then in ChatActivity.onCreate, I mark the invoker class type 'ProfileActivity' and user id, if it's going to start an Activity, I would check whether it is a 'ProfileActivity' for the user or not. If so, just call 'finish()' and go back to the former ProfileActivity instead of creating a new one.
Memory leak is another thing.
Related
When I do startActivityForResult to take a photo, the underlying Activity is destroyed. Even when I put
android:configChanges="orientation|keyboardHidden|screenSize"
in the manifest, any ideas would be extremely appreciated!
Probably your process is being terminated while your app is in the background. This is perfectly normal and will happen in many other cases, not just this one. You will need to adjust your application to deal with this situation (e.g., use the saved instance state Bundle).
What impact does removing a Fragment in Android have on the performance of an application. What I am referring to is something like:
fragmentTransaction.remove(myFragment);
I've read the documentation about the Fragment Lifecycle Fragments and the description of the remove method in the Fragment Transaction Fragment Transaction remove() but haven't found whether calling the remove actually frees the memory occupied the Fragment's views.
Also, is there a way that I can suspend Fragments into a low memory state? The idea is that in an application with many Fragments and assuming that only one Fragment is visible at a time, is there anything I can do to optimize memory?
Your app should be optimized for best performance from design. It should not change it's behavior upon system resources. If you are low on memory, the background apps are killed so that your app can run smoothly and you user can get the best of it.
Just use a fragment when you need it. And remove it when it's not needed. If you do it the right way, you're already optimizing your app.
I have read the two reasons/issue mentioned on:(Please read two reason on below link)
Android AsyncTask for Long Running Operations
1. "If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die":
Lets suppose i have set the orientation of my activity to Portrait. Will this issue still be there?
2. Memory leak issue:
inner class will hold an invisible reference on its outer class instance : the Activity.
What if i am not using Inner AsyncTask instead created separate class. Also if i use weak reference.
The issues you mention arise only when life-cycle of AsyncTask is not handled properly, mainly from lack of understanding of how they work.
AsyncTask is a wrapper for running code on a separate thread. It is similar to plain Java's Runnable submitted to ExecutorService, with additional features of "pre" and "post" hooks to be run on main thread. So, its basically an enhanced version of Thread, Runnable and Handler setup.
By default AsycTask's share a single thread and hence not advised for long running tasks. Because when a single background thread is shared by many tasks, a long running task may block others. However, AsycTask can also run on a custom Executor, removing such restrictions of a shared worker thread.
All that means that AsyncTask's own design doesn't restrict its usage for long running tasks.
You can have a background Service run some continuous processing using AsyncTasks on a separate ThreadPoolExecutor.
You can have a Fragment load latest news using an AsyncTask and when Fragment's onDestroy() is called, you cancel the task, since its no longer meaningful.
Hence the answer to "how long and AsyncTask should run", entirely depends upon the usage context.
Additional problem of AsyncTask: losing your results.
Yes, you said:
Lets suppose i have set the orientation of my activity to Portrait.
Will this issue still be there?
But, Activity could be recreated not only 'cause rotation. For example, if there is no enough resources in system, operation system can destroy your Activity.
So, for long running operations there is high risk that AsyncTask will have an invalid reference to its Activity in onPostExecute() after Activity recreation.
Another problem: parallelism.
new AsyncTask1().execute();
new AsyncTask2().execute();
Will these two tasks run at the same time or will AsyncTask2 start when AsyncTask1 is finished?
Well... It depends on the API level.
And aboud API level...
Before API 1.6 (Donut): the tasks were executed serially. This means a task won't start before a previous task is finished.
API 1.6 to API 2.3 (Gingerbread): the Android developers team changed AsyncTasks to make possibility to start them in parallel on a separate worker thread.
API 3.0 (Honeycomb): the AsyncTasks where executed serially again. Of course the Android team provided the possibility to let them run parallel. This is done by the method executeOnExecutor(Executor). Check out the API documentation for more information on this.
Setting the orientation will work because locking to portrait means no orientation change, meaning no lifecycle re-creation because of this. However if an activity is paused for a long time it can still be destroyed so this is not a good way to make sure this works 100%. You could instead try a service or a headless fragment.
According to this post, having a weak reference will solve the memory issue
AsyncTask have following drawback.
1. Memory leak :- In inner class as well in seprate class you provide reference of your activity to AsyncTask for callback in both case AsyncTask will not release the reference of activity for GC which cause memory leak.
2. GC :- If a AsyncTask is running although the calling activity is destroyed it will restrict the GC to not run till it will not finish its process.
3. On Orintation change activity recreate as Asynchtask will running in background and when it finish its operation it will try to update UI which cause IllegalStateException as activity is not attached to window.
So its better if you use Service for long running background process instead of AsyncTask.
There are so many superstitions around this topic, it's hard to know where to start. AsyncTask is just a small piece of sugar around a standard task queue, using it or not using it does not make much difference in comparison to other things.
For example the problem of orientation change is NOT real. You can start an AsyncTask when the activity starts for the first time and simply not start it the next time around. (and remember that other changes in configuration can also restart your activity).
The weak references are a total overkill and will probably get you nowhere. You either need a reference to the current activity (and then the weak reference won't work) or not (and then, simply don't hold any reference).
The most important, and missing from your question, is what are you actually trying to accomplish?
Think about someone answering their phone while your application is running, and going back to it after some time. And then try to answer questions like:
- are the results from 15 minutes ago relevant? Or will the task be restarted?
- how about 6 hours ago?
- will something bad happen if the background task is interrupted?
- does user expect the task to be finished? (did he press "OK" and just waited for a confirmation to appear?).
And then you can ask a more precise question. AsyncTask can be used in any scenario, but usually it's simpler not to use it than to use it correctly.
For android I am trying persist state if onDestroy() is called. I'm wondering what are common design patterns used to do such a thing so that the actual app functionality is decoupled from the persistence functionality? For example, I have a for loop that iterates through all of the players in the game. This update happens at the end of each round in the game. Would it be possible that the app gets destroyed half way through the update? If that happened, what kind of logic would i need to include to remember which player was updated.
You have two main options for saving state. If you are concerned with instance variables, then override Activity.onSaveInstanceState The answer to this question provides a good sample of how to do this.
For persistent data, you can either store it in SharedPreferences, the SQLite database, or write it to a file. This article should help you get started: http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState
Your app can be killed half way during the update if users switch to another app such as receiving a phone call.
Considering such cases, you may need to persist your state in onPause() instead of onDestroy() since onPause() is the last method which is guaranted to be called when your activity is killed by the system.
And in onPause(), you can start a background service to do the update which can give your process higher priority so that it's less likely to be killed by the system when you are doing the update.
See more details in the Activity lifecycle and the Process document.
Android is not very nice about killing apps. You may or may not get onPause or onDestory. You may or may not be able to receive a hook onShutdown of the VM. Basically your app can die at any time (low memory pressure), user kills it, or etc and you won't get any warning. Basically it is best practice to assume that you can die at ANY time and store or update critical state as soon as you get it.
Basically I would either make a SQLitedatabase or use shared preferences for this.
Is there some sort of onTerminate() method where I can do some cleanup (I want to clear some SharedPreferences) when my Android app is terminating?
I have an Activity that is keeping a running average of a few numbers, that I'm storing in a SharedPreference. I want this average to last while the app is running (the user can move between different activities) so I can't clear it on onDestroy() for that particular activity. I need to be able to clear it once the app is about to quit.
How can I do this?
I've not tried this, but here's what I would do:
As Alex mentioned in the comment to original question, use a Service to share the app-wide state between Activities.
Whenever you move between Activities, bind to the service from the "new" activity, and unbind from the "old" one. Check this to understand how to coordinate activities.
If you follow this properly, you can ensure that at least one Activity is always bound to the Service as long as your app is running; and that all Activities are unbound when the app is no longer running - at which point your service's onDestroy() is called. This is where you perform your cleanup.
So android doesn't really have a concept of an app being "finished". Unfortunently there is nothing synonymous to "onTerminate()". Is there some criteria by which you can decide when to clear your running average?
Use SharedPreference.Editor to remove the preferences, and commit. Here's a link for you: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html