Tuesday, April 20, 2010

Activity in Android

As I had noted in the previous post, Android app can be built of four components and Activity is the most crucial one. Well you can term an activity in Android as a UI  screen. So an application can have more than one activity. All activities are derived from the class Activity.
An Activity is made up of a views. These views are placed in a hierarchy with content View at the root of it.A view in simpler words are controls for android.
To launch an activity, we need to use Intents.An intent is like a message envelope. Its used to pass information or parameters to the activity. The Android API for launching an activity is Context.startActivity(Intent intent) or Activity.startActivityForResult(Intent  intent, int requestCode). The activity being launched, can call its getIntent() method to get the intent information.One activity often starts the next one. startActivityForResult() is called when we expect some return information from the activity, like some choice that the user has made. The result is obtained by calling onActivityResult(int requestCode, int resultCode, Intent data) method of the Activity.

To shut an activity down, you need to call  finish(). An activity started by another one by using startActivityForResult() can be shut by calling finishActivity().

But for an activity, its not just start and stop. There are several states that an activity can go through. It can be active(running and visible on the screen), paused ( visible to user, but in the background) and stopped(not running and currently all resources on the device are taken over by another activity). The following chart explains things more clearly.
activity_lifecycle

So as clear from the above chart, the three states are monitored by the seven functions which are
1. onCreate() - Called when the activity is created
2. onStart() - Called just before the activity is made visible to the user
3. onResume() - Called just before activity starts interacting
4. onPause() - Called when currently running activity needs to be paused and other activity comes into focus.
5. onStop() - When an activity is no longer visible to the user, either because current one is going to be destoyed or another one has gained complete focus.
6. onDestroy() - Called before activity is destroyed.
7. onRestart() - Called just before an activity, previously stopped is going to be started.

This is as far as fundamentals of activity are concerned, but this is by no means complete of Activity. More on this in the next few posts

No comments:

Post a Comment