0% found this document useful (0 votes)
120 views8 pages

Android App Components & Lifecycle Overview

The document outlines the fundamental components of Android applications, including Activities, Services, Broadcast Receivers, and Content Providers, which are defined in the AndroidManifest.xml file. It explains the activity lifecycle, detailing the various states an activity can be in and the corresponding lifecycle methods. Additionally, it describes the use of Intents for navigation between activities and provides a simple example of creating an Android application that switches between two activities using buttons.

Uploaded by

Raja Kishore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views8 pages

Android App Components & Lifecycle Overview

The document outlines the fundamental components of Android applications, including Activities, Services, Broadcast Receivers, and Content Providers, which are defined in the AndroidManifest.xml file. It explains the activity lifecycle, detailing the various states an activity can be in and the corresponding lifecycle methods. Additionally, it describes the use of Intents for navigation between activities and provides a simple example of creating an Android application that switches between two activities using buttons.

Uploaded by

Raja Kishore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 [Link] 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 −
[Link] 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 −

[Link] 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.
( [Link] )

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"?>
<[Link] xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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" />

</[Link]>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link] xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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" />

</[Link]>
Don’t forget to give id’s to the buttons which we will need in [Link] file.
To navigate from activity_main.xml to activity_main2.xml we have to write the code in [Link] 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 [Link];

import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

public class MainActivity extends AppCompatActivity {

Button b1 ;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

b1 = findViewById([Link].page1);
[Link](
new [Link]() {
@Override
public void onClick(View v) {
Intent i = new Intent([Link],[Link]);
startActivity(i);
}
}
);

}
}
Now after clicking the button in the first page the second page is opened.

Common questions

Powered by AI

Activities are one of the four main components in Android that dictate the user interface and handle user interactions with the smartphone screen . They represent a single screen with a user interface, similar to a window in a desktop application. Each activity goes through various stages in the activity lifecycle, such as being active (running), paused, stopped, and destroyed, which determine how the application should manage its state . The lifecycle methods like onCreate(), onStart(), onResume(), onPause(), onStop(), onRestart(), and onDestroy() manage the state transitions of activities. These methods ensure that activities manage transitions properly, conserving resources by releasing them when the activity is not in the foreground . Understanding these lifecycle stages and appropriate use of lifecycle methods is crucial for developing efficient and responsive Android applications .

The activity lifecycle is crucial in maintaining optimal application performance and user experience in Android applications. It dictates how activities transition through different states, such as created, started, resumed, paused, stopped, and destroyed, each associated with lifecycle methods that manage these transitions . Proper use of the lifecycle methods ensures efficient resource management, such as releasing memory or processing capacity when the activity is not in the foreground (such as in onPause() or onStop()) and reinitializing them when the user returns to the activity (such as in onStart() or onResume()). Mismanagement of these lifecycle states can lead to memory leaks, high battery usage, and decreased system efficiency, significantly impacting application performance. Thus, understanding and correctly implementing lifecycle management is a critical skill in Android application development to ensure that applications remain responsive and resource-efficient even under varying workload conditions .

When an Android activity is destroyed, it can be restored to its previous state using a combination of lifecycle methods and saved instance state. The onSaveInstanceState() method allows an activity to save its dynamic state, like user preferences or temporary data, into a Bundle object before it is destroyed . When the activity is recreated, typically in the onCreate() method, the savedInstanceState parameter can be used to restore this state, ensuring a seamless user experience . The onRestoreInstanceState() method is also available for restoring the saved state after onStart(), adding flexibility to where restoration logic can be implemented . These methods facilitate managing configuration changes, like screen rotations or background-to-foreground transitions, ensuring that the application's user state is maintained effectively across lifecycles .

