Possible Duplicate:
State of variables inside an Android activity
If android OS kills my application (which uses service ) due to low memory, then it will try to run it again. From android.developers site:
**Note this means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. If this happens, the system will later try to restart the service. **
If i have in my main activity code like this:
public static MainActivity mainAct;
protected void onCreate(Bundle savedInstanceState)
{mainAct = this;}
When android OS kills my application value of mainAct is lost, because its initialized only onCreate() in activity not in service.
How to “save” that object so it will retain value if my app is killed due to low memory?
You can implement the onDestroy() method in your service to persist some application state to the device. So, when the services onStartCommand() method is call you can check your persisted state (if it exists) and start your application again from that point.
For example, if you have a news feed app that pulls articles from different sources you can write your state to the file before you start the download to say something like:
So if your application fails completely because someone pulled the battery out then you have a known state to resume from. Likewise, if Andoid calls your onDestroy() method to terminate your service you can persist a state to the device in the same way. Then when your service starts back up you have the state that you can read from the file and load into your “object” to use again.
You are not restricted to just files. As @wtstang02 mentioned you can also use a database.