Activities in Android
Prerequisites
Although this is a beginner article,you should at-least know the basic structure of an android application.If not please check on Structure of an Android app .
What is an activity?
Almost all applications that we use requires us to login,the screen where you enter your login details is called an activity.After filling in your details and clicking the login button you will be redirected to another screen e.g Home ,Home screen is also another activity.This means that apps are made up of many activities. i.e Login Activity, SignUp Activity, Home Activity, Profile Activity e.t.c
An activity is a single, focused thing that the user can do.
Activity Lifecycle
Just like human beings or animals,activities also have their own lifecycle.A human being moves from being a child to being a teenager to being an adult and finally to an old age which leads to death.
An activity undergoes through different states from the time we open an app to the time we close or simply exit using the home button.
The diagram below shows the states the states of activity lifecycle.
The activity goes through the following states:
onCreate() -> this is the first method that is called when an activity is opened by the user.This is also the method responsible for displaying the UI,this is achieved by passing the corresponding XML layout.
onStart() -> this is called immediately after the onCreate() method.The activity becomes visible but the user cannot interact with it.
onResume() -> this is called immediately after the onStart() method. At this state,the user can now interact with the activity. The activity remains in this state until when the activity loses focus e.g if a call interrupts which leads to onPause() being called.
onPause() -> this is called when an activity is partially visible and the user cannot interact with the activity.Apart from interruption,this is called also when the user is leaving the app.
onStop() -> this is called when the activity is no longer visible to the user.This may happen because:
- the activity is being destroyed
- a new activity is starting
- an existing activity is entering a Resumed state and is covering the stopped activity.
onRestart() -> this method is called when an activity is about to be restarted.This happens when for example you are opening an activity(app) after leaving using the home button.
onDestroy -> this is the last method to be called and destroys the activity completely,this means the activity will start the lifecycle when you reopen. This is called when an activity is cleared on the application stack.