0% found this document useful (0 votes)
40 views44 pages

Chapter 3

Chapter 3 discusses the core components of Android applications, focusing on Intents and Services. It details the lifecycle of Activities, Content Providers, Broadcast Receivers, and Services, explaining their roles and how they interact within an app. The chapter emphasizes the importance of managing these components effectively to enhance user experience and application performance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views44 pages

Chapter 3

Chapter 3 discusses the core components of Android applications, focusing on Intents and Services. It details the lifecycle of Activities, Content Providers, Broadcast Receivers, and Services, explaining their roles and how they interact within an app. The chapter emphasizes the importance of managing these components effectively to enhance user experience and application performance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Chapter 3

Intents and Services

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 1


Contents
 Components of Android Applications
 Android Intents and Services
 Characteristics of Mobile Applications
 Successful Mobile Development

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 2


Android Application Components
 In android, application components are the basic building blocks of an application and these
components will act as an entry point to allow system or user to access our app.
 The following are the basic core application components that can be used in Android
application.
 Activities
 Content Providers
 Broadcast Receivers
 Services
 Intents

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 3


1. Activity
 Activity represents a single screen with a user interface (UI) of an application and it will acts an entry point for
users to interact with an application.
 Android apps will contain multiple screens and each screen of our application will be an extension of Activity
class. By using activities, we can place all our android application UI components in a single screen.
 From the multiple activities in android app, one activity can be marked as a main activity and that is the first
screen to appear when we launch the application.
 Each activity can start another activity to perform different actions based on the requirements.
 For example, a contacts app which is having multiple activities, in that the main activity screen will show a
list of contacts and from the main activity screen we can launch other activities that provide screens to perform
tasks like add a new contact and search for the contacts.
 All these activities in the contact app are loosely bound to other activities but will work together to provide a
better user experience.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 4
Cont..
 In android there is a minimal dependency between the activities in an app.
 To use activities in application we need to register those activities information in our app’s
manifest file (AndroidMainfest.xml) and need to manage activity life cycle properly.
<?xml version="1.0" encoding="utf-8"?>  Activity attribute android:name
<manifest …..>
<application …..> will represent the name of class and we
<activity android:name=".MainActivity" >
……. can also add multiple attributes like
……. icon, label, theme, permissions, etc. to
</activity>
……. an activity element based on our
</application>
</manifest> requirements.
 Activities can be implemented as a subclass of Activity class like.
public class MainActivity extends Activity {
}
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 5
Android Activity Lifecycle
 Activities in our android application will go through a different stages in their life cycle.
 In android, Activity class have 7 callback methods like onCreate(), onStart(), onPause(),
onRestart(), onResume(), onStop() and onDestroy() to describe how the activity will behave at
different stages.
 By using activity callback methods we can define how our activity can behave when the user
enter or leaves our application.
Android Activity Lifecycle Callback Methods
 In android, an activity goes through a series of states during its lifetime. By using callback
methods we can get the activity transitions between the states.
 Android system initiates its program within an Activity starting with a call on onCreate()
callback method.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 6
onCreate()
 This is the first callback method and it fires when the system creates an activity for the first time.
 During the activity creation, activity entered into a Created state.
 If we have an application start-up logic that needs to perform only once during the life cycle of
an activity, then we can write that logic in onCreate() method.
 Following is the example of defining a onCreate() method in android activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
 Once onCreate() method execution is finished, the activity will enter into Started state and the
system calls the onStart() method.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 7
onStart()
 The onStart() callback method will invoke when an activity entered into Started State by
completing onCreate() method.
 The onStart() method will make an activity visible to the user and this method execution will
finish very quickly.

Following is the example of defining a onStart() method in android activity.

@Override
protected void onStart()
{
super.onStart()
}
 After completion of onStart() method execution, the activity enters into Resumed state and
system invoke the onResume() method.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 8


onResume()
 When an activity entered into Resumed state, the system invokes onResume() call back
method. In this state activity start interacting with the user that means user can see the
functionality and designing part of an application on the single screen.
 Mostly the core functionality of an app is implemented in onResume() method.
 The app will stay in this Resumed state until an another activity happens to take focus away
