MobileApplications Chapter 3
MobileApplications Chapter 3
C#
JavaScript SQLite
Java
03
HTML
Swift C++
Kotlin
Prerequisites
PHP
Activities
MySQL
and
Resources
1
Objectives
At the end of this chapter, you will be able to:
• Explain the role of the Android manifest file and its elements in an Android
Activities and Resources
application.
• Write a broadcast receiver that listens for specific system events and performs
actions in response.
• Create a complex Android application that uses resources to provide support for
seamless user experience. The four main components of an Android app are activities,
Activities and Resources
Components
Broadcast Content
Activity Service
receiver provider
3
The Notion of Activity
Activities and Resources
Definition
Activities are the main user interface components of an Android app. They represent
individualscreens that users interact with, and they have a lifecycle that determines how
4
The Notion of Activity
An activity represents a single screen with a user interface. It serves as the entry
point for user interaction and can be thought of as a self-contained module that
Activities and Resources
Activities are responsible for managing the app's interaction with the user, such as
keeping track of what is currently on-screen and handling user input. They also help
the system to manage the app’s resources, including the use of system memory and
processor time.
Other apps can start an activity if the app allows it, and activities can communicate
5
The Notion of Activity
Other apps can start an activity if the app allows it, and activities can communicate
To implement an activity, you create a subclass of the Activity class and override its
6
The Notion of Activity
Activities and Resources
Example
An email application may have different activities for composing an email,
reading an email, and displaying a list of new emails. Although these activities
the others.
A camera app for instance, can start the activity in the email application to let the
user experience
8
Methods of the Activity Class
Lifecycle Methods
The onXxx methods are called during the life cycle. If they are overloaded, they must call their counterpart of their
Activities and Resources
counterpart of the superior class (super.onXxx). See diagram of the life cycle of an activity below .
• onCreate(Bundle) called at creation. This method is used to initialize the activity and its UI components. The
parameter allows to retrieve a saved state when the activity is stopped (if a backup has been made).
• onPause() called when the activity is no longer in the foreground and has lost focus, but is still visible to the
user. This method is typically used to save any unsaved data and release any system resources that are no longer
needed.
• onDestroy() called when the activity is about to be destroyed. This method is typically used to release any
• onStart()called when the activity is becoming visible to the user but before it is actually displayed. This means
that the activity is not yet in the foreground and the user cannot interact with it. 9
Methods of the Activity Class
Lifecycle Methods
• onResume() called when the activity is brought to the foreground and becomes the focus of the user's attention.
Activities and Resources
10
Methods of the Activity Class
Interface Related Methods
• setContentView(int) allows to create the interface from an XML file, the parameter designates this file by its
identifier.
Activities and Resources
• findViewById(int) retrieve an interface element (returns an object of class View), the parameter designates
• showDialog(int) open a dialog window. The parameter designates the dialog window by its identifier.
• showDialog(int, Bundle) opening of a dialog window. The 1st parameter designates the dialog window by its
• onCreateDialog(int, Bundle) called when a dialog window is opened. The 1st parameter is the identifier of
the dialog window, the second parameter is the one passed when calling of showDialog.
• onPrepareDialog(int, Bundle) called when activating a dialog window already open dialog window. The first
parameter is the identifier of the dialog window, the second is the one that was passed when calling showDialog.
11
Services
Activities and Resources
Definition
Services are background components that can perform long-running operations
and do not have a user interface. They can run even when the application is not
visible on the screen and can interact with other application components.
12
Services
In Android, there are two types of services
• Started Services: it is a service that is started by an application and continues to run in the background even
if the application is closed. A started service typically performs a single task and stops itself when it is
Activities and Resources
done. Examples of started services include downloading a file, playing music in the background, or uploading
data to a server.
13
Services
• Bound Services: It is a service that allows other applications to bind to it and interact with it through an
interface. A bound service typically provides some kind of functionality that can be used by other applications or
Activities and Resources
14
Services
A service is implemented as a subclass of Service. For more information about the Service class (see the code
below).
Activities and Resources
15
Broadcast Receivers
Definition
Activities and Resources
the system or by applications, and then perform actions based on those events
16
Broadcast Receivers
Android broadcasts system events as they occur, including things like the device's power dropping, a new
These events can be handled by creating a broadcast receiver. Broadcasts can originate from the
system or apps, announcing events such as a low battery or downloaded data. Although broadcast
receivers do not have a user interface, they can create notifications to alert the user. They are
17
Content Providers
Definition
Activities and Resources
Content providers are components that manage a shared set of application data that
you can store in the file system, in a SQLite database, on the web, or on any other
persistent storage location that your app can access. Through the content provider,
other apps can query or modify the data, if the content provider permits it
18
19
Content Providers
Activities and Resources
Content Providers
The Android system provides a content provider that manages the user's contact
information. Any application with the proper permissions can query the content
20
Activating Elements : Intents
Intents allow for the management of sending and receiving messages in order to coordinate between
applications. The purpose of Intents is to delegate an action to another component, application, or activity
Activities and Resources
• Action: A string that describes the operation to be performed, such as ACTION_SEND to send data.
• Data: MIME (Multipurpose Internet Mail Extensions) content and URI (Uniform Resource Identifier).
• Extras: Additional data in the form of key/value pairs that can be used to pass information between
components.
• Flags: A set of flags that modify how the Intent is handled, such as FLAG_ACTIVITY_NEW_TASK to start
!Important
Activities and Resources
We can send informative Intents to pass messages. But we can also send Intents
22
Types of Intents
There are two types of Intents:
Intent
Activities and Resources
s
Explici Implici
t t
23
Explicit Intents
Explicit intents are used to start a specific component, such as a particular Activity,
Service, or BroadcastReceiver, within a given application.
Activities and Resources
Explicit Intents include the component name (i.e., the fully qualified class name of
the target component) to which the Intent is directed.
24
Implicit Intents
Implicit Intents are used to activate components that are able to handle the
requested action or data type, without specifying the component name.
Activities and Resources
Implicit Intents include the action to be performed, data to be operated upon, and
category of the Intent. Android system resolves the Intent to an appropriate
component based on the Intent's information and the available components on the
device.
Implicit Intents provide flexibility and allow for interoperability between different
applications.
25
Implicit Intents
For example, an implicit Intent to send an email can be handled by the default email application,
or any other app that has declared itself as capable of handling the email intent.
26
Code Examples
Intents for Launching a New Activity
There are several ways to create an Intent object that will launch a new activity. If we
want to launch an activity that is internal to the application, we can create the Intent and
Activities and Resources
The first parameter of the Intent constructor is actually the context of the application. In
some cases, we should not use this, but instead use getApplicationContext() if the
object handling the Intent does not inherit from Context.
27
Code Examples
Intents for Launching a New Activity
If we want to launch an activity that is external to the application, we pass the Intent
constructor the relevant data and URI: the operating system is responsible for finding an
Activities and Resources
28
Code Examples
Intents for Launching a New Activity
Activities and Resources
29
Code Examples
Returning From an Activity
If we want to launch an activity that is external to the application, we pass the Intent
constructor the relevant data and URI: the operating system is responsible for finding an
Activities and Resources
Filtering in the parent class allows us to know who called this child activity:
30
Code Examples
Activity Result
It is also possible to define an activity result before explicitly calling the end of an activity
with the finish() method. In this case, the setResult() method is used to register a
Activities and Resources
31
Code Examples
Activity Result
And the parent class can filter like this:
Activities and Resources
32
Code Examples
Sending Data
The Intents allow transporting information to the target activity. These pieces of information are called
Extras, and the methods for manipulating them are getExtra() and putExtra(). When preparing
Activities and Resources
an Intent and wishing to add a "key-value" type information, the following procedure is followed:
33
Code Examples
Implicit Intents Types
Actions:
The first parameter in the construction of an Intent is the type of action carried by the Intent. These
Activities and Resources
action types can be either native system actions or actions defined by the developer. There are several
default native actions on Android. The most common is the Intent.ACTION_VIEW action, which allows
you to call an application to view a content whose URI is provided.
Here is an example of sending an email. In this case where we are using the native action, additional
information needs to be added using putExtra():
34
Code Examples
Implicit Intents Types
To define a personal action, simply create a unique string:
Activities and Resources
35
Code Examples
Implicit Intents Types
Categories
In addition to action types, Intents can also have categories that define the type of the
Activities and Resources
36
Code Examples
Broadcasting Information
Intents can also be used to broadcast information. This way, all applications can capture
the message and retrieve the information:
Activities and Resources
The putExtra() method allows you to register a key/value pair in the Intent. You can
retrieve the data using the getExtras() method in the Bundle object that is in the
Intent:
37
Code Examples
Receiving and Filtering Intents
Given the multitude of messages conveyed by Intents, each application must be able to
easily "listen" to the Intents it needs. Android has a declarative filter system that allows
Activities and Resources
38
Code Examples
Receiving and Filtering Intents
By declaring a filter at the activity tag level, the application declares the types of
messages it can handle and that invoke it.
Activities and Resources
39
Code Examples
Receiving and Filtering Intents
The Intent categories mentioned earlier allow for responding to events in a specific
context. The most commonly used example is intercepting a click during web
Activities and Resources
navigation, where a particular protocol is expected. For example, links to the market are
in the form market://.
To respond to a click on a link "foo://domainName.dz/mypage ", you need to construct
an Intent filter that uses the category defining what is "browsable", combined with an
action type indicating that you want to "view "the resource. Additionally, you need to
use the data tag in filter construction:
The host attribute defines the URI authority (thus avoiding phishing attempts), and the scheme
attribute defines the left part of the URI. This way, you can launch an activity on a click on:
40
Code Examples
Receiving and Filtering Intents
The host attribute defines the URI authority (thus avoiding phishing attempts), and the scheme
attribute defines the left part of the URI. This way, you can launch an activity on a click on:
Activities and Resources
foo://domainName.dz
41
Android Manifest
Geolocation (GPS)
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
Personal Data
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission android:name="android.permission.WRITE_HISTORY_BOOKMARKS" />
Etc…
44
Resources
Resource Directories
The res directory contains all the resources that will be put in the application file (apk).
It is made of subdirectories:
Activities and Resources
The IDE (e.g., android studio) explores the files contained in the subdirectories of res
and generates a class (called R) in which an identifier is created for each of the
Activities and Resources
elements found:
• Files (images, texts ..) placed in drawable-xxxx, raw and xml.
• Interface elements defined in files placed in layout and menu.
• Values defined in files placed in values.
• Animations defined in files placed in anim.
• Then, in most of the methods, we can designate these resources by their identifier in
this class R in the form : R.type.name.
46
Resources
Resource Referencing Class (R Class)
Activities and Resources
R.drawable.photo.
47
Resources
Drawables
Activities and Resources
Definition
Drawables are graphical resources used in Android applications to create user
interfaces and provide visual feedback to users. They can be used as backgrounds,
icons, buttons, or any other element that needs to be displayed on the screen.
48
Resources
Types of Drawables
49
Resources
Drawable Folders
To support different screen sizes and densities, drawables are stored in different folders, each targeting a
specific range of screen sizes and densities.
Screen Density
Folder Name Description Example usage
Activities and Resources
(dpi)
Default drawable folder for images that do not Applications icons, button
drawable -
require any special handling. images, etc.
High-density drawable folder for images that should
Background images,
drawable-hdpi ~240dpi be used on devices with a screen density of around
banners, etc.
240dpi.
Medium-density drawable folder for images that
drawable-mdpi ~160dpi should be used on devices with a screen density of UI elements, icons, etc.
around 160dpi.
Extra-high-density drawable folder for images that
High-resolution graphics,
drawable-xhdpi ~320dpi should be used on devices with a screen density of
large images, etc.
around 320dpi.
Double extra-high-density drawable folder for Very high-resolution
drawable-
~480dpi images that should be used on devices with a graphics, high-quality icons,
xxhdpi
screen density of around 480dpi. etc.
Triple extra-high-density drawable folder for images Extremely high-resolution
drawable-
~640dpi that should be used on devices with a screen graphics, large graphics,
xxxhdpi
density of around 640dpi. etc.
Graphics that need to be
drawable- Drawable folder for images that should not be displayed in a specific size
-
nodpi scaled automatically based on screen density. or resolution, such as QR50
codes or barcode images.
Resources
Resources of Type “Values”
The values folder is a directory in an Android project that contains XML files defining various types of values
used in an Android application. These values can include:
Activities and Resources
• String Values: The strings.xml file defines all the string values used in an Android application.
• Color Values: The colors.xml file defines all the color values used in an Android application.
• Dimension Values: The dimens.xml file defines all the dimension values used in an Android application.
• Style Values: The styles.xml file defines all the styles used in an Android application.
• Theme Values: The themes.xml file defines all the themes used in an Android application.
• Array Values: The arrays.xml file defines arrays of strings, integers, colors, and other resources used in
an Android application.
• Integer Values: The integers.xml file defines integer values used in an Android application.
• Boolean Values: The bools.xml file defines boolean values used in an Android application.
• Plurals Values: The plurals.xml file defines plural versions of string resources used in an Android
application.
51
Resources
Values Folders
In general, the values directory is the default folder for resource values that apply to all devices. However,
there are other folders that developers can use to create resources that are optimized for different devices,
Activities and Resources
languages, and API versions. This allows for a more customized and efficient user experience. These
directories are summarized in the table below:
Folder Name Description Usage
values Default folder for resource values All devices
52
Resources
Values Folders
Activities and Resources
Example: Values
Let us say we have an Android app that has text resources in both Arabic and English (specifically, British
English). We can create a values-ar folder in the application's res/ directory and add a strings.xml file with
values/
values-ar/
values-en-rGB/
By using these different values folders, the app will automatically use the appropriate translations based
53
Resources
String Values
The strings.xml file in the values folder is used to define all the string values used in an Android
application. These strings can be used in the application's UI, in code, or in other XML files.
Activities and Resources
<resources>
<string name="app_name">My App</string>
<string name="login_button_text">Login</string>
<string name="welcome_message">Welcome to my app!</string>
</resources>
54
Resources
String Values
From the previous example, the strings.xml file in the values folder would contain the default text resources
In this case, the strings.xml file in the values-ar folder would contain the Arabic translations of the text
55
Resources
Color Values
The colors.xml file in the values folder is used to define all the color values used in an Android application.
These colors can be used in the application's UI, in code, or in other XML files.
Activities and Resources
56
Resources
Dimension Values
The dimens.xml file in the values folder is used to define all the dimension values used in an Android
application. These dimensions can be used to specify sizes and distances in the application's UI.
Activities and Resources
57
Resources
Integer Values
The integers.xml file in the values folder is used to define all the integer values used in an Android
application. These integers can be used to specify numerical values such as widths, heights, and margins in
Activities and Resources
58
Resources
Integer Values
The integers.xml file in the values folder is used to define all the integer values used in an Android
application. These integers can be used to specify numerical values such as widths, heights, and margins in
Activities and Resources
59
Resources
Style Values
The styles.xml file in the values folder is used to define all the styles used in an Android application. These
styles can be used to specify the appearance of UI elements in the application.
Activities and Resources
60
Resources
Plurals Resource Type
The plurals resource type in Android allows you to define multiple versions of a string based on a numeric
quantity. This is useful when you need to display a different string for singular and plural forms of a word.
Activities and Resources
61
Using Resources
Referencing a Resource in XML
A resource is referenced in an XML file by : "@[package:]type/identifier".
Activities and Resources
62
Using Resources
Retrieving a Resource from Code (the
Resources Class)
In the code, the resources are designated by their identifier in the R class of the form: R.type.name.
Activities and Resources
Some methods accept this designation as a parameter to access the resource. However, when we need
to access the content of resources, we can make an applet to the Resources class
(android.content.res.Resources).
We obtain an instance of the Resources class by the getResources() method of the activity.
63
Using Resources
Retrieving a Resource from Code (the
Resources Class)
We access object which accepts as parameter an identifier of the form R.type.name, these methods are :
• InputStream openRawResource(int) returns a read stream on the designated resource.
Activities and Resources
• String getString(int resId): Returns the string resource with the specified resource ID from the
strings.xml file.
• Color getColor(int resId): Returns the color resource with the specified resource ID from the
colors.xml file.
• float getDimension(int resId): Returns the dimension resource with the specified resource ID from
the dimens.xml file.
• Drawable getDrawable(int resId): Returns the drawable resource with the specified resource ID from
the drawable folder.
• Style getStyle(int resId): Returns the style resource with the specified resource ID from the
styles.xml file.
• XmlResourceParser getLayout(int resId): Returns the layout resource with the specified resource ID
from the layout folder.
64
Using Resources
Retrieving a Resource from Code (the
Resources
•
Class)
int[] getIntArray(int resId): Returns the integer array resource with the specified resource ID from
the arrays.xml file.
Activities and Resources
• String[] getStringArray(int resId): Returns the string array resource with the specified resource ID
from the arrays.xml file.
• int getInteger(int resId): Returns the integer resource with the specified resource ID from the
integers.xml file.
• boolean getBoolean(int resId): Returns the boolean resource with the specified resource ID from the
bools.xml file.
• PluralResource getPlural(int resId, int quantity): Returns the plural resource with the specified
resource ID and quantity from the plurals.xml file.
65
Using Resources
Uri
Uri is a way to designate resources on the Internet or locally.
Resource on the Internet
Activities and Resources
For example, the following Uri refers to the GIF file real time.gif accessible on
https://github.com/CharafeddineMechalikh/PureEdgeSim/blob/master/PureEdgeSim/files/.
And then you can use an efficient library (e.g. Glide), to download and display it.
66