Keep activity in paused state - Android - android

I have an application with 3 tabs with one activity per tab. When I am switching between first two activities, the activity, which is going to background passes the onPause() state, while the new one becomes active and onResume() is called. That’s good, because both activities have a complex UI and rendering them takes 2-3 seconds, but when they are kept in paused state, they are resumed quickly.
But when I click on the 3rd tab, then the application behavior is different, the activity, which is going to background, is completely destroyed (it passes onPause(), onStop() and onDestroy()).
Any idea why there is difference in behavior? Is there a way to force the activity to remain in a paused state when user switches to another activity within the application?
Thanks
STeN

This behaviour can even be different on another device or in any other context (different amount of available memory, etc).
You have the guarantee that
onResume() is called when an Activity is going foreground
onPause() is called when the Activity is going background,
and this is the only guarantee you have. (More details on the Activity lifecycle here).
So you can make absolutely no assumption about the calling of onStop() and onDestroy(). They may be called or not each time you are switching from a tab to another, and your application needs being able to handle this.

The reason why the first activity is destroyed may be caused by the lack of heap memory. If Android is running out of memory it kills background activities. This behaviour cannot be influenced by the developer since the whole system would slow down and crash if there's not enough memory left to keeps things going.

Related

How can we guarantee that onPause will be called?

Going of this question
android save game state in onPause or onDestroy?
The answer highlighted that the person asking the question should save game state in onPause because the onDestroy documentation says "There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away." In these situations, how can we ensure onPause will be called? Is it possible to control what methods are called in these situations? Seems unpredictable
onPause will be called every time your activity leaves the screen, before it is finished or if something overlays your activity that keeps the user from interacting with your activity.
You don't need to worry that onPause is not called.
For more information look into the starting and stopping activity training or the Lifecycle Api Docs
You should save temporary instance state in onSaveInstanceState(). This method recieves a Bundle parameter which you can use to write state to. The Bundle is then sent to onCreate() when your app is restarted.
If you need to save instance state more permanently, then save it to a database or SharedPreferences. According to http://developer.android.com/training/basics/activity-lifecycle/stopping.html, you should use onStop() for more CPU-intensive operations rather than onPause(). I don't think you need to worry about onPause() being called in normal use cases. As far as I can tell, it is guaranteed. (Of course, there are always catastrophic failures, such as the user pulling out the battery of the device, but there's not much you can do about that.)
It's almost certain that onPause() will always be called. The reasoning is that it's highly unlikely the "system" will aggressively kill an active (i.e., visible) Activity.
In order to free resources, the Android OS effectively reserves the right to kill dormant processes - in particular ones that have been long-running but not recently used. In order for your Activity (and its process) to qualify for this, at some point you must have sent the Activity to a background state, e.g., pressed HOME or started another app's Activity. The simple fact your Activity is no longer visible means it will have been paused and onPause() will have been called. It's almost certain that the Activity will have been stopped and onStop() will have also been called.
What you have to remember is Android has been around for a while now and early devices had RAM measured in 100s of MB and the system behaviour possibilities and documentation reflects this. More recent devices have RAM measured in GB (even 10s of GB) so unless a user really pushes their device to the limitations of its resources, aggressive clean-up of app processes becomes less likely.
You can show Dialog for User to Act Accordingly.When Dialog will be opened to ask user that he wants to quit or not,Activity will definitely call onPause() and at this time you can write your game state saving code. Its better to write code on onPause() because at onDestroy() resources are freed by os.

Is it safe to do all cleaning up in onDestroy?

