I have an activity in whose onCreate method an Init function is called (the function calls some native code involving lot of stuffs and calls to the openSLES audio api). The point is that this Init function makes the app crash when called again, which happens on a screen rotation or when i close the activity using Back button and i launch it again (but if in the meanwhile the process is killed, i have no troubles). I can’t change the beaviour of the Init function.
I see that the process isn’t killed when the activity is destroyed, I expected this after reading the docs, and it’s a good thing since – if there is some audio signal playing – that continues playing after the activity has been destroyed, which is good for my purposes.
I tried to perform a check on the initialization state using onSaveInstanceState, but that works well only on screen-rotation, that’s when onSaveInstanceState is called. The callback is not called when i push the Back button.
So i tried to use Shared Preferences, performing the state saving in onPause. But at this point i have the opposite problem: if the process is killed, the Shared Preferences values are kept, but in that case i need to perform Init again for the app to work properly.
I guess i need a way to know for sure if my activity is created after a process kill or not, but at the moment i can’t see how. I thought about using the bundle instance in onPause method, but i can’t figure how and whether this is possible. Any kind of hint would be really appreciated.
There’s a simple solution to this problem. You don’t need to save things in SharedPreferences to accomplish this. Just use a static (class) variable. Like this:
The variable
initializedwill be set to false when the class is loaded. Only once. In your code, you then check and set the variable like this:Even if all your activities are finished, if the OS doesn’t kill your process the variable
initializedwill still be “true” if the application is started again. Once the OS kills the process, the variable will be set to “false” the next time the application is started and a new process is created.