Integration of activities and intents is fundamental to creating coherent user navigation flows within Android applications. Activities represent individual screens within an app, and intents serve as the communication mechanism that facilitates transitions between these screens . By using explicit intents, developers can pinpoint transitions to specific activities within the application, enabling precise navigation patterns, such as moving between a homepage and detail pages . Implicit intents allow applications to call upon external functionalities provided by other apps, such as opening maps or sharing content, enhancing the application’s interaction level and providing more enriched user experiences . Intent-based navigation, combined with activities properly managing their lifecycle states, ensures intuitive and seamless user experiences where screens transition logically, maintaining context and user data effectively across various activities .

Content providers manage the sharing of data between applications in Android, supplying data on request using a standard set of methods . They are implemented as subclasses of the ContentProvider class and must provide APIs that allow other applications to perform transactions, often via the ContentResolver class . This data can come from a database, file system, or other flat files, enabling one application to interact with another's data securely and efficiently. By decoupling data storage from data presentation, content providers enable Android applications to reuse and share data without needing to directly access each other's databases, adhering to the principles of encapsulation and data abstraction. The use of URIs to identify data within a content provider allows flexibility in data management and retrieval, making it a powerful component for efficient data handling across multi-application environments .

Broadcast receivers act as an intermediary between the Android operating system and applications, facilitating communication by responding to broadcast messages . They are implemented as a subclass of the BroadcastReceiver class, where the broadcast messages are transmitted as Intent objects. This allows applications to initiate broadcasts to notify other applications that certain data has been downloaded or that a particular event has occurred . Such communication can include system-wide status changes, like network connectivity or battery level, allowing applications to respond to changes in the environment or operation status. By intercepting these broadcasts, broadcast receivers enable applications to perform appropriate actions without needing to interact directly with the operating system on each state change .

When an implicit intent is broadcasted, the Android system uses intent filters to determine which components can handle the requested action. Intent filters, specified in the manifest file, define the types of intents that a component can respond to, including the action, data, and category associated with the intent . The system evaluates these filters when an implicit intent is invoked, matching the intent's action and data with the components that have registered to handle such actions through their intent filters. If multiple components can handle the intent, the user may be prompted to choose which application to use . This mechanism enables applications to interact with each other and the broader system flexibly, allowing developers to define dynamic interactions without hard-coding component interactions. Intent filters also ensure security and efficiency by controlling which components can respond to particular intents .

Fragments and views are vital for enhancing user interface design in Android applications. Fragments are reusable portions of the user interface within an activity, allowing for dynamic UI management where parts of the UI can be replaced or updated without needing to restart an entire activity . They provide flexibility by enabling multiple interface modules to coexist on a single screen, such as a list of items and their details side by side. Views, such as buttons, forms, and other UI elements, define user interaction points on those interfaces . By combining fragments with various views and leveraging constraint layouts, developers can create complex, responsive, and aesthetically pleasing interfaces that adjust to different screen sizes and orientations, enhancing the overall user engagement and interaction experience within the app .

Services and activities both play important roles in Android applications but serve different purposes. Activities are responsible for displaying a user interface and handling user interactions, while services manage background processing tasks . Services run in the background to perform long-running operations, such as playing music or fetching data over the network, without the need for user interaction or a user interface, allowing for continued application functionality even when the app is not in the foreground . Unlike activities, services do not go through a well-defined lifecycle visible to the user. Instead, they function more autonomously, being initiated through specific triggers and running without UI constraints. This separation of user interface and background processing allows Android applications to operate efficiently, optimizing user experience by balancing resource use .

Intents in Android act as messages that enable communication between application components, facilitating functions such as starting an activity, passing data, or initiating services . There are two main types of intents: implicit and explicit. Implicit intents are used when a general action needs to be performed without specifying the exact component. The system uses intent filters to determine activating a component based on the specified action, data, and attributes. For example, an implicit intent can request viewing a webpage or sending an email . Explicit intents, in contrast, specify the target component by its class name and are used to start a specific activity, service, or broadcast receiver within the same application. This type of intent is useful for navigating between screens in the same app . By effectively utilizing both implicit and explicit intents, developers can create seamless and integrated applications that can interact not only within their components but also with other applications on the device .

You might also like