How to prevent call of onDestroy() after onPause()? - android

In my android application I have noticed that on press of back key, after onPause() automatically, onDestroy() is getting called.
How do I prevent the application from calling onDestroy() after onPause()?
I dont want to destroy the instances after back key press.
On press of Back key, my webview object is getting destroyed. So, I am not able to access the webview again,once I press back key.
I have got two URLs. Imagine them as URL1 and URL2.
When I launch URL1 in the webview and press back key the flow is onKeyDown() -> onPause()
When I launch URL2 in the webview and press back key the flow is onKeyDown() -> onPause() -> onDestroy()
Why is there a difference in the behaviour? Has it got anything to do with cookies?
For URL1 -- cookies.isSecure=true;
For URL2 -- cookies.isSecure=false;

Check the declaration of your activity in Manifest. Declare it in such a manner that it can store the data when minimized.
Activity should have the capability to restore the content.

That's how the Activity lifecycle is designed in Android and you should not interfere with it. You app can be destroyed by runtime at any point of time regardless of you want it or not :) So a better approach would be to accommodate the lifecycle in your application's logic.

you can override finish() to avoid this:
#Override
public void finish() {
//super.finish(); // do not call super
moveTaskToBack(true); // move back
}

you can override onBackPressed() in your activity, but that should be the last resort,
get a hang of these links before you start
activity lifecycle
developer blog

