0% found this document useful (0 votes)
4 views66 pages

MobileApplications Chapter 3

Uploaded by

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

MobileApplications Chapter 3

Uploaded by

boumellaseif16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 66

Programming

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.

• Differentiate between explicit and implicit intents.

• Write a broadcast receiver that listens for specific system events and performs

actions in response.

• Implement a bound service that communicates with an activity to perform a long-

running taskin the background.

• Create a complex Android application that uses resources to provide support for

multiple languages and screen sizes.


2
Android Application
Components
Android application is made up of several components that work together to provide a

seamless user experience. The four main components of an Android app are activities,
Activities and Resources

services, broadcast receivers, and content providers.

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

they behave at differentstages of their existence.

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

performs a specific task or presents a certain type of content.

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

with each other to provide a seamless user experience.


Activities and Resources

To implement an activity, you create a subclass of the Activity class and override its

methods to define the behavior of the activity.

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

work together to create a seamless experience, each activity is independent of

the others.

A camera app for instance, can start the activity in the email application to let the

user share a picture via email. 7


The Activity Lifecycle
Activities have a well-defined lifecycle,

which includes methods that are called when


Activities and Resources

the activity is created, started, paused,

resumed, and destroyed. By implementing

these lifecycle methods, you can manage the

state of the activity and provide a consistent

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

system resources that are no longer needed.

• 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

• onRestart() called when the activity restarts after being stopped.

• onStop() called when the activity is not visible anymore.

• onResume() called when the activity comes to the foreground.

• finish() allows to finish an activity.

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

this element by its identifier (normally defined in the R class).

• 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

identifier, the second one allows to pass parameters to it.

• dismissDialog(int) close a dialog window designated by its identifier.

• 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.

Example: Started Service


Examples of started services include downloading a file, playing a ring 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

components. Such service runs as long as components are bound to it.

• When the components are no longer bound, the service is destroyed.

Example: Bound Service


Examples of bound services include a music player service that allows a user

interface to control playback or a location service that allows other applications to

get the user's location.

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

Broadcast receivers are components that listen to broadcast announcements sent by

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

phone call coming in, or the system starting up.


Activities and Resources

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

implemented as a subclass of BroadcastReceiver and delivered as an Intent object.

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

Example: Content Provider


Activities and Resources

The Android system provides a content provider that manages the user's contact

information. Any application with the proper permissions can query the content

provider to read and write information about a particular person.

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

within the current application.

An Intent object can contain the following information:

• Name of the targeted component.

• 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.

• Category: A string that specifies the category of the Intent.

• Flags: A set of flags that modify how the Intent is handled, such as FLAG_ACTIVITY_NEW_TASK to start

an activity in a new task.


21
Activating Elements : Intents

!Important
Activities and Resources

We can send informative Intents to pass messages. But we can also send Intents

to launch a component (e.g., a new activity).

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

Example: Implicit Intent


Activities and Resources

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

pass the class of the targeted activity as the Intent's parameter:

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

application that can handle the Intent.

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

application that can handle the Intent.

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

return code that can also be filtered in the parent activity.

In the child activity, we have:

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:

On the receiving activity's side, the information is retrieved as follows:

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

target application. Here are some common examples of categories:


• DEFAULT: the default category
• BROWSABLE: an activity that can be launched from a web browser, allowing the
management of specific links (e.g. foo://truc)
• APP_MARKET: an activity that allows browsing and downloading of applications from
the application market
• APP_MUSIC: an activity that allows browsing and playing of music

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

filters to be defined in the Manifest.

A filter can use several levels of filtering:


• action: identifies the name of the Intent. To avoid collisions, the Java naming
convention should be used.
• category: allows filtering of an action category (DEFAULT, BROWSABLE, ...).
• data: filters on the message data, for example using android:host to filter a particular
domain name.

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

Thus, the application responds to the solicitation of Intents sent by:

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

An application is described by an XML file called AndroidManifest. This file allows to


indicate :
Activities and Resources

• The SDK used by a uses-sdk tag.


• The permissions : a uses-permission tag for each requested permission.
• The activities of the application: an activity tag for each activity containing one or
more intent-filter tags.
• Application services : a service tag for each service containing one or more several
intent-filter tags.
• The broadcast intent listeners : a receiver tag for each listener, each containing one
or more intent-filter tags.
• Content providers: a provider tag for each activity.
42
43
Android Manifest
Activities and Resources
Permisssions

To allow an application to access certain resources it must be given permission by a


<uses-permission> tag. The main permissions are:
Activities and Resources

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

• layout (XML description of interfaces).


• values (XML definitions of values: strings, arrays, numerical values, etc.).
• anim (XML description of animations).
• menu (XML description of menus for the application).
• xml (XML files used directly by the application).
• raw (all other types of resources: text files, video, sound ...).
• drawable (for graphic assets).

• It is possible to create other directories than those indicated above for


particular cases
45
Resources
Resource Referencing Class (R Class)

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

Example: Using the R class


For example, a "photo.png" image placed in drawable-hdpi will be designated by

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

There are several types of drawables that can be used in Android:


• Bitmap Drawables: Bitmaps are images that are stored as pixel data. They can be
Activities and Resources

created in different formats such as PNG, JPEG, or GIF.


• Vector Drawables: Vector graphics are images that are defined mathematically,
using lines, curves, and shapes. They are resolution-independent and can be scaled
without losing quality.
• Nine-Patch Drawables: Nine-patch drawables are bitmaps that can be resized
without distorting their content. They are used to create resizable backgrounds,
borders, and other graphics.
• State List Drawables: State list drawables are a set of drawable resources that can
be used to define different states of a view, such as focused, pressed, or disabled.

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

Used for devices with smallest width (sw)


values-sw<N>dp Layout and dimension resources
equal to N dp or more

Used for resources in a specific language


values-<language code> String resources
(e.g. values-es for Spanish)

Used for resources in a specific language


values-<language code>-r<region code> and region (e.g. values-es-rMX for String resources
Mexican Spanish)

Used for devices with API version (v)


values-v<N> All resources
equal to N or more

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

the Arabic translations:


res/

values/

strings.xml (default language)

values-ar/

strings.xml (Arabic translations)

values-en-rGB/

strings.xml (British English translations)

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

Example: String Values


Activities and Resources

From the previous example, the strings.xml file in the values folder would contain the default text resources

used in the applications. For example:

In this case, the strings.xml file in the values-ar folder would contain the Arabic translations of the text

resources used in the application:

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

Example: Color Values

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

Example: Color Values

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

the application's UI.

Example: Integer Values

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

the application's UI.

Warning: Floating Point Values


There is no specific resource file for float or double values in Android. Instead, you can

define double values in the existing dimens file.

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

Example: Style Values

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

Example: Plurals Values

61
Using Resources
Referencing a Resource in XML
A resource is referenced in an XML file by : "@[package:]type/identifier".
Activities and Resources

Example: In XML files


For example: @string/string_name refers to a string described in an XML file placed in the res/values directory and

defined by : <string name="string_name">content of this string</string>

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.

For instance : String title = getResources().getString(R.string.texte_titre); retrieves the string


defined in an XML file by : <string name="title_text">.....</string>.

65
Using Resources
Uri
Uri is a way to designate resources on the Internet or locally.
Resource on the Internet
Activities and Resources

To create a Uri referring to a resource on the Internet:

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

You might also like