0% found this document useful (0 votes)
9 views61 pages

Ma 03

Chapter 03 of the Mobile Applications course discusses the importance of activities and resources in Android application development. It covers the concept of activities, their lifecycle, and how to create and manage them, as well as the use of fragments and resources like strings, drawables, and animations. The chapter emphasizes the organization of resources and their usage within the application to enhance functionality and user experience.
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)
9 views61 pages

Ma 03

Chapter 03 of the Mobile Applications course discusses the importance of activities and resources in Android application development. It covers the concept of activities, their lifecycle, and how to create and manage them, as well as the use of fragments and resources like strings, drawables, and animations. The chapter emphasizes the organization of resources and their usage within the application to enhance functionality and user experience.
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/ 61

‫الجمهوريــة الجزائريــة الديمقراطيــة الشعبيــة‬

Algerian Democratic and Popular Republic


‫وزارة التعليم العالي والبحث العلمي‬
Ministry of Higher Education and Scientific Research

University of Ahmed Zabana Relizane


Faculty of Science & Technology
Computer Science Department

Course
Mobile Applications

Chapter 03

Presented by : Dr. Oussama DERNI


[email protected]

09, 16 /02/2025
Chapter 03

Activities and resources


PLAN
01 ACTIVITIES AND RESOURCES
• Introduction

• Activity concept

• Activity life cycle

• Fragments

• Resources

• Resource organization

• Resource usage
Introduction

• Activities and resources are crucial elements in the application development process

• Unlike in some programming models in which applications are launched with a main()

method, the Android system initiates code in an activity instance.

• Android supports a wide range of resource types, which will be explained in this

chapter

4
Activity concept

• An activity provides the window in which the application draws its user interface.

• This window generally fills the screen, but can be smaller than the screen and float

above other windows.

• Typically, an activity implements a screen within an application.

• For example, one of an application's activities may implement a “contact list” screen,

while another activity implements a “chat with a contact” screen, another activity

implements an “application settings” screen, and so on.

5
Activity concept

• Most applications contain several screens, which means they include several activities.

• Typically, an activity in an application is specified as the main activity, which is the first

screen to appear when the user launches the application.

• Each activity can then start another activity to perform different actions.

6
Activity concept

• There are usually minimal dependencies between activities within an application.

• One activity may start activities belonging to other applications.

• For example, a browser application may launch the Share activity of a social

networking application.

• To use activities in your application, you need to record information about them in the

application manifest (AndroidManifest.xml).

7
Activity concept

Creating an activity

1 Right
Click

8
Activity concept

Creating an activity

7 9
Activity concept

Declaring an activity

• To declare an activity named “Parametres”, add these lines to the application element
of the “AndroidManifest.xml” file:

<activity
android:name=".Parametres"
android:exported="false" >
</activity>

• The “exported” attribute: Indicates whether the given application component is


available to other applications.
10
Activity concept

Declaring an activity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Bonjour"
tools:targetApi="31" >
<activity
android:name=".Parametres"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
11
Activity concept

Parts of an activity

The code, for example “MainActivity.java”


package com.si.bonjour;

import static android.content.ContentValues.TAG;


import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the user interface layout for this activity.
// The layout is defined in the project res/layout/main_activity.xml file. Define activity content
setContentView(R.layout.activity_main); from a Layout resource.
}
}
12
Activity concept

Parts of an activity

The graphical interface (XML), for example “main_activity.xml”


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello world !!"
/>

</androidx.constraintlayout.widget.ConstraintLayout>

13
Activity concept

Example

Activity “Contact list” Activity “Chatter”


14
Activity life cycle

• A life cycle is a series of stages through which something (such as an individual, a

culture or a manufactured product) passes during its lifetime.

• To navigate the transitions between stages in the activity's lifecycle, the Activity class

provides a core set of seven callbacks: onCreate(), onStart(), onRestart(), onResume(),

onPause(), onStop() and onDestroy().

• The system calls each of these callbacks when the activity enters a new state.

15
Activity life cycle
Activity launched

