Understanding Android Activity Lifecycle (Part Four)

1. when the user close the application forcefully
2. when Android it self destroy the Activity.
3. when user hits the back button

Unfortunately you can not distinguish between 1 and 2.

But you can do something when user clicks the back button since onPause() is called after onBackPressed(),
so you can put a flag in the onBackPressed(). That way you can distinguish how it landed here

onBackPressed() -> onPause() or

home button / multitask button -> onPause()

Enjoy 🙂

Understanding Android Activity Lifecycle (Part Two)

Enough is enough no more coding, we will read lots of texts today yeeee. Today we will learn when we will save application state, data etc.

Activity Lifecycle

Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity — the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.

An activity has essentially four states:

1. If an activity in the foreground of the screen (at the top of the stack), it is active or running.

2. 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.

3. 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.

4. 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.

please read the bold text carefully. The documentation itself self explanatory.

ok, now lets read more documentations

There are three key loops you may be interested in monitoring within your activity:

1. The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of “global” state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().

2. The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.

3. 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 and interacting with the user. An activity can frequently go between the resumed and paused states — for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered — so the code in these methods should be fairly lightweight.

Great is that as simple as it says, no the story does not end here….
onCreate() —> No
onRestart() —> No
onStart() —> No
onResume() —> NO
onPause() —> Pre-HONEYCOMB ( < 3.0)
onStop() —> YES
onDestroy() —> YES

read some more !!!

Note the "Killable" column in the above table — for those methods that are marked as being killable, after that method returns the process hosting the activity may killed by the system at any time without another line of its code being executed. Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

observations: hmm moral of the story is onStop(), onDestroy() and onSaveInstanceState(Bundle) are very dangerous methods, because its not the choice of a developer to decide or control these methods. These three methods are handled by android OS, sometimes these methods are called sometimes not. So the answer is onPause().

And for the last time read some more documentation

Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate()). The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that match the new device configuration.

To properly handle a restart, it is important that your activity restores its previous state through the normal Activity lifecycle, in which Android calls onSaveInstanceState() before it destroys your activity so that you can save data about the application state. You can then restore the state during onCreate() or onRestoreInstanceState().

Action: App icon clicked (screen orientation is vertical, portrait)
activity A onCreate
activity A onStart
activity A onResume

Action: Rotates the screen (screen orientation is horizontal, landscape)
activity A onPause
activity A onSaveInstanceState
activity A onStop
activity A onDestroy
activity A onCreate
activity A onStart
activity A onRestoreInstanceState
activity A onResume

Action: Rotates the screen (screen orientation is back to vertical, portrait)

activity A onPause
activity A onSaveInstanceState
activity A onStop
activity A onDestroy
activity A onCreate
activity A onStart
activity A onRestoreInstanceState
activity A onResume

If you want to stop this, use these codes

                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

“Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity’s Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.”

observations: so use onSaveInstanceState() to save data and onCreate() to retrieve when user changes screen orientation, not when you are going from Activity A to B (calling intent) or going back from B to A (pressing back button), for that use onPause() to save and onResume() to restore data. And for home and multitask button i think we should use the second method, because the documentation says not much about this.

Source: http://developer.android.com/reference/android/app/Activity.html



How to Finish an Android Activity

Suppose you have two Activity

Activity A and Activity B

You want to navigate A to B and also want finish the previous Activity (in this case Activity A).
put this code inside your Activity A

A.this.finish(); // Activity_Name.this.finish(); 

So where you will put that line, well then you have to understand the life cycle of an Android Activity.


So i guess now you know, where you should put that line.

	protected void onPause() {

Special case: If you just put it like this, with out any checking, than your app will not act like normally, because in screen rotation onPause() is also called. So as a result your app will finish when user rotates the screen.

	protected void onPause() {
        // put some logic here 

enjoy 🙂

Well i edited the solution, it seems finishing the Activity in onStop() creates unknown bug like it calls the onDestroy() later, which creates serious bug in the code. So i move it to onPause() and its working great, thanks to Jamael Tanveer Vaia 🙂