Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Application's state when application is out of stack due to Memory constrain

Please help me to resolve this problem.

1 > I am having application which Uses Service to retrieve data from server.
2 > Now on Pressing Home key and i have opened new application..
3 > I have opened around 20 application.
4 > So my application might go out of memory stack.
5 > now i am resuming my application, application crashes as i am opening activity of my
    application which is not in the stack.

Is there anyway by which i can handle this exception and redirect my activity to Homepage or relaunch application resume and is not in stack...

like image 938
Rakesh Gondaliya Avatar asked Dec 30 '10 07:12

Rakesh Gondaliya


1 Answers

Indeed a very good question which I try to puzzle out myself.

I even wonder What's the difference between killing an app and restarting the phone.
If a user manually kills an app or opens 20 other apps, he'd probably want the app to start from the beginning. Why Android aren't restoring state after phone restart?

Also, I see that when an app is killed (by the system), global variables turn to null upon activity reinitiating. This kind of breaks the concept of Java. If you have some kind of state in the application and the application erases it, I would expect the application to restart.

The solution I propose:

1. Handle the case of a state problem: Initiate a simple state (new Object()) as a global variable. For each Activity, in the methods onCreate/Start/Resume check that the state is null. If it's null launch the first activity with 'Intent.FLAG_ACTIVITY_CLEAR_TOP' - as if the application is relaunched.
 2. Try not to use global variables - Always put data in the intent.
 3. Lazy load global variables - If you do want to use global data, don't count on one time initialization. Lazy load them 'if (A.MY_DATA == null) {A.MY_DATA = new ...}' - Don't forget to do it in the background if it will take a long time (AsyncTask). Loading partial state needs to be done carefully because it may not comply to other loaded state objects.

The downside of the first point is that the state problem handling needs to be done on every Activity (AOP is not yet implemented in Android).

Hope that helped.

like image 128
AlikElzin-kilaka Avatar answered Oct 09 '22 13:10

AlikElzin-kilaka