Hi We are facing a strange issue in our android application. In our app we are storing all needed objects/data in a Common object(called as object A) when we start the app(First Activity). We stored the context itself in that object. Whenever we need context in our app we are getting the context from object A and using it. All the cases its working fine except below cases.
i) While our app is in background, we played some high end games. Now we went back to the app via minimized screen(recent apps). Suddenly the app is crashed.
ii) If we do force stop the app via Settings, and came back to the app via minimized screen the same crash happens.
Both the cases, Object A becomes null(it might be removed by GC), so all operations dependent on object A getting exceptions.
Why is it happening? How do we prevent GC from collecting object A? How can we deal with the force stop? Please give any ideas.
Why is it happening?
Other apps need memory to run as well. It is unreasonable to assume that Android will keep your data in memory indefinitely.
How do we prevent GC from collecting object A?
Don't. Find a different solution to your problem.
How can we deal with the force stop? Please give any ideas.
In the end, the decision is up to you, but here are a few common options:
The second option obviously won't work for your Context, but I would probably architect a different solution for the Context anyway.
You better use the application context for that!
Simply use getApplicationContext()
in your Activity
and use this instead.
Otherwise your activity leaks as soon as the system needs memory.
Your Activity gets in the background when pressing home, when then playing videoGames or memory consuming apps, your activity gets freed by the system.
Try to understand the Activity Lifecycle to solve this:
Furthermore when seeing it in "normal" java your Wrapped object for the activity gets collected by the GC
as soon as its eligable for it, i.e. it isnt referenced by any other objects anymore. This can't be prevented if your whole app gets freed when the system needs memory.
Try to check for null in onResume()
and re-instantiate your Object again!
I hope this may help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With