Unit-2
Components, Activity Life Cycle, Intents
2.1Android application components
2.1.1 Activities
2.1.2 Services
2.1.3 Content providers
2.1.4 Broadcast Receivers
Android application components
Application components are the essential building blocks of an Android application. These components are loosely
coupled by the application manifest file AndroidManifest.xml that describes each component of the application and
how they interact.
There are following four main components that can be used within an Android application −
Sr.No Components & Description
Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.
Services
2
They handle background processing associated with an application.
Broadcast Receivers
3
They handle communication between Android OS and applications.
Content Providers
4
They handle data and database management issues.
Activities
An activity represents a single screen with a user interface,in-short Activity performs actions on the screen. For
example, an email application might have one activity that shows a list of new emails, another activity to compose an
email, and another activity for reading emails. If an application has more than one activity, then one of them should
be marked as the activity that is presented when the application is launched.
Services
A service is a component that runs in the background to perform long-running operations. For example, a service
might play music in the background while the user is in a different application, or it might fetch data over the
network without blocking user interaction with an activity.
Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example,
applications can also initiate broadcasts to let other applications know that some data has been downloaded to the
device and is available for them to use, so this is broadcast receiver who will intercept this communication and will
initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcaster as
an Intent object.
Content Providers
A content provider component supplies data from one application to others on request. Such requests are handled
by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere
else entirely.
A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs
that enable other applications to perform transactions.
We will go through these tags in detail while covering application components in individual chapters.
Additional Components
There are additional components which will be used in the construction of above mentioned entities, their logic, and
wiring between them. These components are −
S.No Components & Description
Fragments
1
Represents a portion of user interface in an Activity.
Views
2
UI elements that are drawn on-screen including buttons, lists forms etc.
Layouts
3
View hierarchies that control screen format and appearance of the views.
Intents
4
Messages wiring components together.
Resources
5
External elements, such as strings, constants and drawable pictures.
Manifest
6
Configuration file for the application.
Describe Activity life cycle
In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any
desktop application. An Android app consists of one or more screens or activities.
Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when a new activity
starts, the previous one always remains below it. There are four stages of an activity.
1. If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or
running. This is usually the activity that the user is currently interacting with.
2. If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your activity. In
such a case either another activity has a higher position in multi-window mode or the activity itself is not
focusable in the current window mode. Such activity is completely alive.
3. If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the
information, and as its window is hidden thus it will often be killed by the system when memory is needed
elsewhere.
4. The system can destroy the activity from memory by either asking it to finish or simply killing its process.
When it is displayed again to the user, it must be completely restarted and restored to its previous state.
For each stage, android provides us with a set of 7 methods that have their own significance for each stage in the life
cycle. The image shows a path of migration whenever an app switches from one state to another.
Detailed introduction on each of the method is stated as follows:
1. onCreate()
It is called when the activity is first created. This is where all the static work is done like creating views, binding data
to lists, etc. This method also provides a Bundle containing its previous frozen state, if there was one.
2. onStart()
It is invoked when the activity is visible to the user. It is followed by onResume() if the activity is invoked from the
background. It is also invoked after onCreate() when the activity is first started.
3. onRestart()
It is invoked after the activity has been stopped and prior to its starting stage and thus is always followed by onStart()
when any activity is revived from background to on-screen.
4. onResume()
It is invoked when the activity starts interacting with the user. At this point, the activity is at the top of the activity
stack, with a user interacting with it. Always followed by onPause() when the activity goes into the background or is
closed by the user.
5. onPause()
It is invoked when an activity is going into the background but has not yet been killed. It is a counterpart to
onResume(). When an activity is launched in front of another activity, this callback will be invoked on the top activity
(currently on screen). The activity, under the active activity, will not be created until the active activity's onPause()
returns, so it is recommended that heavy processing should not be done in this part.
6. onStop()
It is invoked when the activity is not visible to the user. It is followed by onRestart() when the activity is revoked from
the background, followed by onDestroy() when the activity is closed or finished, and nothing when the activity
remains on the background only. Note that this method may never be called, in low memory situations where the
system does not have enough memory to keep the activity's process running after its onPause() method is called.
7. onDestroy()
The final call received before the activity is destroyed. This can happen either because the activity is finishing (when
finish() is invoked) or because the system is temporarily destroying this instance of the activity to save space. To
distinguish between these scenarios, check it with isFinishing() method.
( https://www.geeksforgeeks.org/activity-lifecycle-in-android-with-demo-app/ )
Define intents
In Android, it is quite usual for users to witness a jump from one application to another as a part of the whole
process, for example, searching for a location on the browser and witnessing a direct jump into Google Maps or
receiving payment links in Messages Application (SMS) and on clicking jumping to PayPal or GPay (Google Pay). This
process of taking users from one application to another is achieved by passing the Intent to the system. Intents , in
general, are used for navigating among various activities within the same application, but note, is not limited to one
single application, i.e., they can be utilized from moving from one application to another as well.
Intents could be Implicit, for instance, calling intended actions, and explicit as well, such as opening another activity
after some operations like onClick or anything else. Below are some applications of Intents:
1. Sending the User to Another App
2. Getting a Result from an Activity
3. Allowing Other Apps to Start Your Activity
Types of Android Intents
There are two types of intents in android
1. Implicit
2. Explicit
Implicit Intent
Implicit Intent doesn't specify the component. In such a case, intent provides information on available components
provided by the system that is to be invoked.
Implicit intents are used to request a specific action without specifying the exact component that will
perform it.
They declare a general action to be performed (e.g., view a webpage, send an email, make a phone call) and
allow the system to find a component from any app that can handle that action.
The system uses Intent Filters to determine which component to activate based on the declared action, data,
and other attributes.
Implicit intents are useful for interacting with other apps on the device.
Example: In the below images, no component is specified, instead, an action is performed i.e. a webpage is going to
be opened. As you type the name of your desired webpage and click on the ‘CLICK’ button. Your webpage is opened.
Explicit Intent
Explicit Intent specifies the component. In such a case, intent provides the external class to be invoked.
Explicit intents are used to start a specific component (like an Activity, Service, or BroadcastReceiver) within
the same application.
They specify the target component by its class name.
This is useful for navigating between screens within your own app or for starting a service in your app that
you know is available.
For Example: In the below example, there are two activities (FirstActivity, and SecondActivity). When you click on the
‘GO TO OTHER ACTIVITY’ Button in the FirstActivity, then you move to the SecondActivity. When you click on the ‘GO
TO HOME ACTIVITY’ button in the SecondActivity, then you move to the first activity. This is getting done through
Explicit Intent.
2.4.1 Exploring Intent objects
Two types given above.
2.4.3 Linking activities using intents
Intents are used in Android to link different activities within or between applications. They act as messengers that
request actions from other components, such as starting an activity or sending data.
Linking Activities with Intents:
Starting an Activity:
Use startActivity(intent) with either an explicit or implicit intent to launch another activity.
Passing Data:
Use putExtra() to add data to an intent before launching an activity.
Receiving Data:
In the receiving activity, retrieve the data using getIntent() and then getStringExtra(), getIntExtra(), etc.
Switching between different screens within the same app (e.g., navigating from a main menu to a settings
screen).
Opening another app's activity to handle a specific task (e.g., opening Google Maps to display a location,
opening a web browser to view a URL).
Sending data to another activity for processing (e.g., passing user input to a confirmation screen).
Explain the creation of Android application that switches between Activities
Switching between pages in an application is one of the basic features of an app. We can do that by adding few lines
of code.
For that open android studio and create a new project.
create new project > Empty Activity >Next > Enter name of the project > Finish
Create two activies that we can navigate in using a button.
(We can navigate between pages using pretty much every element, not necessarily button).
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/page1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This Is the First Page"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<Button
android:id="@+id/page2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This Is the Second Page"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Don’t forget to give id’s to the buttons which we will need in MainActivity.java file.
To navigate from activity_main.xml to activity_main2.xml we have to write the code in MainActivity.java file.
We have to set an onClickListner to the element which we are going to use to navigate between pages (in this case
button).
package com.example.navigation;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
Button b1 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.page1);
b1.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
}
}
);
}
}
Now after clicking the button in the first page the second page is opened.