Clicking back button in android does not save the phonegap application state

458 Views Asked by At

I have an app where use can start and play an audio and see the lyrics scrolling.

If the back button on android phone is clicked, the application state is not saved. I would like to stop the application in that state and continue from there when the user comes back.

I would like to pause the audio and stop the scroll.

How can I achieve this ?

The application works fine if I get an incoming call. The audio stops. So does the scroll which depends on the audio state.

Application is built using phonegap via backbone, zepto.

1

There are 1 best solutions below

3
On

I wouldn't mess with that if I were you. Users expect that using the back button will close the application. Changing that also means that people can't regularly close the application (unless they do it with the app manager) People can press the "home" button for that exact funtionality. You'll have to edit the code that gets executed when the app is in or comes back from a "pause" state.

Check this question for more information about that. I'll just place some of the information from that answer here: @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. savedInstanceState.putBoolean("MyBoolean", true); }

You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:

This gets executed when you leave the app (home button).

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("MyBoolean", true);
  savedInstanceState.putDouble("myDouble", 1.9);
  savedInstanceState.putInt("MyInt", 1);
  savedInstanceState.putString("MyString", "Welcome back to Android");
  // etc.
}

When you get back to the app this will get executed.

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
}