Android Life Cycle Description:
Android Activity is the basic building block of an Android App. Android
Activity always has a User Interface. Android apps consist of one or many Activities.
We also saw that to tell Android, which activity to open when the application
is launched, we defined Main Activity in Manifest.xml.
An Android Activity has a Lifecycle during which it performs a
few things. The first question when reading about Lifecycle of Activity
Lifecycle is - Why is it required ? Let's understand it with an example.
Assume you are playing a game on your phone, you are at level 2
and suddenly some one calls you. When you get a call, your games stop and you
see the Caller Id Screen. When you resume your game after the call ends, it
gets resumed from the same point where you left it.
Now assume you are a game developer. For you, there should be a
way to save the game state. Right? How will this happen? To make developer's
life easier, Android has something called Activity Lifecycle.
Consider Lifecycle to be a collection of callback functions getting called
whenever something happens to your application (or Activity to be more
precise).
The Android system is also allowed to recycle
Android components to free up resources. This part explains which for
activities, the lifecycle of other components is described in the respective
part of these components. An activity can be in different states which are
described by the following table.
Methods Of Activity
LifeCycle:
Detail Explanation Of All Activity LifeCycle Methods:
onCreate:
onCreate()
is called when your Activity is getting
created for the first time. It is called only once during the entire Activity
Lifecycle. One of the important things you are supposed to do is to set the
Activity Layout through setContentView function.
Also, you can use onCreate to
initialize your variables. In any Android application, whenever you create an
Activity, the minimum method which you need to override is onCreate.
class MainActivity extends Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
end
If you notice, OnCreate
function is getting passed a variable of class Bundle. Bundle is typically used
to store the state of your Activity. Take the example of screen rotation,
during which your Activity gets killed and OnCreate is called again. You can determine
if the Activity was already there using Bundle so that you do not have to
create the Activity again.
Why is this necessary,
imagine you have a form and user has already filled some of the fields.
Suddenly the user rotates his screen. Using Bundle, Android retains the values
of these fields and re-populates the data after rotation automatically. The
value of Bundle will always be null when Activity is getting created for the
first time.
onStart:
onStart
gets called just before the Activity
becomes visible to the user. If you notice, onStart is called from two places -
after onRestart and OnCreate. onStart is always followed by OnResume or OnStop.
You can use onStart to reset Activity data, reinitialize variables etc.
onResume:
onResume
gets called when your Activity comes into
the foreground, and it becomes visible to the user. At this point, the Activity
is on top of the Activity stack, and the user can start interacting with the
Activity. onResume is typically used to register Listeners, bind to Services
etc.
onResume is a good place to
refresh your UI with any new changes which might have occurred during the
period in which the Activity was not visible. For example, if you are polling a
Service in the background (like checking for new tweets), onResume is a good
place to update your screen with new results.
onPause:
onPause
is called when another android activity
comes on top of your Activity. Typically anything that steals your user away
from your Activity will result in onPause.
In OnPause, we either release
the resources, or save the application data, or stop background threads etc.
It is always guaranteed that
whenever your Activity is becoming invisible or partially invisible, onPause
will be called. But once onPause is called, Android reserves the right to kill
your Activity at any point. Hence you should not be relying on receiving any
further events.
onStop:
onStop
is called when your Activity is no longer
visible to the user, it is similar to onPause but here you will not see your
android activity entirely. You can use this method as well to store the state
of your application and shut down time intensive or CPU intensive operations.
This method is guaranteed to be called as of API level 11.
So what is the difference
between onPause and OnStop ? If an Activity comes into the foreground and fills
the screen such that your current activity is not at all visible, your current
android activity will be called with both onPause and onStop . If, however, an
Activity that comes to foreground does not fill the screen and your current
Activity is partially visible, your current Activity will be called with only
onPause.
Typically whenever you see a
dialog box which requires your attention like battery low, network connection
your current android activity becomes partially visible and popup box comes on
the top. This is the point where only onPause will be called.
onRestart:
It is similar to onCreate,
but
onRestart
gets called only after onStop. This is
the method which you can use to know if your application is starting afresh or
getting restarted.
In onRestart, you will get
your application to save the state and reinitialize all the variables. onStart
gets called after this.
OnDestroy:
This is the method which will
be called when your Activity is getting killed. This is the final call the
Activity will receive in its Lifecycle.
When the user press back
button on any Activity the foreground activity gets destroyed and control will
return to the previous Activity.
But remember the fact, there
is no guaranty that
onDestroy
will be called. Only when the system is
low on resources or user press the back button or if you use finish()
explicitly in your code, onDestroy gets
called.
Even though you should always
use onPause and onStop to clean up resources, release connections etc;
onDestory is there to let your app have the final chance to clean things up
before the Activity cease to exist.
So we have seen the complete
Activity Lifecycle functions. Lets see what are the different states of an
Activity.
Activity
LifeCycle Flow:
In Details When our app launched on the Device or Emulator what all the methods will call.
When
the Activity first time loads the events are called as below:
onCreate()
onStart()
onResume()
When
you click on Phone button the Activity goes to the background
and the below
events are called:
onPause()
onStop()
Exit
the phone dialer and
the below events will be called:
onRestart()
onStart()
onResume()
When
you click the back button OR try to finish() the activity the events are called as
below:
onPause()
onStop()
onDestroy()
Sample Code To Show How all the mothod will execute:
Just Copy The Below Code and see the output in the console how the Activity LifeCycle Methods will Execute.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
String tag = "LifeCycleEvents";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(tag, "In the onCreate() event");
}
public void onStart()
{
super.onStart();
Log.d(tag, "In the onStart() event");
}
public void onRestart()
{
super.onRestart();
Log.d(tag, "In the onRestart() event");
}
public void onResume()
{
super.onResume();
Log.d(tag, "In the onResume() event");
}
public void onPause()
{
super.onPause();
Log.d(tag, "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d(tag, "In the onStop() event");
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag, "In the onDestroy() event");
}
}
Important Activity States in
Android:
These states can be broken into 4 main groups
as follows:
1. Active or Running -
Activities are considered active or running if they are in the foreground, also
known as the top of the activity stack. This is considered the highest priority
activity in Android, and as such will only be killed by the OS in extreme
situations, such as if the activity tries to use more memory than is available
on the device as this could cause the UI to become unresponsive.
2. Paused -
When
the device goes to sleep, or an activity is still visible but partially hidden
by a new, non-full-sized or transparent activity, the activity is considered
paused. Paused activities are still alive, that is, they maintain all state and
member information, and remain attached to the window manager. This is
considered to be the second highest priority activity in Android and, as such,
will only be killed by the OS if killing this activity will satisfy the
resource requirements needed to keep the Active/Running Activity stable and
responsive.
\
3. Stopped/Backgrounded -
Activities
that are completely obscured by another activity are considered stopped or in
the background. Stopped activities still try to retain their state and member
information for as long as possible, but stopped activities are considered to
be the lowest priority of the three states and, as such, the OS will kill
activities in this state first to satisfy the resource requirements of higher
priority activities.
4. Restarted –
It is
possible for an activity that is anywhere from paused to stopped in the
lifecycle to be removed from memory by Android. If the user navigates back to
the activity it must be restarted, restored to its previously saved state, and
then displayed to the user.
No comments:
Post a Comment