from the app like getting a phone call or screen turned off, etc.
 In case if any interruption events happen in Resumed state, the activity will enter
into Paused state and the system will invoke onPause() method.
 After an activity returned from Paused state to Resumed state, the system again will
call onResume() method due to this we need to implement onResume() method to initialize the
components that we release during onPause() method
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 9
Cont..
 Following is the example of defining a onResume() method in android activity.
@Override
public void onResume() {
super.onResume();
if (mCamera == null) {
initializeCamera();
}}
 If any interruption happens in Resumed state, the activity will enter into Paused state and the
system will invoke onPause() method.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 10


onPause()
 Whenever the user leaves an activity or the current activity is being Paused then the system
invokes onPause() method.
 The onPause() method is used to pause operations like stop playing the music when the activity is
in a paused state or pass an activity while switching from one app to another app because every
time only one app can be focused.
 Following is the example of defining a onPause() method in android activity.
@Override
public void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.release();
mCamera = null;
}}
After completion of onPause() method execution, the next method is either onStop() or onResume()
depending on what happens after an activity entered into a Paused state.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 11
onStop()
 The system will invoke onStop() callback method when an activity no longer visible to the user,
the activity will enter into Stopped state. This happens due to current activity entered
into Resumed state or newly launched activity covers complete screen or it’s been destroyed.
 onStop() method is useful to release all the app resources which are no longer needed to the user.
 Following is the example of defining a onStop() method in android activity.
@Override
protected void onStop()
{
super.onStop();
}
 The next callback method which raised by the system is either onRestart(), in case if the activity
coming back to interact with the user or onDestroy(), in case if the activity finished running.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 12
onRestart()
 The system will invoke onRestart() method when an activity restarting itself after stopping it.
 The onRestart() method will restore the state of activity from the time that is being stopped.
 The onRestart() callback method in android activity will always be followed by onStart() method.
onDestroy()
 The system will invoke onDestroy() method before an activity is destroyed and this is the final
callback method received by the android activity.
 The system will invoke this onDestory() callback method either the activity is finishing or
system destroying the activity to save space.
 Following is the example of defining a onDestroy() method in android activity.
@Override
public void onDestroy()  The onDestroy() method will release all the resources which
{ super.onDestroy(); } are not released by previous callback onStop() method.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 13
Android Activity Lifecycle Diagram
 The pictorial representation of the Android Activity Life cycle which shows how Activity will
behave in different stages using callback methods.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 14


2. Content Providers
 Content Provider will act as a central repository to store the data of the application in one
place and make that data available for different applications to access whenever it’s required.
 We can configure Content Providers to allow other applications securely access and modify
our app data based on our requirements.
 Content Provider is a part of an android application and it will act like more like a relational
database to store the app data.
 We can perform multiple operations like insert, update, delete and edit on the data stored in
content provider using insert(), update(), delete() and query() methods.
 We can use content provider whenever we want to share our app data with other apps and it
allow us to make a modifications to our application data without effecting other applications
which depends on our app.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 15
Cont..
 In android, the content provider is having different ways to store app data. The app data can be
stored in a SQLite database or in files or even over a network based on our requirements.
 We have different type of access permissions available in content provider to share the data.
 We can set a restrict access permissions in content provider to restrict data access limited to only
our application and we can configure different permissions to read or write a data.
 The following diagram depicts how the content provider helps in sharing data with applications
from data stores.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 16


Creating a Content Provider
To create a content provider in android applications we should follow below steps.
 We need to create a content provider class that extends the ContentProvider base class.
 We need to define our content provider URI to access the content.
 The ContentProvider class defines a six abstract methods (insert(), update(), delete(), query(),
getType()) which we need to implement all these methods as a part of our subclass.
We need to register our content provider in AndroidManifest.xml using <provider> tag.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 17


Cont..
 query() - It receives a request from the client. By using arguments it will get a data from the
requested table and return the data as a Cursor object.
 insert() - This method will insert a new row into our content provider and it will return the
content URI for newly inserted row.
 update() - This method will update existing rows in our content provider and it returns the
