0

If my phone sleeps or I leave my app to send a text/take a call my app restarts. How do I prevent this?

I wish to save objects rather than basic data types. I don't need to save the apps current state/data if the app is closed or the phone is switched off, although I'm prepared to do this if necessary.

Declan McKenna
  • 4,321
  • 6
  • 54
  • 72

2 Answers2

1

You need to save any temporary state variables in your main activity when onSaveInstanceState(Bundle outState) is called. This is called by whenever your app has a possibility of being destroyed by the OS. In your onCreate(Bundle savedInstanceState), if savedInstanceState is not null, then it means your activity was previously terminated and you need to repopulate your temporary state variables from that bundle.

This is why your main Activity is "restarting", because onCreate is getting called again when your main Activity resumes after being killed, but it's not loading the data from the bundle to recreate the state to when the app was paused.

This is described in more detail here: http://developer.android.com/reference/android/app/Activity.html

triad
  • 20,407
  • 13
  • 45
  • 50
0

Override this method to save your object

@Override
public Object onRetainNonConfigurationInstance() 
{
  if (myObject != null) // Check that the object exists
      return(myObject);
  return super.onRetainNonConfigurationInstance();
}

Use this code within your onCreate() method to reload your object.

if (getLastNonConfigurationInstance() != null)
    {
      table = (Table)getLastNonConfigurationInstance();

This will save your object if your phones shuts your app off to save memory or your phone sleeps. Pressing back/closing your object will not save it. You can either prompt the user to press the home button instead or press the back button again to quit using onBackPressed() or use SQL to permanently store the data within your object.

Declan McKenna
  • 4,321
  • 6
  • 54
  • 72