Activity forms the building blocks of an android application.The purpose of the Activity is to interact with user.
Activities from different applications communicate using intents.An activity is declared in the AndroidManifest.xml file as:
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
Android applications consists of a collection of Activities.There is a single main activity in Android application.This activity is launched when the Android application is started.An Activity can be in one of several states:
- Started
- Resumed
- Paused
- Stopped
- Destroy
There is a corresponding call back methods for all these activities:
onCreate | When activity is created.Application resources are allocated in this state. |
onStart | When activity is visible to the end user |
onResume | User interface is refreshed when activity is resumed |
onPause | Activity pauses and is moved to background |
onStop | Application stops running |
onDestroy | Application resources are released |
These states of the activities constitute the life cycle of Android application.
You can create a new activity in your Android application by deriving a class from Activity class.Activity class is there in the android.app package.
You override the methods of the Activity super class in your derived class for handling different lifecycle methods.
For example to handle the OnCreate method you override the OnCreate method as:
public class MainActivity extends CustomActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
Starting Activity
You start an activity by using the Intent class object.Intent represents an action such as starting a new activity or service.Once you have created an Intent object you can start a new activity using it:
Create an object of Intent class
Intent intent = new Intent(this, ActivityToStart.class);
Start the activity using the startActivity() method
startActivity(i);
Leave a Reply