Normal android application behaviour states that the Home button hides the app to the background (you'll be shown the home screen), and Back button finishes the application (goes through onPause, onStop, onDestroy, in that order).
If you want to retain instances/states of your application when back button is pressed, I suggest you do the saving in onPause - save the states in SharedPreferences or in a place in your sqlite db. But mind that the saving process should be as quick as possible, because your application will wait until onPause executes completely before exiting.
Then load your instances/states in onResume.

You can know that onDestroy() will be called after onPause() using isFinishing() so you can avoid some code.

The answer here specifies that we have to configure the manifest in such a way that it should not get destroyed, but it does not answer how to configure. I arrived at this post when I had a similar problem for, the solution is pretty simple. Just mention
android:persistent="true"
Reference : - https://developer.android.com/guide/topics/manifest/application-element.html
This should prevent your activity getting destroyed when you click back button
I explained in detail with a use case in another post,
Prevent activity from being destroyed as long as possible
I hope this helps others who arrive at this place for the same problem

Related

Call onDestroy() with menu button but not with back button on closing app in android?

I want that when i close app with back button on device then my thread should
send data to server.
update GPS (lat,long) and get notification(on specific place) means do not call
onDestroy() but when i close app with menu button on device then app should totally
closed and stop all background updation.(means should call onDestroy()).
Please help me ,i am new to android.
Override onBackPressed() in your activity to decide what to do when the back button is pressed. And call finish() from wherever you want to finish your activity. Never call onDestroy() directly.
I think you will have to move your removal code stuff away from onDestroy() to a better place, as you cannot prevent onDestroy() of being invoked by the System when the activity is finished.
Keep in mind that onDestroy will be called if system is low on resources, but not because you closed application. I think the better ways is override onBackPressed in your home activity and implement your logic, what do you want to do when you are closing application.

Want to start a new activity but let the original activity finish first

I have an Android activity we'll call A which has a button and another activity B. When the user clicks the button in Activity A, I'd like to finish A (let both onStop and onDestroy finish running) and then start up the instance of B. When I put a finish() and startActivity() call in the button click listener, the instance of B starts up before the old instance of A finishes. Can someone help me figure out a way to do what I'm looking for?
What you are looking for is not possible and actually is against Android's activity lifecycle implementation.
Correction
It is possible with android:noHistory="true" tag in your manifest, but for what you are trying to do it seems wrong (read the EDIT)... Messing with the activity stack makes a non intuitive application!
Android OS doesn't let you control when activities will be removed from memory (or killed), and therefore all these fancy "Task killers" are so popular (DONT use them, they only make things worse).
When your activity's onStop() is being called, the activity stops completely, and it just hangs in your memory, but that's fine...
If you want to reset the state of activity A, or close the app when exiting activity B, just create a set of rules in both onResume() and onStop(), you can do everything you wish by creating a set of rules in those functions.
for example: have a boolean in activity A that turns true just before calling activity B,call finish() on your activity A's if this boolean is true
I suggest that you take a look at Android's Activity lifecycle diagram, and make sure that everything you do follows the best practice.
EDIT
I saw your comment, it seems like you are trying to create things that are already in your memory, don't recreate them, it's a waste of CPU time, memory, and battery.
Instead, create a static class with a singleton that will hold all your shared data !
I believe you're looking for
onPause()
which is what gets called when the activity is sent to the background. You can do whatever cleanup you want in there. onStop should only be called when a user is exiting out of your program (or launching another one)
onPause is a better place to do this cleanup. See the Saving Persistent State section of the Activity doc.
When an activity's onPause() method is called, it should commit to the backing content provider or file any changes the user has made. This ensures that those changes will be seen by any other activity that is about to run. You will probably want to commit your data even more aggressively at key times during your activity's lifecycle: for example before starting a new activity, before finishing your own activity, when the user switches between input fields, etc.
While I'm not definite that your cleanup is for user changes, the bold sentence above implies that onPause will complete before the next Activity is created. Of course that probably implies that you'll have to move some setup to onResume...
Alternatively, you could move all your cleanup code to a method, let's just call it cleanup and then just call it before you start activity B. You'll have to put in appropriate guards for your onDestroy cleanup too of course.
override finish() method.
implement cleanUp() method.
create boolean isClean=false in the activity
in cleanUp() write your clean up code.
call cleanUp() in your finish()
check for isCleaned in finish() or in cleanUp() if its true then ignore the clean
now before you start B , call cleanUp() and set isCleand=true
after you call B , call finish()
Start activity A
from inside A startService(c) and finsh A
from inside the service , start Activity B

variables retaining values after app close

My app is retaining all of the variable values when it closes and this is effecting how it runs when reopened. Is there any way to reset them all upon app close? or is there a way to clean the app from memory when it is closed so to speak? For the moment I have just been setting all of the important variables "=0" in the last few lines of execution but I know there must be a correct way to doing this.
EDIT:
OK I thought that it would just be easier to reply here instead of individually to everyone.
The app is indeed staying alive in the background, I checked with advanced task killer. How would I get the ap to "Die" by presing the back button? I think this would be the easiest solution given how the app works:
open app > press start button > press stop button > results screen > press back button to exit.
so basically each time the app runs should be an independant execution.
Override the onPause, onResume, and onDestroy methods. onPause should save anything upon pausing, onResume should reload these values when it is resumed, and onDestroy will be called when your app closes. You can clean up stuff in onDestroy. See this link.
You app is probably not closing but remaining in background. Check advanced task manager and see if the app is running or not.
You need to familiarize yourself with the Activity Lifecycle.
You could leverage onResume() to reset your variables; also note onDestory() and onPause().
UPDATE:
Killing the application in its entirety each time the app moves to the background is an anti-pattern. You should really look at your application and follow the aforementioned activity lifecycle pattern and take the needed steps to insure your variables exist as you desire based on state.
I like what #Alex and #Jack said. To add to that, also consider that you can call finish() in your Activity if you want to force it to close up and return to the last Activity. Going along with this, also consider the use of setResult(int) (JavaDoc Here)
You can also set a flag on the Intent when you call the Activity you are questioning about. A flag like FLAG_ACTIVITY_NO_HISTORY could be helpful:
If set, the new activity is not kept in the history stack. As soon as the user navigates away from it, the activity is finished. This may also be set with the noHistory attribute.
List of Intent Flags
Uninitialized variables are bad. Don't do it. ALWAYS manually reset variables before using them for the first time.
the onResume() method will let you reset the variables when the program resumes, but will also do it when you return to the activity unless you add the logic that says you are coming from in the app, not the home page. Maybe onRestart() is what you really need? I'm not positive, but it's possible with onResume.

Interactivity Coordination: onStop and onResume

I have two activities. One loads all rows from a database, and the other saves to the database. When I have the second save in onStop and the first repull the data in onResume, they do it out of order (the first resumes and then the second saves). I managed to fix this by putting the saving data in onPause, but why was this happening? Was this the cleanest way to do it?
Doing the save in the first actvity's onPause should be fine.
You've discovered that the foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time, the activity is in front of all other activities on screen and is interacting with the user.
When you start the second activity, onPause is called on the first and then interactive control switches to the second, with onStop on the first to be called somewhat in background.
This improves responsiveness and gets the new activity in front of the user ASAP. Consequently, you should try to keep your onPause implementation as fast and efficient as possible.
See the following Android docs for more details on the lifecycle http://developer.android.com/guide/topics/fundamentals.html, but what you have found should work fine for you.
Some official quote as an add-on:
The Activity documentation states that
onPause() is where you deal with the user leaving your activity.
Most importantly, any changes made by the user should at this point be
committed

Killing android application on pause

I have an application which I would like to be fully disabled/closed when it is paused (IE. When the user presses the Home, End (call) and Back button I would like the application to be closed, instead of being saved in the history stack).
How do I do this....?
Thanks.
Implement onPause() in your activity and call finish() on your activity. Bear in mind, though, that this will occur on every pause, including dialogs, incoming calls, users activating a Notification. You might want to consider doing finish() in onStop(), which would at least solve the dialog problem.
Also, bear in mind that users will may get confused when using your app, thinking it has crashed since it is gone when they try to get back to it.
you can easily do that by setting true the "noHistory" attribute in to your activity element, in the manifest
http://developer.android.com/guide/topics/manifest/activity-element.html#nohist
You know how you have an OnCreate() method in your activity which performs actions when you start. You need to add something like:
#Override
protected void onPause(){
finish();
super.onPause();
}
in your activity to add actions before it starts
in this case the
finish();
command is what you want to execute before your activity pauses.

Categories

Resources