More concretely: Is it safe to place the canceling of a task in onDestroy? Also, is it safe to use onDestroy for unregistering receivers and freeing up resources?
My aim is to make sure that my task is canceled/destroyed when the Activity is destroyed, but not before.
onDestroy():
is called when the activity is destroyed and resources must be
released.
is NOT called when the activity is destroyed in a hurry (when the
system is low on resources etc).
The first case is clear: I do all cleaning in onDestroy and no problems arise. The second case is a bit of a problem though. When the Activity is destroyed and onDestroy is skipped (so I don't cancel my task), could it happen that the task continues execution, then completes and tries to update the dead Activity, so the app crashes?
We come to the real question:
When an Activity is killed and onDestroy is skipped, is everything attached to that Activity automatically destroyed? (Is onDestroy skipped only in case that everything will be wiped out altogether? Tasks, registered receivers etc)
If onDestroy is skipped does this mean that the whole app is being killed?
Let's focus on onDestroy(), because the solution is not in onPause() or onStop(). Arguments:
onStop() could be skipped when the Activity is being destroyed, just like onDestroy
onPause is called too early and too often, so it is not appropriate for the use case. Examples:
Screen lock: onPause can be called when the device screen is locked. Very often this happens like a screensaver and the user unlocks immediately because he is standing there looking at the screen. Canceling tasks and stopping everything my app is doing in such a case will only degrade user experience. I don't want my app to choke and misbehave just because of an incidental "screensaver".
In an example app I have two screens that are Activities. The user can quickly switch between them. In this app users tend to switch screens often and quickly.
Navigation: One of the screens has a map which receives location updates from the system. It records a precise graphical log of the changes in location (route), so it needs to run constantly until the Activity is closed. Normally I would register and unregister any receivers in onResume and onPause. However, this would make the app very unusable, as the updates on the map will stop every time the user navigates away. Therefore, I would like to unregister the receivers in onDestroy.
Loading list: The second screen has a list that shows data from a webservice. It takes 4 seconds to download the data. I use an AsyncTask and I know I should cancel when necessary. It should not be canceled in onPause, because it should continue loading while the user switches between screens. Therefore, I would like to cancel it in onDestroy.
There can be many more examples. Some of them might not be totally appropriate in everyone's opinion (you might even suggest using a service instead of AsyncTask). But the idea is important, and all of them have the same idea: keep on doing work that's specific to the Activity, while the Activity is paused, but ENSURE to stop doing it when the Activity is destroyed. (It does not matter whether I am using an AsyncTask or a Service. In either case, the work should be stopped when the Activity is destroyed.)
P.S. If the answer is that it is not safe to do the clean up in onDestroy, this would mean that the Android framework requires us to stop everything we are doing in onPause. And then I would not see any reason for using onDestroy...
I would like to refer you to this baby: http://developer.android.com/reference/android/content/ComponentCallbacks2.html#onTrimMemory(int)
Essentially it gives you all the places where the system finds it useful to cancel tasks and clean its memory:
Please take a closer looks at the following 2 cases:
TRIM_MEMORY_UI_HIDDEN - the process had been showing a user interface, and is no longer doing so.
TRIM_MEMORY_COMPLETE - the process is nearing the end of the background LRU list.
Which are the cases for most of what you asked.
In the same method you can also catch TRIM_MEMORY_RUNNING_CRITICAL which will alert you to a case where the system has no memory and special actions must be taken immediately.
This method has made my development life much better in similar cases.
If you just need to do some cleanup, no matter how the activity is closed, you should be able to use a combination of onSaveInstanceState() and onDestroy(). One of those should be called no matter what. Maybe have a boolean cleanupDone in your activity, which is set whenever one of the two finishes.
Concerning saving of user data, have a look at Saving Persistent State:
Google suggest a
"edit in place" user model
That is: save as soon as the user creates new data, at the latest in onPause(). This does not mean that you need to recreate the data in onResume(), just that it should have been saved.
By the way: onStop() can be skipped only on pre-Honeycomb devices, that is, as of June 2015, less than 6 % of all devices. Still, onSaveInstanceState() should be called if either onDestroy() or onStop() are omitted.
As far as I gone with android,
1 When your apps crashes every resource relevant to it are destroyed.
2 When the device changes configuration resulting the Activity to be destroyed and recreated.
3 When apps running in background and Android kill it due to running on Low Memory
apart from these the other callback method are called i e
1 when another Activity come in front , or your device locks ..etc
In all case according to your requirement you can release all your resources in onDestroy and cancel the Thread and Asyntask and stop all the services etc .if you want your task remain paused and alive while on destroy called then you can save the configuration and retain it while onCreate is called again by check is null or not.

Android destroying activities, killing processes

Hi I'm wondering how Android is managing memory and I can't find precise answer anywhere.
Let's assume I have an application with 5 activities on current activity stack (4 are stopped and 1 is resumed), there is no service connected. I press HOME button so that all of my activities are stopped.
I start some other memory consuming application and overall device memory is starting to be low. And the question is
... What will happen to my application?
Can system destroy only one or some of my activities to recover memory?
Will system kill the whole process of my application? Will all activities be nicely destroyed?
What will happen when I get back to my application when it was totally killed? Will it start from beggining (like the first start) or will it try to recover activities to previeous state / if yes - is it only the one on the top of the stack or all of them?
UPDATE:
Before asking this question I've seen Activity lifecycle a few times but it doesn't have answers to my questions.
I made some tests and I have some answers. "Stop process" in DDMS was a clue for testing.
I haven't tested answer for question 1, but as guide says:
If an activity is paused or stopped, the system can drop the activity
from memory by either asking it to finish, or simply killing its
process.
It seems that one or more of the activities can be destroyed gently(with onDestroy method) without killing the process. You will simply get (onCreate + bundle) when getting back to them.
Question 2 answer:
YES. Generally system kills the whole process this means all data including activities and static fields are destroyed. This is NOT done nicely - you won't get onDestroy or finialize() for any of your paused/stopped activities. This is why saveInstanceState() is called just before onPause method. onPause is basically the last method where you should save something because after this method you could never see onStop or onDestroy. System can just kill the process destroying all of your objects whatever they hold and whatever they are doing.
Question 3 answer:
What will happen when you get back to a killed application?
Prior to Android 2.2 - application will start from the beggining, with launcher activity.
Starting from 2.2 - system will restore the previous application state. What does it mean? It means that last visible activity will be recreated (onCreate + bundle). What will happen with activity stack? Stack is fine but all activities on it are dead. Each of them will be recreated (onCreate + bundle) when you get back to it with back button.
There is one more thing about that:
Normally, the system clears a task (removes all activities from the
stack above the root activity) in certain situations when the user
re-selects that task from the home screen. Typically, this is done if
the user hasn't visited the task for a certain amount of time, such as
30 minutes.
Conclusion?
Don't think that handling activity rotation problems can be solved
by android:configChanges="orientation". When you do that you will
get many other problems that you are not even aware of.
Test your application with DDMS - Stop process button. See This
Be careful when using static variables. Don't think that when you initialized them in activity 1 - you will have them initialized in activity 2. The only safe place to initialize global statics would be Application class.
Remember that you may never see onStop or onDestroy. Close files/databases, stop downloaders in onPause. When you want app to do something in BG - use foreground Service.
That would be it ... Hope I helped with my essey :)
First please have a look at this:
onPause() Called when the system is about to start resuming a
previous activity. This is typically used to commit unsaved changes to
persistent data, stop animations and other things that may be
consuming CPU, etc. Implementations of this method must be very quick
because the next activity will not be resumed until this method
returns. Followed by either onResume() if the activity returns back to
the front, or onStop() if it becomes invisible to the user.
onStop() Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this
one. This may happen either because a new activity is being started,
an existing one is being brought in front of this one, or this one is
being destroyed. Followed by either onRestart() if this activity is
coming back to interact with the user, or onDestroy() if this activity
is going away.
So, when you press "HOME" button on your device, your current foreground activity is put onto onPause() then onStop(), the other 4 should remain onStop()
According to Google's Documents:
If an activity in the foreground of the screen (at the top of the stack), it is active or running.
If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your
activity), it is paused. A paused activity is completely alive (it
maintains all state and member information and remains attached to the
window manager), but can be killed by the system in extreme low memory
situations.
If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however,
it is no longer visible to the user so its window is hidden and it
will often be killed by the system when memory is needed elsewhere.
If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing
its process. When it is displayed again to the user, it must be
completely restarted and restored to its previous state.
And, for the process lifecycle:
Process Lifecycle 3. A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so
the system may safely kill its process to reclaim memory for other
foreground or visible processes. If its process needs to be killed,
when the user navigates back to the activity (making it visible on the
screen again), its onCreate(Bundle) method will be called with the
savedInstanceState it had previously supplied in
onSaveInstanceState(Bundle) so that it can restart itself in the same
state as the user last left it.
All the quotes above are come from: Android Developers Reference: Activity
It is confirmed that the system can destroy non-acitve activities and recycle memories when you launched some memory consuming applications. And you can implement like: isFinishing() in your activity and then using "kill" button in DDMS to detect which of your activities is being dropped by system. But I guess the system will destroy the oldest one first. However it is no point to keep other activities when the "Launch Activity" has been recycled.
UPDATE
Here's some opinions I found from here:
Stopped state
When an activity is not visible, but still in memory, we say it’s in a
stopped state. Stopped activity could be brought back to the front to
become a Running activity again. Or, it could be destroyed and removed
from memory.
The system keeps activities around in a stopped state because it is
likely that the user will still want to get back to those activities
some time soon, and restarting a stopped activity is far cheaper than
starting an activity from scratch. That is because we already have all
the objects loaded in memory and simply have to bring it all up to the
foreground.
Stopped activities can be removed from memory at any point.
Can system destroy only one or some of my activities to recover
memory?
Yes. Android kills activities which are running in the background when there is a need for memory. Killing one or all might depend on some conditions. For an instance paused or stopped can make android kill an activity or a process itself. Here under Activity Lifecycle you can get the below points. I recommend you to go through that page completely. It will definitely clear your doubts.
If an activity has lost focus but is still visible (that is, a new
non-full-sized or transparent activity has focus on top of your
activity), it is paused. A paused activity is completely alive (it
maintains all state and member information and remains attached to the
window manager), but can be killed by the system in extreme low memory
situations.
If an activity is completely obscured by another activity,
it is stopped. It still retains all state and member information,
however, it is no longer visible to the user so its window is hidden
and it will often be killed by the system when memory is needed
elsewhere.
If an activity is paused or stopped, the system can drop
the activity from memory by either asking it to finish, or simply
killing its process. When it is displayed again to the user, it must
be completely restarted and restored to its previous state.
Will system kill the whole process of my application? Will all
activities be nicely destroyed?
Activity pertains to an individual whereas process pertains to group of activities. Look at the third point above again it kills the process as mentioned.
What will happen when I get back to my application when it was totally
killed?
Its similar to restart . Again the third point will give you some answers like When it is displayed again to the user, it must be completely restarted and restored to its previous state
Get some more information about memory related stuffs here.
Edit:
All activities in an application runs in a single process. So when a process is killed all the activities no matter 5 or 10 will be killed i.e., restarted. Restart will cause your application to start from a beginning no saved states.