the user accesses the


activity
onCreate()

onStart() onRestart()
Application YES
process onResume()
interrupted
Activity in the user
YES accesses the
progress activity
Applications with higher
priorities need more Another activity comes to the user
memory the fore returns to
the activity?
onPause()

activity is no longer visible

onStop()

The activity is ending or is being destroyed


Stopped activity onDestroy() by the system.
16
Activity life cycle

onCreate()

• When an activity is created, it changes state to Created.


• In the onCreate() method, execute basic application startup logic that occurs only once
during the lifetime of the activity.
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the user interface layout for this activity.
// The layout is defined in the project res/layout/main_activity.xml file.
setContentView(R.layout.main_activity);
// Initialize member TextView so it is available later.
textView = (TextView) findViewById(R.id.text_view);
} 17
Activity life cycle

onStart()

• When the activity changes to the Started state, the system calls onStart().
• This call makes the activity visible to the user, while the application prepares the
activity to come to the foreground and become interactive.
• For example, this method initializes the code that manages the user interface.
• The onStart() method executes quickly, and once this callback is complete, the activity
changes to the Resume state and the system calls the onResume() method.
@Override
protected void onStart() {
super.onStart();
textView.setText("Hello world !!");
} 18
Activity life cycle

onResume()

• When the activity enters the Resume state, it comes to the foreground and the system
calls the onResume() callback.
• This is the state in which the application interacts with the user.
• The application remains in this state until something distracts it, such as the device
receiving a phone call.
• This is where lifecycle components can activate any functionality that needs to run
when the component is visible and in the foreground, such as starting a camera
preview.

19
Activity life cycle

onPause()

• The system calls this method as the first indication that the user is leaving your activity,
although this does not always mean that the activity is destroyed.
• It indicates that the activity is no longer in the foreground, but is still visible if the user
is in multi-window mode.
• This is where components can stop any functionality that doesn't need to be executed
when the component (activity) is not in the foreground, such as stopping a camera
preview.

20
Activity life cycle

onStop()

• When your activity is no longer visible to the user, it switches to the Stopped state and
the system calls the onStop() callback.
• This can happen when a newly launched activity covers the entire screen.
• The system also calls onStop() when the activity finishes execution and is about to end.
• In the Stopped state, the Activity object remains resident in memory: it retains all state
and member information, but is not attached to the window manager. When activity
resumes, it recalls this information.
• You don't need to reset the components you've created.

21
Activity life cycle

onDestroy()

• onDestroy() is called before the activity is destroyed.


• The system calls this callback for one of two reasons:

 The activity is terminated, either because the user has completely discarded the
activity, or because finish() was called on the activity.

 The system temporarily destroys the activity due to a configuration change, such
as rotating the device or switching to multi-window mode.

22
Activity life cycle

onDestroy()

• If the activity ends, onDestroy() is the last lifecycle callback the activity receives.
• If onDestroy() is called following a configuration change, the system immediately
creates a new activity instance, then calls onCreate() on this new instance in the new
configuration.
• The onDestroy() callback releases all resources not released by previous callbacks,
such as onStop().

23
Fragments

• A fragment represents a reusable part of your application's user interface.

• A fragment defines and manages its own layout, has its own lifecycle and can handle

its own input events.

• Fragments cannot live on their own.

• They must be hosted by an activity or another fragment.

• The fragment's View hierarchy becomes part of, or attached to, the host's View

hierarchy.

24
Fragments

Creating a fragment

1 Right
click

25
Fragments

Creating a fragment

7 26
Fragments

Parts of a fragment

The graphical interface (XML), for example “fragment_entete.xml”.

<?xml version="1.0" encoding="utf-8"?>


<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EnteteFragment">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#a0d98b"
android:text="Fragment d'entete" />

</FrameLayout>
27
Fragments

Parts of a fragment

The code, for example “EnteteFragment.java”.


package com.si.bonjour;

import .....