number of rows updated.
 delete() - This method will delete the rows in our content provider and it returns the number of
rows deleted.
 getType() - This method will return the MIME type of data to given content URI.
 onCreate() - This method will initialize our provider. The android system will call this method
immediately after it creates our provider.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 18
3. Broadcast Receivers
 Broadcast Receiver is a component that will allow an android system or other apps to deliver
events to the app like sending a low battery message or screen turned off the message to the app.
 The apps can also initiate broadcasts to let other apps know that required data available in a device
to use it.
 We use Intents to deliver broadcast events to other apps and Broadcast Receivers use status bar
notifications to let the user know that broadcast event occurs.
 Broadcast Receiver is implemented as a subclass of BroadcastReceiver and each broadcast is
delivered as an Intent object.
 We can register an app to receive only a few broadcast messages based on our requirements. When a
new broadcast received, the system will check for specified broadcasts have subscribed or not based
on that it will routes the broadcasts to the apps.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 19
Cont..
 Broadcast receivers, unlike Activities, have no user interface. It’s working is similar to that
of a publish-subscribe design pattern. It’s used for Asynchronous Inter-Process
communication.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 20


3. Services
 Services in Android are a special component that facilitates an application to run in the
background in order to perform long-running operation tasks.
 The prime aim of a service is to ensure that the application remains active in the background
so that the user can operate multiple applications at the same time.
 A user-interface is not desirable for android services as it is designed to operate long-running
processes without any user intervention. A service can run continuously in the background
even if the application is closed or the user switches to another application.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 21


Types of Android Services
The working of these three services is below:
1. Foreground Services - are those services that are visible to the users. The users can interact
with them at ease and track what’s happening. These services continue to run even when users are
using other applications.
 The perfect example of this is Music Player and Downloading.
2. Background Services - These services run in the background, such that the user can’t see or
access them. These are the tasks that don’t need the user to know them.
 Syncing and Storing data can be the best example.
3. Bound Services - runs as long as some other application component is bound to it. Many
components can bind to one service at a time, but once they all unbind, the service will destroy.
 To bind an application component to the service, bindService() is used.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 22
Lifecycle of Android Services
In android, services have 2 possible paths to complete its life cycle namely Started and Bounded.
1. Started Service
 A service becomes started only when an application component calls startService().
 It performs a single operation and doesn’t return any result to the caller. Once this service starts,
it runs in the background even if the component that created it destroys.
 This service can be stopped only in one of the two cases:
 By using the stopService() method.
 By stopping itself using the stopSelf() method.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 23


Cont..
2. Bounded Service:
 It can be treated as a server in a client-server interface. By following this path, android
application components can send requests to the service and can fetch results.
 A service is termed as bounded when an application component binds itself with a service by
calling bindService() method.
 To stop the execution of this service, all the components must unbind themselves from the
service by using unbindService() method.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 24


Cont..
 Suppose, I want to play music in
the background, so call
startService() method. But I want
to get information of the current
song being played, I will bind the
service that provides information
about the current song.

Understanding Started and Bound Service by background music example


Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 25
IntentService()
 There’s an additional service class, that extends Service class, IntentService Class. It is a
base class for services to handle asynchronous requests.
 It enables running an operation on a single background. It executes long-running programs
without affecting any user’s interface interaction.
 Intent services run and execute in the background and terminate themself as soon as they are
executed completely.
Certain important features of Intent are :
 It queues up the upcoming request and executes them one by one.
 Once the queue is empty it stops itself, without the user’s intervention in its lifecycle.
 It does proper thread management by handling the requests on a separate thread.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 26


Methods of Android Services
 The service base class defines certain callback methods to perform operations on applications.
When we talk about Android services it becomes quite obvious that these services will do some
operations and they’ll be used.
The following are a few important methods of Android services :
 onStartCommand()
 onBind()
 onCreate()
 onUnbind()
 onDestroy()
 onRebind()

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 27