Android life cycle: Explanation for state transitions

I want to discuss the Android life cycle. I know the basics of how the Android life cycle works but there are some questions I want to ask.
Why don't Android apps move from running to stop directly why it first goes through the pause phase ?
Why don't Android apps move from Running to Destroy directly like IPhone apps? Why does it move from Pause->Stopped->Destroy why not Running->Destroy ?
Apps are not immediately destroyed mainly for performance reasons. From the Android Developer Activity Reference:
The Android system attempts to keep application process around for as
long as possible, but eventually will need to remove old processes
when memory runs low.
If the screen is still powered on and there's no pressing need for your device to free up memory, for example, it's obviously faster for the user if the activity is simply paused instead of completely destroyed. Multiple end lifecycle stages make this possible.
The various callbacks indicate different things. This allows you to separate your cleanup functions into the quick, critical items (disconnecting from system resources like a database or network connection) vs. the longer term tasks (persisting user data across launches of your application, for instance). Because your activity is kept around as long as possible, you can avoid the expensive operations when the user is just pausing the activity momentarily.
onPause() is the first callback, indicating your activity is no longer in the foreground. An app will be paused if a dialog appears or if the user pushes the Home button, for instance. If the app is paused for a dialog, for example, you wouldn't want it to be destroyed because it's still visible.
If you also receive onStop(), it indicates your activity is no longer visible. At this point the user no longer sees what you are displaying. This could mean the user opened another application, for example. Even at this point, however, the system may still keep your activity around to make it quicker for the user to return to it later. (If you/the user ended the activity, however, then it will not be kept and will proceed with the end lifecycle callbacks.)
onDestroy() is the final callback before the activity is destroyed. Note that in extreme cases, the system may destroy your activity without calling this method.

