Understanding Android Activity Lifecycle (Part Three)

Today i am gonna ask a question and later we will try to answer that :p

Observations: Well we understood that when we hit the home or multitask button, the current Activity goes to background, but before going to background it called onPause() method for sure.

Question 1: Unfortunately this method also gets called

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

So curious minds want to know, how can i distinguishes among them.

coming soon
Understanding Android Activity Lifecycle (Part Four)

Enjoy 🙂

Advertisements

Android Time Class

Get Old Month Using Time Class

// Author: Mahbub

/*
http://developer.android.com/reference/android/text/format/Time.html

just provide the month, year and day and get previous dates

Since Time class does not provides months and day name, you have to do that by yourself
*/

public void oldDate(int month, int year, int day) {
    
    --month;

    oldDay = 1; // here i did not vary the old months date

    String s;
    
    for (int i = 1; i <= 5; ++i) { // i am fetching last 5 month data
        
        if (month == -1) {
            month = 11;
            year = year - 1;
        }

        oldYear = year;
        oldMonth = month;
        
        Time old = new Time();
        old.set(oldDay, oldMonth, oldYear);
        s = "Month of "+old.month+ +old.year;
        
        // update
        --month;
    }
}



https://gist.github.com/lifeparticle/7139069

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….
Killable?
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

<activity
          
            android:configChanges="orientation|screenSize"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity

“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

http://developer.android.com//guide/topics/resources/runtime-changes.html

Enjoy!

Understanding Android Activity Lifecycle (Part One)

Hello lets talk about Android Activity life cycle hmm.
We know there are three buttons in android phone at bottom Back, Home, and Multitask.

There are seven methods to control android activity life cycle

onCreate()
onRestart()
onStart()
onResume()
onPause()
onStop()
onDestroy()

An Application which have only one Activity and life is beautiful.

Action: App icon clicked

In the onCreate() method
In the onStart() method
In the onResume() method

Action: Home Button clicked

In the onPause() method
In the onStop() method

we can retrieve the activity in two way

case 1:
Action: Multitask Button clicked, we selected our app

In the onRestart() method
In the onStart() method
In the onResume() method

case 2:
Action: App icon clicked

In the onRestart() method
In the onStart() method
In the onResume() method

Action: Back button clicked

In the onPause() method
In the onStop() method
In the onDestroy() method

observations: we can clearly say that onCreate() method is called once when the activity first started and onDestroy() is also called once when the activity is killed (android removes the activity from the memory). But when we pressed the home button or multitask button android sends the activity in the background (the activity still there in the memory). After that we can bring the activity in the foreground by clicking the app icon or from multitask button. well its not as easy as it seems. Later i will discuss more about multiple activity.

activity_lifecycle

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

Download Source Code

Enjoy !