Question

I'm working on an application which has a few Activities. One Activity starts the next one. To share some Values I'm using a custom implementation of Application (I'm talking about android.app.Application) called MyApplication.
As we all know, the Android system kills an app, if it needs more space. But this leads to a problem:

  • I open my app and use it just like any other app
  • I close it (Home Button) and use other apps
  • The system will kill my application because it's wasting memory
  • When I reopen my App, it wants to open the last activity I used and I get a force close, because the values in MyApplication are null

The strange thing is, that the system destroys my Application, but it seems like it keeps the Activity. I don't really understand why this is so because the Application doesn't seem to have a life cycle.

What I want to have:
When MyApplication (whole Application, not only the activity) gets killed, I want the last activities to be killed too. So when I reopen the App, it starts the main acitvity provided by the manifest.xml.
or
The values in MyApplication are persisted and don't get lost if the Application gets destroyed. (I'm talking about a few objects so i think the shared preferences won't work).
I don't want to use a service to bind my activities to, but is there a similar way to tell the system that my last used activity depends on the application-context?

I hope you understand what my problem is and someone can help me out with this.

Was it helpful?

Solution

The right way to do things would be to save your application state. Override the onSaveInstanceState(Bundle savedInstanceState) method to save your state and onRestoreInstanceState to retrieve it.

If you need to save large sets of data consider using a SQL database

OTHER TIPS

You should make sure the app closes and restarts the way you want it to in the onPause() , onResume() and onStop() methods. Check out savedInstanceState which can save the state of the app (and restore it, when it's sent as a parameter to onCreate)

In your custom implementation of Application, add a Flag say :

public boolean appContextExist = false;

On your first Activity set the flag to true,

Override onCreate and onResume method on your Activity which need the contexts, add following :

MyApplication myApp = ((MyApplication) getApplicationContext());
if (!myApp.appContextExist) {
    // Code to return to start activity here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top