Android multitaksing

I am seeking short characteristic of Android Multitasking. I have found, that when you minimize Android application, it is ended and it's process remains on the background. When user wants to reuse his app, this process alive it's application. User will be at the same state, when he left (if there was enough memory while working with it), or it will be loaded from scratch, because there was no free RAM for other work and Android exited this process. Am I right? Everywhere there are articles with 20 pages and more about Android multitaksing. I need to know key points because I am lost in a such long artices.
Thanks
Short Answer: Yes. If your app can live in memory despite being 'closed' then it will stay in RAM and processing will continue when you click on it again. Otherwise it will be restarted and you will get an onResume().
Long Answer: Please just read the Activity Lifecycle:
When Android activity is covered by other windows it will enter into paused state and method onPause will be called. It may also me destroyed by OS and then onDestroy will be called. You have very little control over it and can't expect your application to come back up with the same state. However, when activity is brought up again to foreground in will go through steps of onCreate and onPause. Those methods can be used to restore its state.
Here you can find nice diagrams describing Activity lifecycle. Similar but slightly different lifecycle is applicable to service.
http://developer.android.com/reference/android/app/Activity.html
Android activities are the main visible screens that user see while the application is running. If you close the screen or switch to another application, the current activity is put to hibernate and you can save the state with
Activity.onSaveInstanceState(Bundle bundle)
After your activity gets the control back, you can restore the state with
Activity.onRestoreInstanceState(Bundle bundle)
Note that you need to be careful not to store any context references within the activities and related classes as the activity and thus context has changed between pause and resume. Instead, you should always pass the current activity as the active context to avoid having exceptions from invalid context.

Categories

Resources