Cont..
Let us see these methods in detail:
1. onStartCommand()
The system calls this method whenever a component, say an activity requests ‘start’ to a service,
using startService().
Once we use this method it’s our duty to stop the service using stopService() or stopSelf().
2. onBind()
This is invoked when a component wants to bind with the service by calling bindService(). In this, we must
provide an interface for clients to communicate with the service. For interprocess communication, we use
the IBinder object.
It is a must to implement this method. If in case binding is not required, we should return null as
implementation is mandatory.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 28


Cont..
3. onUnbind()
The system invokes this when all the clients disconnect from the interface published by the service.
4. onRebind()
The system calls this method when new clients connect to the service. The system calls it after
the onBind() method.
5. onCreate()
This is the first callback method that the system calls when a new component starts the service. We
need this method for a one-time set-up.
6. onDestroy()
This method is the final clean up call for the system. The system invokes it just before the service
destroys. It cleans up resources like threads, receivers, registered listeners, etc.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 29
5. Intent
 Intent is a messaging object which is used to request an action from another app
component such as activities, services, broadcast receivers, and content providers.
 It will help us to maintain the communication between app components from the same
application as well as with the components of other applications.
 Intents are the objects of android.content.Intent types and intents are mainly useful to
perform the following things.
Component Description
1. Starting an Activity Performs a task when we pass the Intent object to the content.startActivity()
method. When an intent object is passed to startActivity(), it starts a new
activity or an existing one.
2. Starting a Service An Intent object is passed to the content.startService() method, to start a
Service. We can also send a required request to an existing service.

3. Delivering a Broadcast Passing the Intent object in content.sendBroadcast(), sends messages to


broadcast receivers.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 30


Building an Intent Object
 Intent object contains the information required to determine which component to start and the information
about the action to be performed by the recipient component.
 The Intent object is having following characteristics to help the android system to understand which
component should start.
1. Component Name: It defines the name of the component to start and by using the component name
android system will deliver intent to the specific app component defined by the component name.
 In case if we didn’t define component name then the android system will decide which component should
receive intent based on other intent information such as action, data, etc.
 We can specify the component name for intent by using a fully qualified class name of the target
component and package name, for example, com.tutlane.sampleActivity.
 We can set the component name by using setComponent(), setClass(), setClassName() or by using the
Intent constructor.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 31
Cont..
2. Action
It defines the name of the action to be performed to start an activity. The following are some of the
common actions to start an activity.
Let’s see a few actions that an intent object stores:
 ACTION_CALL: This is for initiating calls from the user’s device.
 ACTION_EDIT: This is to edit and make changes in the data that is visible to the users.
 ACTION_MAIN: This is an initial activity of a task. It takes no input and returns no output.
 ACTION_DIAL: This is used to display a Dialer to the users.
 ACTION_SYNC: This is to synchronize the user’s data on their device on a server.
 ACTION_HEADSET_PLUG: This displays that a headset is plugged in or taken out.
 ACTION_SCREENON: This is for turning on the screen of the user’s device.
 ACTION_BATTERY_LOW: This is a warning for a low running battery.
 ACTION_VIEW: This displays the data to the users on the screens of their devices.
Actions of an Intent Object are set using setAction() method and read through getAction() method.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 32


Cont..
3. Data
It specifies a type of data to an intent filter. When we create an intent, it’s important to specify the
type of data (MIME type) in addition to its URI. By specifying a MIME type of data, it helps the
android system to decide which is the best component to receive our intent.
While defining the data type that is the MIME type of Data in addition to its URI, the data is
expressed as URI (Uniform Resource Identifier).
Different actions are paired with different types of data specifications.
For example – Action_Edit would contain the URI of Document and Action_dial would contain tell:
URI.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 33


4. Category
 It’s optional for intents and it specifies the additional information about the type of component that should
handle an intent. We can specify a category for intent by using addCategory().
Some of the categories included are as follows :
 BROWSABLE: The target components can be invoked in browsers to display data or message.
 ALTERNATIVE: This means the component should be added in the list of alternative actions that the user
performs on some data.
 GADGET: This activity can be added inside some other components that host the gadgets.
 HOME: This displays the home page of the user’s device.
 LAUNCHER: The target can be an initial task and listed on the top of the application launcher.