public class EnteteFragment extends Fragment {

public EnteteFragment() {
// Required empty public constructor
}
Define fragment content
@Override from a Layout resource.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_entete, container, false);
}
} 28
Fragments

Using the fragment (XML)

Example « activity_main.xml »
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" Fragment container
android:orientation="vertical"
tools:context=".MainActivity">

<androidx.fragment.app.FragmentContainerView The fragment class


android:id="@+id/fragment_container_view"
android:layout_width="match_parent"
android:layout_height="300dp"
android:name="com.si.bonjour.EnteteFragment"
/>
</LinearLayout> 29
Fragments

Using the fragment (Code)

Example « MainActivity.java »

@Override
Retrieve the
protected void onCreate(Bundle savedInstanceState) { FragmentManager
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.add(R.id.fragment_container_view, EnteteFragment.class, null)
.commit();

Fragment container id The Fragment class


30
Fragments

Using the fragment

Example

31
Resources

• These are the additional files and static content your code uses, such as bitmaps,

layout definitions, strings, animation instructions, etc.

• Always externalize application resources such as images and strings from your code, so

that you can manage them independently.

• Also provide alternative resources for specific device configurations by grouping them

in specially named resource directories.

32
Resources

• At runtime, Android uses the appropriate resource based on the current configuration.

• For example, you may wish to provide a different UI layout depending on screen size,

or different strings depending on the language setting.

• Once you've externalized your application's resources, you can access them using the

resource IDs generated in your project's R class.

33
Resources

Resource types

Strings:
Provides strings for your application with optional text style and formatting.
There are three types of resource that can supply strings to your application:

String String array Quantity strings (plurals)


A unique string that can be Table of channels that can be
referenced from within the
application or from other
resource files (such as an XML
layout).
referenced from the
application.
?
34
Resources

Resource types

Drawables:
• A drawable resource is a general concept for a graphic that can be drawn on the screen
and that you can retrieve with APIs such as getDrawable(int) or apply to another XML
resource with attributes such as android:drawable and android:icon.

35
Resources

Resource types

Styles:
• A style resource defines the format and looks for a user interface.
• A style can be applied to an individual View (from a presentation file) or to an entire
activity or application (from the manifest file).

36
Resources

Resource types

Animations:
• An animation resource can define one of two types of animation:
Property animation View animation
Animation defined in XML The “View animation” framework supports tween and frame-by-
that modifies the properties frame animation, both of which are declared in XML.
of the target object, such as
background color or alpha
value, over a defined Tween animation Frame animation
duration. XML-defined animation that An animation defined in
performs transitions on a graphic, XML that shows a
such as rotating, fading, moving sequence of images in
and stretching. order, like a movie.
37
Resource organization

• Resources are organized in directories, with each resource type having its own special
directory.
• Place each resource type in a specific subdirectory of your project's res/ directory.
MyProject/
src/
MainActivity.java
res/
drawable/
graphic.png
layout/
activity_main.xml
mipmap/
icon.bmp
values/
strings.xml 38
Resource organization

39
Resource organization
SUBDIRECTORY RESOURCE TYPE
animator/ XML files that define Property animations
anim/ XML files that define Tween animations.
color/ XML files that define a list of color states.
drawable/ Bitmap files (PNG, .9.png, JPG or GIF) or XML files compiled in the following drawable resource subtypes: Bitmap
files; Status lists; Shapes; Animation drawables; Other drawables
mipmap/ Drawable files for different densities of launcher icons.
layout/ XML files that define a user interface layout.
menu/ XML files that define application menus, such as an options menu, context menu or submenu.
raw/ Arbitrary files to be saved in their raw form.
values/ XML files containing simple values, such as strings, integers and colors.
Whereas XML resource files in other res/ sub-directories define a single resource based on the XML file name,
files in the values/ directory describe several resources. Examples include :
colors.xml for color values/dimens.xml for dimension values/strings.xml for string values
styles.xml for styles
xml/ Arbitrary XML files that can be read at runtime by calling getResources().getXml(int). Various XML configuration
files must be saved here, such as a search configuration.
font/ Font files or XML files including a <font-family> element.

40
Use of resources

Strings

01 - Create a string :

<resources>
<string name="app_name">bonjour</string>
<string name="mon_message">Hello world !!</string>
</resources>

The resource name Resource value

41
Use of resources

Strings

02 - Using the resource in XML :

<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/mon_message"
/>

Resource type
Attribute to modify Resource name
42
Use of resources

Strings

03 - Using the resource in the code :

@Override
protected void onStart() {
super.onStart();
textView.setText(R.string.mon_message);
}

Resource name
Resource type
The R class
43
Use of resources

Arrays

Resource name
01 - Create an array:

<resources>
<array name="animaux">
<item>Lion</item>
<item>Chat</item>
<item>Tigre</item>
<item>Crocodile</item>
<item>Cheval</item>
<item>Requin</item>
</array>
</resources>

6th element
44
Use of resources

Drawables
01 - Creating a drawable :

1 Right
3
Click

45
Use of resources

Drawables
01 - Creating a drawable :

4 7

6
46
Use of resources

Drawables

02 - Using the resource in XML :

<ImageButton
android:id="@+id/mon_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/dz"
/>

Resource name
Attribute to modify Resource type 47
Use of resources

Drawables

03 - Using the resource in the code : View name (ImageButton)

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton button;
button = this.findViewById(R.id.mon_button);
button.setBackground(getResources().getDrawable(R.drawable.dz));
}

