Prevent Android activity from being recreated on turning screen off

activity-lifecycle, android-activity, android-intent, lifecycle, lifetime

Solution

- Create the view in Application.onCreate().

- Add the view to a layout in Activity.onCreate().

- Remove the view from the layout in Activity.onDestroy().

Details are here: Attach/detach Android view to/from layout

Problem

How to prevent an activity from being recreated on turning screen off? What I do - Start Bejewels and go to the jewelry screen. - Press power button shortly. The screen is turned off, but the device is not. - 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 - Start my app. The activity onCreate() method loads an URL into the WebView. - Press power button shortly. The screen is turned off, but the device is not. - 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. 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 until I press power button again. What I tried. - android:alwaysRetainTaskState="true" The same behavior. - Reading about intents (to no avail, I just did not understand, how they are applied to my situation). - Using PhoneGap. It behaves differently: just kills the whole application on pressing power button. This IS better, but not the best.

Original source

Related problems