Mobile Dev (3)
Mobile Dev (3)
MOBILE
DEVELOPMENT
2
HOW ARE MOBILE APPS
DISTRIBUTED?
Mobile apps are usually downloaded from official stores controlled by smartphone
companies.
Types of App Stores:
📥 Paid Apps → Users pay to download the app.
📥 Free Apps → Users download for free, but apps may show ads.
Examples of app stores: Google Play Store (Android) and App Store (iOS). 😊
4
WHY MOBILE DEVELOPMENT?
Growing Mobile Market
5
WHY MOBILE DEVELOPMENT?
Better User Experience
✨ Optimized for Mobile → Apps are designed for easy use on small screens.
🔔 Push Notifications → Keep users updated in real time.
📍 Hardware Access → Use GPS, camera, and sensors for more features.
This makes mobile apps fast, interactive, and user-friendly! 🚀
6
CHALLENGES OF MOBILE DEVELOPMENT
1️⃣Limited Size & Power ⚡
✅ Smartphones are less powerful than PCs.
✅ Less RAM & weaker processors require optimized code.
✅ Poor optimization = slow apps!
4️⃣Battery Management 🔋
✅ Heavy apps (games, videos) drain battery quickly.
✅ Avoid unnecessary background processes to save power.
9
MAIN MOBILE FRAMEWORKS
📌 What is a Mobile Framework?
A mobile framework is a tool that simplifies mobile app development by providing ready-to-use
components.
✅ Speeds up development ⏳
✅ Reduces the amount of code needed 📝
10
PRINCIPAUX FRAMEWORKS MOBILE
11
MOBILE OS
📌 Why Learn Android?
💡 Conclusion
12
ANDROID
📌 What is Android?
✅ Advantages of Android :
✔ Open-source → The code is free and modifiable. Developers can use libraries like OpenGL
(for 2D/3D graphics) and SQLite (for databases).
✔ Affordable → Android is almost free. Publishing an app on the Play Store costs only $25.
Developers keep 70% of the revenue, while Google takes 30%.
✔ Easy to develop → Android provides simple and powerful APIs, making development
faster and more efficient. 🚀
13
WHAT IS AN ANDROID API?
An API (Application Programming Interface) is a set of functions and classes
provided by Android that allows developers to access system features.
Each API version introduces new features, and its version number indicates the
functionalities available.
🔹 Backward Compatibility → Newer API versions are usually compatible with older
ones.
🔹 Challenge → Many users have older smartphones that do not support the latest
APIs.
⚠️Problem Example:
Imagine you want to develop an app that uses Facial Recognition to unlock access.
✔ Android 10 (API 29) and above support this feature.
❌ But older devices running Android 8 (API 26) do not support it.
📌 Developers must carefully choose an API that balances:
✔ Market compatibility → Works on most smartphones.
✔ Desired features → Includes the latest functionalities.
15
WHAT IS AN ANDROID SDK?
Le SDK (Software Development Kit) est un ensemble d'outils permettant de développer des
applications Android. Il contient :
✔ Les API Android (pour interagir avec le système).
✔ Des outils de développement (compilateur, débogueur, émulateur AVD(Android Virtual
Device), etc.).
✔ La documentation officielle pour guider les développeurs.
📌 Différence entre API et SDK Android
🔹 Critère 🔸 API Android 🔸 SDK Android
Ensemble de fonctions Ensemble d'outils pour
📌 Définition
pour interagir avec Android développer une application
Classes, méthodes (ex: API + Émulateur + Outils
📂 Contenu
Camera API, Location API) de compilation
Permet d'utiliser des
Permet de créer, tester et
🎯 Utilisation fonctionnalités du
compiler une app
téléphone
LocationManager.getLastKn Android Studio + Debugger
📌 Exemple
ownLocation() + API Android
👉 Le SDK inclut les API, mais les API ne suffisent pas pour développer une app sans le 16
SDK !
ARCHITECTURE D’ANDROID
17
MACHINE VIRTUELLE
Les applications Android sont écrites en Java, mais elles ne sont pas exécutées par une
machine virtuelle Java JVM.
Les applications Android sont exécutées par une machine virtuelle spécifique appelée
Dalvik ( jusqu’`a la version 5.0 Lollipop, sortie en 2014) et actuellement ART , et non par
une JVM classique.
18
DÉVELOPPEMENT EN C/C++ AVEC ANDROID
Avec Android, il est possible d’écrire des applications en C/C++ qui sont exécutées
directement par le système d’exploitation Linux. Pour cela, Android fournit un kit de
développement natif (NDK).
Kit de Développement Natif (NDK)
Le NDK permet de créer des bibliothèques C++ en utilisant les bibliothèques libc et libm,
offrant un accès natif à OpenGL (Open Graphics Library).
OpenGL sur Android
OpenGL est une spécification qui définit une API multiplateforme pour la conception
d’applications générant des images 3D ou 2D.
19
MÉTHODES DE DÉVELOPPEMENT
il y a deux manières pour développer une application Android :
https://developer.android.com/studio? 20
hl=en
2024-2025
CHAPTER 2 : PROJECT
STRUCTURE
21
22
START A NEW ANDROID STUDIO
PROJECT
23
START A NEW ANDROID STUDIO
PROJECT
• MinSDK (Minimum SDK) is the lowest Android version your app can run
on.
• The percentage % shows how many active Android devices support your
chosen MinSDK.
24
START A NEW ANDROID STUDIO
PROJECT
When you create a new Android project, you have to wait because Android Studio is setting up
your project.
• 1️⃣Gradle Scripts
• 2️⃣App
In the following sections of this course, we will detail each directory. But Before that we
first need to understand what is an Activity is in Android development.
26
WHAT IS AN ACTIVITY?
Before we dive into the project folders and files, we first need to understand what an
Activity is in Android development.
In Android development, an Activity represents a single screen of an application. Each
app is made up of multiple screens (activities).
Each activity consists of:
✅ A Java/Kotlin logic file (handles the functionality like button click)
✅ An XML layout file (defines the UI design)
27
PROJECT STRUCTURE(1️⃣GRADLE)
1️⃣What is
Gradle?
28
PROJECT STRUCTURE(2️⃣APP
DIRECTORY)
2️⃣App Directory
• 📌 What happens inside onCreate()? This is where we set up the UI, initialize
variables, and define event listeners.
• super.onCreate(savedInstanceState): Calls the onCreate() method of the parent class
(AppCompatActivity).
• setContentView(R.layout.activity_main); : This loads and displays the UI of the activity.
• R.layout.activity_main :
• R: A generated class that links Java code with XML resources.
• layout.activity_main: Refers to the activity_main.xml file located in the
res/layout folder 📁.This XML file defines the buttons, text fields, and UI
components for the activity.
33
ANDROID RESOURCES(THE RES
FOLDER)
Question : What Are Resources in Android?
Resources in Android are external files that store static content used by the app. These include
images, text, colors, and layouts.
Question : Why Use Resources?
• Better Compatibility: Adapts apps to different screen sizes and devices.
• Easy Maintenance: Changes can be made without modifying the code.
• Multilingual Support: Helps in translating the app into different languages.
34
ANDROID RESOURCES
Types of Resources:
👉 Example:
If an app displays a logo, instead of coding it, you store the image in the drawable
folder and reference it in the UI.
35
ACCESSING A RESOURCE
Question : Resources are separate from Java code, but how can we access them in Java code?
R class is:
1
1️⃣ Auto-generated by Android (inside R.java in the gen folder).
2️⃣ Read-only (we can’t manually edit it).
3️⃣ Static and final (IDs never change during runtime).
4️⃣ Used to reference all resources in the res folder.
36
ACCESSING A RESOURCE
📌 Example 1: Accessing a Layout (activity_main.xml)
🔹 Suppose we have a layout file:
📁 res/layout/activity_main.xml
📌 The setContentView()
method is used to define which
XML layout file should be
displayed on the screen
when an activity starts.
📌 This links the MainActivity.java to
the activity_main.xml layout file.
// java code
📁 Java Code (MainActivity.java)
To use this layout in Java:
setContentView(R.layout.activity_ma 37
in);
ACCESSING A RESOURCE
📌 Example 2: Button Click Action in Android
<Button
android:id="@+id/myButton" ✅ We give the button an ID
(@+id/myButton) so we can reference
android:layout_width="wrap_cont it in code.
ent"
android:layout_height="wrap_cont
In Android
ent"
XML layouts, the @+id/myButton notation is used to define a unique identifier for a
UI elementandroid:text="Click
(View) so that it can beMe" />
referenced in Java/Kotlin code. Let's break it down:
39
WHAT IS A TOAST IN ANDROID?
A Toast is a small pop-up message that briefly appears on the screen to provide
feedback to the user. It automatically disappears after a short duration and does not
require user interaction.
2️⃣ Views :
These are the individual UI elements that users interact with, such as buttons,
text fields, and images.
41
LAYOUTS TYPES(LINEAR
LAYOUT)
Arranges child Views in a single direction: vertically or horizontally.
Uses the attribute android:orientation to specify the direction.
46
👉 This layout stacks the TextView and Button
LAYOUTS TYPES(GRIDLAYOUT)
TableLayout arranges child views in rows and columns, similar to a table. You can use it when
you want to organize items in a grid-like fashion.
47
👉 This layout stacks the TextView and Button
WHAT ARE VIEWS (WIDGET) ?
A View is a UI element that the user interacts with. Here are common examples:
1.TextView – Displays text.
2.EditText – Input field for user text(Basic , Password , Phone Number ,…) .
48
TEXTVIEW
TextView is used to display text on the screen. You can customize its appearance, such as
text size, color, and alignment.
<TextView
android:id="@+id/textView"
android:layout_width="wrap_cont
ent"
android:layout_height="wrap_con
tent"
android:text="winter is
coming"
We can also change the text dynamically in Java
android:textSize="18sp"
code:
android:textColor="#FF5722"
TextView tvTitre =
/>
findViewById(R.id.tvTitre);
tvTitre.setText(“Say My Name");
49
TEXTVIEW
Explanation:
android:layout_width : This attribute defines the width of the view (the element in the
layout). It can take one of three values:
• wrap_content: The view will only be as wide as its content (i.e., it will "wrap" around
the content). For example, a TextView with the text "Hello" will only be as wide as the
text "Hello".
• match_parent: The view will take up the full width of its parent container (usually the
width of the screen or parent layout).
• Specific dp value: You can define a specific width using a unit like dp (density-
independent pixels), for example 100dp.
// ///////java code
EditText editText = findViewById(R.id.myEditText);
String textValue = editText.getText().toString(); // Get the text and
convert to String
• findViewById(R.id.myEditText) finds the EditText by its ID in the
layout.
• getText() retrieves the text as an Editable object.
• toString() converts the Editable object into a regular string.
52
BUTTON
Button is a clickable UI element. It can trigger actions when clicked, such as navigating to
another screen, submitting a form, etc.
<Button
android:id="@+id/button"
android:layout_width="wrap_cont
ent"
53
BUTTON(EVENT LISTENER)
When handling a button click event in Android, we use an event listener. This is an object that "listens"
for user actions and executes specific code when triggered.
To handle button clicks in Android Studio using Java, we use the setOnClickListener method.
3️⃣Using a Lambda
54
BUTTON(1️⃣USING A SEPARATE INNER
CLASS)
The setOnClickListener method accepts an object that implements View.OnClickListener interface. So, we
have to create a separate inner class that implements View.OnClickListener. After that, we define what happens
when the button is clicked (inside the onClick() method), and finally, we create an instance of this class and
pass it to the setOnClickListener method.
public class MainActivity extends AppCompatActivity {3
Button button = findViewById(R.id.button);
1
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
2 button.setOnClickListener(new MyClickListener());}
/////////// this a separate inner class
public class MyClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Button Clicked!",
•The onClick(View v)
Toast.LENGTH_SHORT).show();}}
method is called when the }
user clicks the button.
✅ Reusable in multiple
places 55
❌ More code
BUTTON (2️⃣USING AN ANONYMOUS
INNER CLASS)
Question : What is an Anonymous Inner Class?
Answer : An anonymous inner class is a class that does not have a name. It is used to create
a one-time-use object of a class without explicitly defining a separate class.In Android, we
often use an anonymous inner class to implement event listeners, such as
View.OnClickListener.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but=(Button)findViewById(R.id.button);
but.setOnClickListener(new View.OnClickListener(){ @Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "I Love Tunisia",
Toast.LENGTH_LONG).show(); }});
}
}
✅ Best for simple
actions 56
❌ Not reusable
BUTTON (3️⃣USING A LAMBDA )
Alternative: Using a Lambda (Shorter Code in Java 8+) .
For a simpler way to write the same click event (if you are
using Java 8 or Kotlin), you can use a lambda function:
but.setOnClickListener(v ->
Toast.makeText(getApplicationContext(), "Button clicked!",
Toast.LENGTH_SHORT).show()
);
57
BUTTON (3️⃣USING A LAMBDA )
v → This is the parameter (View v) representing the button clicked.
-> → This is the lambda arrow, which separates parameters from the function body.
{ ... } → The function body, which runs when the button is clicked.
Since setOnClickListener requires a View.OnClickListener (which has only one
method: onClick(View v)), Java automatically understands that our lambda is
implementing this method.
Question : When Can You Use Lambdas?
Answer : You can only use lambda expressions when an interface has only one
abstract method (called a functional interface).
58
CHECKBOX
CheckBox is a UI element that allows users to select one or more options. It is typically
used for binary choices (checked/unchecked).
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I agree to the terms and
conditions" />
In the Java code, you can check if the CheckBox is
checked:
CheckBox myCheckBox = findViewById(R.id.myCheckBox);
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_conten
t"
android:layout_height="wrap_conte
nt" 60
RADIOBUTTON AND
RADIOGROUP
In Java, you can check which RadioButton is
selected:
radioButtonCelsiusToFahrenheit =
findViewById(R.id.radio_celsius_to_fahrenheit);
if (radioButtonCelsiusToFahrenheit.isChecked()) {
// action here
}
61
ACTIVITY LIFECYCLE
Question : What is the Activity Lifecycle?
An Activity in Android goes through multiple stages from creation to destruction. The
Android system automatically calls lifecycle methods to manage how an Activity
behaves during:
• App launch
• User interactions (switching between screens, rotating the phone,
pressing home/back buttons, etc.)
• App closing
62
ACTIVITY LIFECYCLE
When an Activity is created and used, it passes through several states. Here are the 7 core
lifecycle methods:
Method When is it called? What happens?
UI is initialized, variables are
onCreate() When the Activity is created
set up
Activity is visible but not yet
onStart() When the Activity becomes visible
interactive
User can now interact (click
onResume() When the Activity is interactive
buttons, type, etc.)
Temporary pause (e.g., user
opens a notification) . Activity
onPause() When the Activity is partially hidden
is still running, but it is losing
focus
Activity is fully hidden
onStop() When the Activity is no longer visible
(another activity is open)
When the Activity is removed from Activity is shut down and
onDestroy()
memory resources are released
63
When the Activity is restarted after Activity returns from
onRestart()
ACTIVITY LIFECYCLE
Question : Where do these methods come from?
Answer : Activity is a built-in class in Android that provides these lifecycle methods.
Your activity class (e.g., MainActivity) inherits from AppCompatActivity,
which itself extends Activity.
Hierarchy
64
ACTIVITY LIFECYCLE
Question : Who calls these lifecycle methods?
Answer : You don’t call them manually.The Android system automatically calls
them when the activity state changes.
Example:
• When you open an activity → Android calls onCreate() , onStart() ,
onResume() .
• When you press home button → Android calls onPause() , onStop() .
• When the activity is destroyed → Android calls onDestroy().
65
ACTIVITY LIFECYCLE
66
WHAT IS AN INTENT?
An Intent is a messaging object used to communicate between different components
of an Android app.
Think of it as a way to request an action from another component (activity, service, or
broadcast receiver).
67
TYPES OF INTENTS
There are two types of intents in
Android:
Type Description
Think of Explicit Intent in Android like taking a bus 🚌
that goes to a specific destination.
Imagine you are at a bus station (your current
Explicit Intent activity) and you want to go to your friend's house
(another activity). You take a direct bus that goes
only to your friend’s house (specific activity).
Used to start a specific activity within the same app.
An implicit intent in Android is like taking any
available bus that goes to a place that offers the
service you need, without specifying a particular bus
number. Instead of telling the system exactly which
Implicit Intent
activity to open, you just say what kind of action you
want to perform, and Android finds the best app for it.
Used to request an action from another app (e.g.,
opening a web page, making a call).
68
EXPLICIT INTENT
Example: Navigating from MainActivity to SecondActivity Defines an intent to go from
MainActivity to
SecondActivity.
// java code here of MainActivity
Button btn = findViewById(R.id.button);
The startActivity()
btn.setOnClickListener(v -> {
method in Android
Intent intent = new Intent(MainActivity.this,
is used to start a
SecondActivity.class);
new activity.
startActivity(intent);
});
69
EXPLICIT INTENT WITH DATA
TRANSFER
Step 1: Sending Data from MainActivity
• data (Various types) → The
Example: Sending Data to Another Activity actual data to send (String,
int, boolean, etc.)
Intent intent = new Intent(MainActivity.this,
SecondActivity.class);
• key (String) → A unique
intent.putExtra(“isitcom“ , "Hello from
name (identifier) for the
MainActivity!");
data.
startActivity(intent);
putExtra() is a method used in Intents to
send extra data from one component
(Activity, Service, BroadcastReceiver) to
another.
📌 What Happens Here?
We create an Intent to go from MainActivity to SecondActivity.
We add extra data using putExtra("message", "Hello from
MainActivity!");
We start the new activity using startActivity(intent);
70
EXPLICIT INTENT WITH DATA
TRANSFER
📌 Step 2: Receiving Data in SecondActivity
• getStringExtra("key") →
Gets a string value from the
TextView textView = intent.
findViewById(R.id.textView);
// Retrieving the data sent from MainActivity
String message =
getIntent().getStringExtra(“isitcom"); getIntent() → Retrieves the intent
// Displaying the received message in that started the activity.
setText(message)
TextView → Displays the
receivedtextView.setText(message);
message in a TextView.
72
IMPLICIT INTENT (OPENING
SYSTEM APPS)
Example 2: Open the Dialer with a Phone
Number
Intent.ACTION_DIAL → Opens the dialer with a given
number.
73
IMPLICIT INTENT (OPENING
SYSTEM APPS)
Example 3: Send an
Email
74
IMPLICIT INTENT (OPENING
SYSTEM APPS)
Example 4: Open Camera to Take a
Picture
75
HOW TO STOP THE CURRENT
ACTIVITY ?
Stopping an activity means closing the current screen and removing it from the
activity stack.
The most common way to stop an activity is using finish() .
Answer : When the button is clicked, finish() removes the current activity from
memory.
If there was a previous activity, it will be shown.
76
HOW TO STOP THE CURRENT
ACTIVITY ?
If we open a new activity and don’t want the user to come back, we call finish() after starting
the new activity:
77
HOW TO STOP THE CURRENT
ACTIVITY ?
When we call finish() , the system automatically triggers the lifecycle methods in this
order:
1️⃣onPause() → The activity is partially visible but about to be stopped.
2️⃣onStop() → The activity is completely hidden.
3️⃣onDestroy() → The activity is permanently destroyed and removed from memory.
We can test this behavior by adding Toast inside each lifecycle
method :
Button btnClose = findViewById(R.id.button3);
btnClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {Toast.makeText(MainActivity.this,"call
finish",Toast.LENGTH_SHORT).show(); finish();}});
@Override
protected void onPause() {super.onPause();
Toast.makeText(MainActivity.this,"pause",Toast.LENGTH_SHORT).show();}
@Override
protected void onStop() {super.onStop();
Toast.makeText(MainActivity.this,"stop",Toast.LENGTH_SHORT).show();}
@Override
protected void onDestroy() {super.onDestroy(); 78
Toast.makeText(MainActivity.this,"destroy",Toast.LENGTH_SHORT).show();}
STOPPING THE ENTIRE
APPLICATION ?
Using finishAffinity()
Closes all activities in the same task (same app stack).
If the app has multiple activities, it will close all of them and exit the app.
Useful for logging out or when you want to exit the entire app.
Button b =
findViewById(R.id.btnbyebye);
b.setOnClickListener(v ->
finishAffinity()
Question : What happens? );
Asnwer : All opened activities in the app are closed, and the app is
exited.
Question : Does finishAffinity() Completely Exit the App?
Asnwer :
❌ No! The app might still be running in memory (e.g., background
services).
✅ But Yes, all UI activities are removed, and the user sees the home
screen. 79
SUMMARY FINISH() VS
FINISHAFFINITY()
Method Effect
finish() Closes the current activity
Closes all activities in the
finishAffinity()
app
80