Find the first


descending View retrieve the drawable Resource name
with the given ID with the given ID 48
Use of resources

Styles
01 - Create a style :

2
3

1 Right
Click

49
Use of resources

Styles
01 - Create a style :

5 50
Use of resources

Styles
01 - Create a style : Style name

<?xml version="1.0" encoding="utf-8"?>


<resources> Attribute name
<style
name="mon_textview_style">
<item
name="android:background">
@color/black
</item> Attribute value
<item
6 name="android:textColor">
@color/white
</item>
<item
name="android:textSize">
40sp
</item>
</style>
</resources>
51
Use of resources

Styles

02 - Using the resource in XML :

<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/mon_message"
style="@style/mon_textview_style"
/>

Resource type Resource name


52
Use of resources

Animations
01 - Create a Tween animation:

Right 3
1
Click

53
Use of resources

Animations
01 - Create a Tween animation:

54
Use of resources

Animations
01 - Create a Tween animation:

5 Right
Click

55
Use of resources

Animations
01 - Create a Tween animation:

9
56
Use of resources

Animations
01 - Create a Tween animation:
Type of animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="5000"
android:fromDegrees="0"
android:toDegrees="180"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
/>
</set>

Pivot point Number of repeats degrees of


Duration degrees departure
of finish 57
Use of resources

Animations

02 - Using animation in code :

@Override
protected void onStart() {
super.onStart();
TextView textView = (TextView) findViewById(R.id.text_view);

Animation mon_anim = AnimationUtils.loadAnimation(this, R.anim.mon_tween_anim);


textView.startAnimation(mon_anim);
}

Resource name
Creating an animation object
Launch animation
58
Use of resources

Animations

03 - Testing the animation :

59
Use of resources

Animations
Examples:

<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>


<set <set <set
xmlns:android="http://schemas.android xmlns:android="http://schemas.android xmlns:android="http://schemas.android
.com/apk/res/android"> .com/apk/res/android"> .com/apk/res/android">
<alpha <scale <translate
android:duration="5000" android:duration="5000" android:duration="5000"
android:fromAlpha="0.5" android:fromXScale="1%" android:fromXDelta="0%"
android:toAlpha="1" android:toXScale="100%" android:toXDelta="50%"
android:repeatCount="infinite" /> android:fromYScale="1%" android:fromYDelta="0%"
</set> android:toYScale="100%" android:toYDelta="200%"
android:pivotX="50%" android:repeatCount="infinite" />
android:pivotY="50%" </set>
android:repeatCount="infinite" />
</set>

60
Use of resources

Animations
Examples:

61

You might also like