Tuesday, May 8, 2012

Prevent Android activity from being recreated on turning screen off

How to prevent an activity from being recreated on turning screen off?



What I do





  1. Start Bejewels and go to the jewelry screen.

  2. Press power button shortly. The screen is turned off, but the device is not.

  3. Press power button again.




What I see




The same screen as before turning screen off.




In case of my application (trivial one, just a web-app with a single WebView) the scenario is the following:



What I do





  1. Start my app. The activity onCreate() method loads an URL into the WebView.

  2. Press power button shortly. The screen is turned off, but the device is not.

  3. Press power button again.




What I see




The WebView is reloading the page.




What I expected




As in Bejewels case I want to see the same screen, that for my app is the page in its previous state: scripts are running, a form fields are
filled etc.




The debugging showed, that I was wrong (in a previous question) and onDestroy() and onCreate() are being called one-by-one when the screen is just turned on. And since I still hear a music, played by a script, when the screen is off, it looks like both the activity and the WebView do exist all that time.



What I tried.




  1. android:alwaysRetainTaskState="true" The same behavior.

  2. Reading about intents (to no avail, I just did not understand, how they are applied to my situation).

  3. Using PhoneGap. It behaves differently: just killed the whole application on pressing power button. This IS better, but not the best.





No comments:

Post a Comment