Saturday, July 16, 2016

Android Activity & Lifecycle

Android Activity is a user interface screen where visual elements called Views (Widgets such as TextView, EditText, Button etc.) are present and can perform some action on getting users input.


We have already discussed in Android Application Components post that Android Activity can be created by two ways, by Java Code or by XML Code and we mostly use XML method to create a Activity interface, for this we have to just drag and drop components from Palette (You can read more about palette in Starting with Android Studio Post)

An android application can have any no. of Activity but one out of these must be declared as launcher activity, You can set an Activity as an launcher activity while creating an Android Activity or using Manifest file.

Lifecycle of Android Activity

In Android, Activity is started by onCreate() method, which you have already seen in MainActivity.java file. As user nagivate through our app then many method may be called by an Activity such as onStart(), onResume(), onPause(), onStop(), onRestart() and onDestroy() etc.
You can also go through below image to understand how Android Activity lifecycle works.

Android Activity - Lifecycle

Some of Callback methods on Android Activity

You can use these callback methods to know how user interact  with your App and also to add some function to your app, when any of these method is called such as you can set some function to perform when onPause() method is called.
So lets start with some of Callback methods on Android Activity.

1. onCreate()
This is the callback method which initiate an Android Activity and called when Android Activity is first created.

2. onStart()
When Activity become visible to user this callback method is called.

3. onResume()
When user started intrecting with an Android Activity this method is called

4. onPause()
When an Android Activity is paused this method is called. when an activity is paused it did not receive any input or execute code.

5. onStop()
Called when activity is no longer visible to user.

6. onRestart()
Called when activity is restarted when it is previously stopped.

7. onDestroy()
Called just before the Android Activity is destroyed by the system. 

You can use these callback methods to improve user experience on your application and you want to check when a callback method is called by using Log.d() method.

Thanks for reading and be updated to this blog for new updates.