To specifically set the Intent Object, the category we use is the addCategory() method. If we like, we can also
delete some categories using deleteCatergory(). To get all the lists of categories on a component, we use
getCategory().
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 34
5. Extras
 This is a piece of extended information, in addition to the provided one. This is optional and is
used only in case when there is a need to provide some extra information for the component.
 It is just an extra key-value pair for the component.

6. Flags
 Flags are also provided in Intent Objects for different types of tasks. There are various types of
flags that can be set using the addFlags() method and the setFlags() method.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 35


Android Intent Types
 There are two types of intents available in android, those are Implicit Intents and Explicit
Intents.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 36


1. Implicit Intents
 Implicit Intents won’t specify any name of the component to start instead, it declare an action to
perform and it allows a component from other apps to handle it. For example, by using implicit
intents we can request another app to show the location details of the user or etc.
 Following is the pictorial representation of how Implicit intents send a request to the android
system to start another activity. [1]. Activity A creates an Intent with an action
description and passes it to startActivity().
[2]. The Android System searches all apps for an
intent filter that matches the intent. When a match is
found,
[3]. the system starts the matching activity (Activity
B) by invoking its onCreate() method and passing it
the Intent.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 37


2. Explicit Intents
 Explicit intents explicitly specify the name of the component to be invoked by activity and we
use explicit intents to start a component in our own app.
 For example, we can start a new activity in response to a user action using explicit intents.
 By using explicit intents we can send or share data/content from one activity to another activity
based on our requirements.
 To create an Explicit Intent, we need to define the component name for an Intent object.

Following is an example to implement Explicit Intent:


Intent intent = new Intent(this,MyActivity.class);
intent.putExtra(“Value 1”, “Value one for MyActivity”);

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 38


Intent Filters
 Intent Filters are expressions in the Manifest file of an Android Application. These are
responsible for deciding the behavior of the Intent.
 Intent filters that we mention in the Manifest file can be nested with the application
components.
 Basically, Intent Filters can define the behavior of Intents using three Elements, that are-
<actions> – Action name defines the intent action that it’ll accept.
<data> – Data defines the data that is acceptable.
<category> – Category defines the name of the Intent Category that is acceptable.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 39


Difference between Service and IntentService

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 40


Additional Components
 Which are used to build the relationship between the above components (Activities, Intents, Content
Providers, Services and Broadcast Receivers) to implement our application logic, those are
Component Description
Fragments To represent the portion of user interface in an activity
Layouts To define the user interface (UI) for an activity or app
Views To build a user interface for an app using UI elements like buttons, lists, etc.
Resources To build an android app we required external elements like images, audio files,
etc. other than coding
Manifest File It’s a configuration file (AndroidManifest.xml) for the application and it will
contain the information about Activities, Intents, Content
Providers, Services, Broadcast Receivers, permissions, etc.

These are the main application components which are required to build an android application
based on our requirements.
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 41
Characteristics of Mobile Applications
1. Simplicity for the End-User - Convenient user interface and logical navigation are the foundation
for a great UX.
2. Both iOS and Android Must Be Covered
3. High Performance
4. Security
5. Offline Work
6. Regular Updates
7. Personalization-People love products that offer plenty of opportunities for customization.
8. Search - Strive to make every feature and page as accessible as possible.
9. Analytics - allows admins to get all the needed information about user behavior.
10.Social Media Integration
Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 42
Successful Mobile Application Developers
 Freelancers: You can easily find freelancers who fit in your budget. However, freelancers can
forge their experience or portfolio, or they may have limited exposure to diverse industries.
 In-House Development: You can hire an in-house development team for your project. This
option is a major investment, including recruitment costs, employee benefits, operational costs
for the team and more.
 App Development Agencies: With diverse portfolios and experienced engineers, app
development agencies are affordable, experienced, and professional. Agencies have expert
developers, designers, project managers, creative artists and data scientists.
 Silicon Giants: You can hand over your project to silicon giants like Oracle and IBM. But this
elite app development is rarely affordable for startups.

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 43


Thank You!

Chapter-Three Compile by:Birhanu G. Information Technology 4/28/2023 44

You might also like