0% found this document useful (0 votes)
30 views59 pages

ITP107 Mobile Dev Draft Module

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)
30 views59 pages

ITP107 Mobile Dev Draft Module

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/ 59

Table of Contents

Module 1: Introduction to Android


Introduction 1
Learning Outcomes 1
Lesson 1. What is Android 1
Lesson 2. Features of Android 2
Lesson 3. Android Development Framework 3
Lesson 4. 5
Lesson 5. Components of an Android Application 7
Lesson 6. Android version releases 10
Assessment Task 11
Summary 11
References 12

Module 2: Setting up Android Development


Introduction 13
Learning Outcomes 13
Lesson 1. Android Studio 14
Lesson 2. Installing Java Development Kit 15
Lesson 3. Installing Android SDK in the android studio. 17
Lesson 4. Hello World example. 18
Lesson 5. Creating an Android Virtual Device 22
Assessment Task 27
Summary 28
References 28

Module 3: Android Anatomy


Introduction 30
Learning Outcomes 30
Lesson 1. The Main Activity File 31
Lesson 2. Manifest File 31
Lesson 3. Strings File 33
Lesson 4. R File 33
Lesson 5. Layout File 35
Lesson 6. Different Resources folder 35
Lesson 7. How to access a resource 38
Assessment Task 40
Summary 40
References 41

iii
Module 4: Android Activities
Introduction 42
Learning Outcomes 42
Lesson 1. What is android activity. 42
Lesson 2. Android Activity Life Cycle 43
Lesson 3. Activity State 48
Lesson 4. Activity Lifetime 50
Lesson 5. Process Priority 53
Assessment Task 55
Summary 55
References 56

iv
List of Figures

Figure Description

1.1 Android Architecture 5


2.1 Java SE Download page 15
2.2 Java SE Download Listing 16
2.3 SDK Manager 17
2.4 Android Studio Start Up page 18
2.5 New Project 19
2.6 Project SDK Selection 20
2.7 Project Template 20
2.8 Project Main Activity 21
2.9 Virtual Device Selection 22
2.10 Android OS selection 23
2.11 Virtual Device configuration 24
2.12 Hello World application 25
4.1 Android Activity Life Cycle 43
4.2 Activity State 48
4.3 Activity Lifetime 50
4.4 Activity Priority Tree 53

iv
List of Table

Table Description

1.1 Components of an Android Application 7


1.2 Additional Components 9
1.3 Android Releases 10
3.1 Resource Folder 36
4.1 Activity Callback 43

vi
MODULE 1
INTRODUCTION TO ANDROID

Introduction
There are countless reasons why a lot of and more individuals have an interest in
learning the way to be able to develop android applications. Unarguably, android is that the
preferred mobile software system, with nearly two billion devices, activated and it offers a
unified approach to application development for mobile devices.

That means, that developers would like solely to develop for Android, and their
applications can be ready to run on completely different devices powered by android. This
explicit quality provides android endless possibilities! This implies that and application that's
designed to figure on mobile phone devices will be additionally transferred to android powered
TV sets or android automotive systems.

This can be why, Android is an exciting house to create apps that will assist you in each
aspect of your life, will assist you to communicate, organize, educate, entertain, or simplyto
create your life easier in each device that they could run on!

Learning Outcomes
At the end of this module, students should be able to:

1. Recall what's Android.


2. establish the components of the Android design.
3. Recall the various Android releases.

1
Lesson 1. What is Android
Android is an open source and Linux-based Operating System for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance,
led by Google, and other companies. Android offers a unified approach to application
development for mobile devices which means developers need only develop for Android, and
their applications should be able to run on different devices powered by Android. The first beta
version of the Android Software Development Kit (SDK) was released by Google in 2007
whereas the first commercial version, Android 1.0, was released in September 2008. On June
27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1
Jellybean. Jellybean is an incremental update, with the primary aim of improving the user
interface, both in terms of functionality and performance. The source code for Android is
available under free and open-source software licenses. Google publishes most of the code
under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU
General Public License version 2. (Android - Overview - Tutorialspoint, n.d.).

The supply code for Android is accessible below free and ASCII text file software system
package licenses. Google publishes most of the code below the Apache License version two.0
and also the remainder, UNIX system kernel changes, below the gnu General Public License
version 2 (Android - Overview - Tutorialspoint, n.d.).

Lesson 2. Features of Android (Android - Overview - Tutorialspoint,


n.d.)

Based in Android - Overview - Tutorialspoint, n.d., Android is a powerful operating system


competing with Apple 4GS and supports great features. Few of them are listed below:
 Beautiful UI - Android OS basic screen provides a beautiful and intuitive user interface.
 Connectivity - GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC
and WiMAX.
 Storage
 SQLite, a lightweight relational database, is used for data storage purposes.

2
 Media support - H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1,
MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.
 Messaging
 SMS and MMS
 Web browser - Based on the open-source WebKit layout engine, coupled with
Chrome's V8 JavaScript engine supporting HTML5 and CSS3.
 Multi-touch - Android has native support for multi-touch which was initially made
available in handsets such as the HTC Hero.
 Multi-tasking - User can jump from one task to another and same time various
application can run simultaneously.
 Resizable widgets - Widgets are resizable, so users can expand them to show more
content or shrink them to save space.
 Multi-Language - Supports single direction and bi-directional text.
 GCM - Google Cloud Messaging (GCM) is a service that lets developers send short
message data to their users on Android devices, without needing a proprietary sync
solution.
 Wi-Fi Direct - A technology that lets apps discover and pair directly, over a high-
bandwidth peer-to-peer connection.
 Android Beam - A popular NFC-based technology that lets users instantly share, just
by touching two NFC-enabled phones together.

Lesson 3. Android Development Framework


According to Meier & Lake (2018), Android applications normally are written using the
Java or Kotlin programming languages and are executed by means of the Android Run Time
(ART). Each Android application runs in a separate process, relinquishing all responsibility for
memory and process management to the Android Run Time, which stops and kills processes
as necessary to manage resources.

ART sits on top of a Linux kernel that handles low-level hardware interaction, including
drivers and memory management, while a set of APIs provides access to all the underlying
services, features, and hardware. (Meier & Lake, 2018, p. 9).

3
The Android SDK includes everything you would like to begin out developing, testing, and
debugging Android applications.

 The Android API Libraries - The core of the SDK is the Android API libraries that provide
developer access to the Android stack. These are the same libraries that Google uses
to create native Android applications (Meier & Lake, 2018).
 Development tools - The SDK includes the Android Studio IDE and several other
development tools that let you compile and debug your applications to turn Android
source code into executable applications (Meier & Lake, 2018).
 The Android Virtual Device Manager and Emulator - The Android Emulator is a fully
interactive mobile device emulator featuring several alternative skins. The Emulator
runs within an Android Virtual Device (AVD) that simulates a device hardware
configuration. Using the Emulator you can see how your applications will look and
behave on a real Android device. All Android applications run within ART, so the
software emulator is an excellent development environment - in fact, because it’s
hardware-neutral, it provides a better independent test environment than any single
hardware implementation (Meier & Lake, 2018).
 Full documentation - The SDK includes extensive code-level reference information
detailing exactly what’s included in each package and class and how to use them. In
addition to the code documentation, Android’s reference documentation and developer
guides explain how to get started, give detailed explanations of the fundamentals
behind Android development, highlight best practices, and provide deep-dives into
framework topics (Meier & Lake, 2018).
 Sample code - The Android SDK includes a selection of sample applications that
demonstrate some of the possibilities available with Android, as well as simple
programs that highlight how to use individual API features (Meier & Lake, 2018).
 Online support - Android has vibrant developer communities on most online social
networks, Slack, and many developer forums. Stack Overflow
(www.stackoverflow.com/ questions/tagged/android) is a hugely popular destination
for Android questions and a great place to find answers to beginner questions. Many
Android engineers from Google are active on Stack Overflow and Twitter (Meier &
Lake, 2018).

4
Lesson 4. Android Architecture (Android - Overview - Tutorialspoint,
n.d.)

Android operating system is a stack of software components which is roughly divided into
five sections and four main layers as shown below in the architecture diagram in Figure 1.

At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This
provides a level of abstraction between the device hardware and it contains all the essential
hardware drivers like camera, keypad, display etc. Also, the kernel handles all the things that
Linux is really good at such as networking and a vast array of device drivers, which take the
pain out of interfacing to peripheral hardware (Android - Architecture - Tutorialspoint, n.d.).

On top of Linux kernel there is a set of libraries including open-source Web browser
engine WebKit, well known library libc, SQLite database which is a useful repository for
storage and sharing of application data, libraries to play and record audio and video, SSL
librariesresponsible for Internet security etc. (Android - Architecture - Tutorialspoint, n.d.).

Figure 1.1 Android Architecture

Source: TutorialsPoint – Android

5
Based from Android - Architecture - Tutorialspoint, n.d., This category encompasses those
Java-based libraries that are specific to Android development. Examples of libraries in this
category include the application framework libraries in addition to those that facilitate user
interface building, graphics drawing and database access. A summary of some key core
Android libraries available to the Android developer is as follows:

 android.app − Provides access to the application model and is the cornerstone of all
Android applications.
 android.content − Facilitates content access, publishing and messaging between
applications and application components.
 android.database − Used to access data published by content providers and includes
SQLite database management classes.
 android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.
 android.os − Provides applications with access to standard operating system services
including messages, system services and inter-process communication.
 android.text − Used to render and manipulate text on a device display.
 android.view − The fundamental building blocks of application user interfaces.
 android.widget − A rich collection of pre-built user interface components such as
buttons, labels, list views, layout managers, radio buttons etc.
 android.webkit − A set of classes intended to allow web-browsing capabilities to be
built into applications.

This is the third section of the architecture and available on the second layer from the
bottom. This section provides a key component called Dalvik Virtual Machine which is a kind
of Java Virtual Machine specially designed and optimized for Android. The Dalvik VM makes
use of Linux core features like memory management and multi-threading, which is intrinsic in
the Java language. The Dalvik VM enables every Android application to run in its own process,
with its own instance of the Dalvik virtual machine. The Android runtime also provides a set of
core libraries which enable Android application developers to write Android applications using
standard Java programming language. (Android - Architecture - Tutorialspoint, n.d.).

6
The Application Framework layer provides many higher-level services to applications in
the form of Java classes. Application developers are allowed to make use of these services
in their applications:

The Android framework includes the following key services:

 Activity Manager − Controls all aspects of the application lifecycle and activity stack.
 Content Providers − permits applications to publish and share information with
different applications.
 Resource Manager − Provides access to non-code embedded resources such as
strings, color settings and user interface layouts.
 Notifications Manager − permits applications to show alerts and notifications to the
user
 View System − An extensible set of views used to create application user interfaces.

You will find all the Android application at the top layer. You will write your application to
be installed on this layer only. Examples of such applications are Contacts Books, Browser,
Games etc.

Lesson 5. Components of an Android Application

(Android - Overview - Tutorialspoint, n.d.)

Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.

There are following four main components that can be used within an Android application:

Table 1.1 Components of an Android Application (TutorialsPoint, 2022)

Component Description
Activities They dictate the UI and handle the user interaction to the smartphone
screen
Services They handle background processing associated with an application.

7
Broadcast They handle communication between Android OS and applications.
Receivers
Content Providers They handle data and database management issues.

Activities - an activity represents one screen with an interface. For example, an email
application may need one activity that shows an inventory of the latest emails, another activity
to compose an email, and one for reading emails. If an application has over one activity, then
one amongst them ought to be marked because the activity that's bestowed once the
application is launched (Android - Application Components - Tutorialspoint, n.d.). An activity
is enforced as a Subclass of Activity class as follows:

public class MainActivity extends Activity


{
}

Services - A service could be a part that runs within the background to perform long-running
operations. For example, a service may play music within the background whereas the user
is in a very completely different application, or it'd fetch information over the network while not
block user interaction with an activity (Android - Application Components - Tutorialspoint, n.d.).

A service is implemented as a subclass of Service class as follows:

public class MyService extends Service


{
}

Broadcast Receivers - it merely responds to broadcast messages from different applications


or from the system. For example, applications can even initiate broadcasts to let different
applications apprehend that some information has been downloaded to the device and is
offered for them to use, thus this can be broadcast receiver who will intercept this
communication and can initiate applicable action (Android - Application Components -
Tutorialspoint, n.d.).

8
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcasted as an Intent object.

public class MyReceiver extends BroadcastReceiver


{
}

Content Providers - A content supplier part provides information from one application to others
for the asking. Such requests are handled by the ways of the ContentResolver class. the info
could also be keep within the classification system, the information or elsewhere entirely
(Android - Application Components - Tutorialspoint, n.d.).

A content provider is implemented as a subclass of ContentProvider class and must implement


a standard set of APIs that enable other applications to perform transactions.

public class MyContentProvider extends ContentProvider


{
}

There are additional components which will be used in the construction of above-
mentioned entities, their logic, and wiring between them (Android - Application Components -
Tutorialspoint, n.d.). These components are:

Table 1.2 Additional Components (TutorialsPoint, 2022)

Components Description
Fragments Represent a behavior or a portion of user interface in an Activity.

Views UI elements that are drawn onscreen including buttons, lists forms etc.

Layouts View hierarchies that control screen format and appearance of the
views.
Intents Messages wiring components together.
Resources External elements, such as strings, constants and drawable pictures.

Manifest Configuration file for the application.

9
Lesson 6. Android version releases (Darwin, 2017)
According to Darwin (2017), Android has versed several versions in its period of time. Every
version incorporates a version range, a code name, and an API level. The version range could
be a typical versioning system like 2.1, 2.3.3, 3.0, 4.0, 4.1, 5.0, 6.0, and so on. Once the
primary digit of the version changes, it’s enormous modify innumerable new APIs; once the
second digit changes, its additional evolution than revolution (and often a brand-new code
name); and if solely the third digit changes, it’s a minor amendment. The API levels are
numbered monotonically. The code names are alphabetical and forever confer with sweet
foods. API levels 1 and 2 did not officially have code names.

Note that the Android system is backward-compatible within the usual sense: an app
engineered for an older release can run on a more modern version of Android, however not
the other way around (unless public category MyContentProvider extends ContentProvider
special care is taken). An app engineered for 1.5 ought to run without recompilation on Android
7, for example. however, an app written for and compiled on Android 7 can in all probability
use API calls that don’t exist on the 1.5 phones, therefore the phone can, in fact, refuse to put
in the newer app, unless you employ some versioning and compatibility tricks. the most
important versions of Android are summarized in Table 1.3 (Darwin, 2017, p. 5).

Table 1.3 Android Releases (TutorialsPoint, 2022)

Name Version number(s) Initial stable release API Level

No official code name 1 23-Sep-08 1


1.1 9-Feb-09 2
Cupcake 1.5 27-Apr-09 3
Donut 1.6 15-Sep-09 4
Eclair 2.0 – 2.1 26-Oct-09 5–7
Froyo 2.2 – 2.2.3 20-May-10 8
Gingerbread 2.3 – 2.3.7 6-Dec-10 9 – 10
Honeycomb 3.0 – 3.2.6 22-Feb-11 11 – 13
Ice Cream Sandwich 4.0 – 4.0.4 18-Oct-11 14 – 15

10
Jelly Bean 4.1 – 4.3.1 9-Jul-12 16 – 18
KitKat 4.4 – 4.4.4 31-Oct-13 19 – 20
Lollipop 5.0 – 5.1.1 12-Nov-14 21 – 22
Marshmallow 6.0 – 6.0.1 5-Oct-15 23
Nougat 7.0 – 7.1.2 22-Aug-16 24 – 25
Oreo 8.0 – 8.1 21-Aug-17 26 – 27
Pie 9 6-Aug-18 28
Android 10 (Quince Tart) 10 3-Sep-19 29
Android 11 (Red Velvet Cake) 11 8-Sep-20 30
Android 12 (Snow Cone) 12 4-Oct-21 31
Android 12L (Snow Cone v2) 12 7-Mar-22 32
Android 13 (Tiramisu) 13 Upcoming 33

Assessment Task

1. Based from your understanding, explain and differentiate the four major android
components

Summary

Android was engineered from the ground-up to modify developers to form compelling
mobile applications that take full advantage of all a telephone must provide. it absolutely was
engineered to be really open. For example, an application will decide upon any of the phone’s
core practicality similar to creating calls, causing text messages, or mistreatment the camera,
permitting developers to form richer and additional cohesive experiences for users. Android
is made on the open Linux Kernel. what is more, it utilizes a custom virtual machine that was
designed to optimize memory and hardware resources in a very mobile atmosphere. Android
is open-source; it will be munificently extended to incorporate new newest technologies as

11
they emerge. The platform can still evolve because the developer community works along to
create innovative mobile applications.

Android provides access to a large variety of helpful libraries and tools which will be
used to create wealthy applications. For example, Android permits developers to get the
placement of the device, and permits devices to speak with each other facultative wealthy
peer–to–peer social applications. additionally, Android includes a full set of tools that are
engineered from the bottom up aboard the platform providing developers with high productivity
and deep insight into their applications.

References
Android - Activities - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from
https://www.tutorialspoint.com/android/android_acitivities.htm

Android - Application Components - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from
https://www.tutorialspoint.com/android/android_application_components.htm

Android - Architecture - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from


https://www.tutorialspoint.com/android/android_architecture.htm

Android - Overview - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from


https://www.tutorialspoint.com/android/android_overview.htm

Android Resources Organizing & Accessing - Tutorialspoint. (n.d.). Retrieved August 20,
2020, from https://www.tutorialspoint.com/android/android_resources.htm

Darwin, I. F. (2017). Android Cookbook: Problems and Solutions for Android Developers (2nd
ed.). O’Reilly Media. https://www.amazon.com/Android-Cookbook-Problems-Solutions-
Developers/dp/1449374433

Meier, R., & Lake, I. (2018). Professional Android (D. Ulery, E. Woodward, C. Krause, & M.
Yener (Eds.); 4th ed.). John Wiley & Sons, Inc. https://www.wiley.com/en-
us/Professional+Android%2C+4th+Edition-p-9781118949528

12
MODULE 2
SETTING UP ANDROID DEVELOPMENT

Introduction
According to Meier & Lake (2018), the Android SDK includes all the tools and genus
API’s you wish to put in writing compelling and powerful mobile applications. the most
important challenge with Android, like any new development toolkit, is learning the options
and limitations of these genus API’s.

Since Android Studio 3.0, it’s doable to put in writing Android apps using Java, Kotlin,
or a mixture of each language. If you have got expertise in Java or Kotlin development, you’ll
realize that the syntax and descriptive linguistics you’ve been using can translate directly into
Android. If you don’t have expertise with Java, however, have used different object-oriented
languages (such as C#), you ought to realize the transition to either Java or Kotlin syntax easily
(Meier & Lake, 2018, p. 15).

The power of Android comes from its genus API’s, not the language being employed,
therefore being unacquainted Java or Kotlin syntax and/or Java-specific categories won’t gift
an important disadvantage. There’s no value to transfer or use the SDK, and Google doesn’t
need your application to pass a review to distribute your finished apps on the Google Play
Store. though Google Play needs a tiny low one-time fee to publish applications, if you decide
on to not distribute via the Google Play Store, you'll be able to do therefore at no value (Meier
& Lake, 2018, p. 15).

Learning Outcomes
At the end of this module, students should be able to:

1. Identify what are the tools required to develop an android application.


2. Examine the code structure of a basic android program.

13
3. Write a simple android program.

Lesson 1. Android Studio


Android Studio is purposeful by the Android team at Google to accelerate your
development and assist you to build high-quality apps. It supports all Android kind factors as
well as phones, tablets, TV, Wear, and Auto—and offers tools tailored specifically for Android
developers, as well as wealthy code redaction, debugging, testing, and identification (Meier &
Lake, 2018, p. 16).

Android Studio provides tools for the testing, and publication phases of the event method,
and a unified development atmosphere for making apps for all Android devices. the event
atmosphere includes code templates with sample code for common app options, in-depth
testing tools and frameworks, and a versatile build system (Meier & Lake, 2018, p. 16).

You can download the latest version of Android Studio for your chosen development
platform from the Android Studio homepage at https://developer.android.com/studio (Meier &
Lake, 2018, p. 17)

According to Meier & Lake (2018), when you have initiated the download for your platform,
you will be shown detailed installation instructions that can be summarized as follows:

 Windows-Run the downloaded installation executable. The Windows installer


download includes OpenJDK and the Android SDK.
 MacOS-Open the downloaded Android Studio DMG file, and then drag Android Studio
into your “Applications” folder. Double-click to open Android Studio, and the Setup
Wizard will guide you through the rest of the setup, which includes downloading the
Android SDK.
 Linux-Unzip the downloaded .zip file to an appropriate location for your applications,
such as within /usr/local/ for your user profile, or /opt/ for shared users. Open a
terminal, navigate to the android-studio/bin/ directory, and execute studio.sh. The
Setup Wizard will then guide you through the rest of the setup, which includes
downloading the Android SDK.

14
Since Android Studio 2.2, OpenJDK has been integrated with Android Studio, ensuring you
don’t need to download and install the JDK separately.

Once the installation wizard is completed, the latest Android platform SDK; SDK, platform,
and build tools; and support library will have been downloaded and installed.

Lesson 2. Installing Java Development Kit manually


You can download the latest version of Java JDK from Oracle's Java site. You will find
instructions for installing JDK in downloaded files, follow the given instructions to install and
configure the setup (https://bit.ly/3340g9l).

Oracle Link: https://bit.ly/3340g9l

Figure 2.1 Java SE Download page

Source: https://www.oracle.com/java/technologies/javase-downloads.html

15
Upon visiting the link provided. Choose the “JDK Download” under Oracle JDK. It will
redirect you to the latest version available for the JDK.

After the redirection, you will see different download option list similar in Figure 2. Please
select the corresponding product base from your operating system.

Figure 2.2 Java SE Download Listing

Source: https://www.oracle.com/java/technologies/javase-jdk15-downloads.html

For the installation process under Windows operating system. Please visit the link
provided below:

https://bit.ly/2WWhpOv

16
Lesson 3. Installing Additional Android SDK in the android
studio.
According to Meier & Lake (2018), you can download older platform versions, as well as
additional SDK components using the SDK Manager. The SDK Manager (Figure 2.3) isavailable
through a shortcut on the toolbar, the Android SDK settings option, or from within the Tools
➪ Android ➪ SDK Manager menu item. It offers tabs for SDK Platforms, SDK Tools,and SDK
Update Sites

Figure 2.3 SDK Manager

Source: Android Studio

The SDK Platforms tab shows which platform SDKs you have downloaded. By default,
this will include the newest Android platform SDK

The SDK Tools tab shows which tools and support libraries you have installed, including
the SDK, platform, and build tools—as well as the support repository, which is required to use
the Android Support Library

By selecting the Show Package Contents Details checkbox, you can find additional details
on which versions each tool has been installed.

17
Lesson 4. Hello World example.
According to Meier & Lake (2018), with Android Studio installed and also the SDK
downloaded you’re able to begin developing apps for Android. You’ll begin by making a brand-
new Android project, configuring the Android individual, and fitting your Android Studio run
and rectify configurations, as delineated within the following sections.

Creating a New Android Project (Meier & Lake, 2018)

To create a new Android project using Android Studio’s New Project Wizard, do the following:

1. The first time you begin Android Studio you're bestowed with the welcome screen shown
in Figure 2-4. you'll be able to come back to the present screen by choosing the File ➪
shut menu item to shut any open projects. From the welcome screen, choose the “Start a
brand-new Android Studio project” choice. as an alternative, among Android Studio
choose the File ➪ New ➪ New Project... menu item.

Figure 2.4 Android Studio Start Up page

Source: Android Studio

2. In the wizard that appears, enter the details for your new project. On the first page (Figure
2-5) enter an Application Name and your Company Domain. These will be combined to
create a unique Package Name as displayed on the wizard. Each Android application

18
must have a unique package name, so it’s good practice to use a domain you own to
minimize the chance of a collision. That said, owning the domain you use isn’t required or
enforced, so you can use almost any domain you want provided the resulting package
name is unique.

Finally, select the directory location to which your project will be saved.

Figure 2.5 New Project

Source: Android Studio

3. The next page (Figure 2-6) lets you select the form factors you wish to support within this
project, as well as the minimum Android platform version on which your application will
run. To get started, we’ll target just phones and tablets and use the default minimum SDK.
Selecting the minimum SDK version allows you to choose the level of backward
compatibility you’re willing to support. The lower this SDK version, the more devices will
be able to run your app, but this will also make it more challenging to support newer
platform features. Selecting each minimum SDK from the drop down will display the
proportion of active Android devices running that platform version.

19
Figure 2.6 Project SDK Selection

Source: Android Studio

4. The next page (Figure 2-7) lets you select a template for your app’s main Activity (user
interface screen). Select the Empty Activity.

Figure 2.7 Project Template

Source: Android Studio

20
5. The final page (Figure 2-8) allows you to specify the class name for your initial Activity, and
specify the name for the XML file that will be used to provide the Activity’s UI layout.In the
case of the empty Activity template, you can also choose if you wish the wizard to generate
a layout file at all. You also have the option to make your Activity backward compatible by
selecting the Backwards Compatibility check box, which is highly recommended. Marking
this box checked will result in the new Activity inheriting from theAndroid Support Library’s
AppCompatActivity class rather than the framework’s Activity class, which will allow your
Activity to take advantage of new API features in a way that’s backward compatible.

Figure 2.8 Project Main Activity


Source: Android Studio

6. When you’ve entered these details, click Finish

Android Studio will now create a new project that includes a class that extends
AppCompatActivity. Rather than being completely empty, the default template implements “
Hello World.”

21
Before modifying the project, take this opportunity to create an Android Virtual Device, enable
debugging on a physical device, and run our new Hello World project.

Lesson 5. Creating an Android Virtual Device (Meier & Lake,


2018)
Android Virtual Devices (AVDs) are used to simulate the hardware and software
configurations of physical Android devices. The Android Emulator runs within AVDs, allowing
you test your applications on a variety of different hardware and software platforms.
According to Meier & Lake (2018), there are no prebuilt AVDs included in the Android
Studio or Android SDK downloads so, if you don’t have a physical device, you’ll need to create
at least one before you can run and debug your applications:
1. Select Tools ➪ Android ➪ AVD Manager (or select the AVD Manager icon on the Android
Studio toolbar).
2. Click the “Create Virtual Device…” button. The resulting Virtual Device Configuration dialog
box (Figure 2-9) allows you to select a device definition from a list of Pixel and Nexus
hardware and standard device configurations; each with its own physical size, resolution,
and pixel density.

Figure 2.9 Virtual Device Selection


Source: Android Studio

22
3. You’ll then be asked to select a device system image corresponding to a particular Android
platform release, as shown in Figure 2-10. If you have not already done so, you will need
to download the desired system image before it can be used. Notice that for each platform
release you can choose system images for different ABIs (application binary interfaces)—
typically x86 or ARM. Consider using a system image using the same architecture as your
host computer to maximize Emulator performance. You can also decide if you want a
system image that includes the Google API’s. These are necessary if your app includes
Google Play Services features such as maps and Location Based Services

Figure 2.10 Android OS selection


Source: Android Studio

4. Specify a descriptive device name, and then hit Finish to create a new AVD, as shown in
Figure 2-11. Note that by clicking Show Advanced Settings you can reveal additional
options to assign your webcam to the front or rear camera, adjust the emulated network
speed and latency, and customize the number of emulated cores, system memory, and
storage

23
5. Starting a new AVD can take some time, so start it now by clicking the green arrow in the
right-most column. This will ensure the emulator is prepared and running when you’re
ready to run your app on it.

Figure 2.11 Virtual Device configuration


Source: Android Studio

Take a step back and have a look at the source code for your first Android application,
starting with the MainActivity.java file. In Android, Activity is the base class for the visual,
interactive screens within your application; it is roughly equivalent to a Form in traditional
desktop development AppCompatActivity is a variation of the Activity class supplied by the
Android Support Library, which provides backward compatibility. Using AppCompatActivity in
preference to the Activity class is considered best practice, and we’ll be doing so throughout
this book. Note that by convention we still refer to classes that extend AppCompatActivity as
Activities (Meier & Lake, 2018).

24
Figure 2.12 Hello World application

Source: Android Studio

The skeleton code for an Activity is shown below; note that it extends AppCompatActivity and
overrides the onCreate method.

package com.professionalandroid.apps.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


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

25
Visual parts among Activities are referred to as Views, that are just like controls or widgets
in ancient desktop and internet development. The Hello World guide created by the wizard
overrides the onCreate methodology to decision setContentView, that lays out the UI by
inflating a layout resource, as highlighted in daring within the following snippet:

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

The resources for Android project are keep within the res folder of your project hierarchy,
which incorporates layout, values, drawable, and mipmap subfolders. Android Studio
interprets these resources and provides design-time access to them through the R variable.
the specific layout created as a part of the Android Project Wizard might change over time,
therefore your layout might look slightly different to the XML shown here, though' the ensuing
UI ought to seem very similar.
The UI layout as defined in the activity_main.xml file created by the Android project
template and stored in the project’s res/layout folder.

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


<android.support.constraint.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="com.professionalandroid.apps.myapplication.Ma
inActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>

26
Defining your UI in XML and inflating it is the preferred way of implementing your user
interfaces (UIs), because it neatly decouples your application logic from your UI design.
To get access to your UI elements in code, you can add identifier attributes to them in
the XML definition:

<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/><TextView
android:id="@+id/myTextView"

You can then use the findViewById method to return a reference to each named item at
run time:

TextView myTextView = findViewById(R.id.myTexTextView myTextView =


findViewById(R.id.myTextView);tView);

For additional reference, you could watch the video from the following link:

https://bit.ly/3g7YlEp

Assessment Task

1. Based from the Hello World example, modify the codes to make the android
application display your fullname and birthday using two TextView. Provide the codes
of the UI Layout XML only.

27
Summary

Android Studio is the official IDE for Android application development supported IntelliJ
plan. On prime of the capabilities you expect from IntelliJ, Android Studio offers versatile
Gradle-based build system, Build variants and multiple apk file generation, Code templates to
assist you to build common app options, wealthy layout editor with support for drag and drop
theme redaction, lint tools to catch performance, usability, version compatibility, and different
issues, ProGuard and app-signing capabilities, intrinsic support for Google Cloud Platform,
creating it straightforward to integrate Google Cloud electronic messaging and App Engine,
and a lot more

References
Android - Activities - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from
https://www.tutorialspoint.com/android/android_acitivities.htm

Android - Application Components - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from
https://www.tutorialspoint.com/android/android_application_components.htm

Android - Architecture - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from


https://www.tutorialspoint.com/android/android_architecture.htm

Android - Overview - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from


https://www.tutorialspoint.com/android/android_overview.htm

Android Resources Organizing & Accessing - Tutorialspoint. (n.d.). Retrieved August 20,
2020, from https://www.tutorialspoint.com/android/android_resources.htm

Darwin, I. F. (2017). Android Cookbook: Problems and Solutions for Android Developers (2nd
ed.). O’Reilly Media. https://www.amazon.com/Android-Cookbook-Problems-Solutions-
Developers/dp/1449374433

Meier, R., & Lake, I. (2018). Professional Android (D. Ulery, E. Woodward, C. Krause, & M.
Yener (Eds.); 4th ed.). John Wiley & Sons, Inc. https://www.wiley.com/en-
us/Professional+Android%2C+4th+Edition-p-9781118949528

28
MODULE 3
ANDROID ANATOMY

Introduction

As discussed in the study of Meier & Lake (2018, p. 58), android applications (or simply
“apps”) are software programs that are installed and run natively on Android devices. To write
high-quality applications, it’s important to understand the components they consist of, and
how those components work together. This chapter introduces each of the application
components, with special attention paid to Activities and Fragments the visual components of
your application.

The Activity class forms the basis for all your user interface (UI) screens. You’ll learn
how to create Activities and gain an understanding of their life cycles and how they affect the
application lifetime and priority.

The range of screen sizes and display resolutions for the devices on which your
application will be used has expanded with the range of Android devices now available. The
Fragment API provides support for creating dynamic layouts that can be optimized for all
devices including tablets and smartphones (Meier & Lake, 2018, p. 58).

Learning Outcomes
At the end of this module, students should be able to:

1. Identify what are basic parts of an android application.


2. Recognize where to categorize different type of resources.
3. Examine the XML codes in the android development.

29
Lesson 1. The Main Activity File
(Android - Application Components - Tutorialspoint, n.d.)
The main activity code is a Java file MainActivity.java. This is the actual application file

which ultimately gets converted to a Dalvik executable and runs your application. Following is

the default code generated by the application wizard for Hello World! Application (Android -

Application Components - Tutorialspoint, n.d.).


package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout

folder. The onCreate() method is one of many methods that are fired when an activity is
loaded.

Lesson 2. Manifest File (Android - Application Components -


Tutorialspoint, n.d.)
Whatever component you develop as a part of your application, you must declare all its

components in a manifest file called AndroidManifest.xml which resides at the root of the

application project directory. This file works as an interface between Android OS and your

30
application, so if you do not declare your component in this file, then it will not be considered

by the OS. For example, a default manifest file will look like as following file:
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN"
/>
<category
android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

Here <application>...</application> tags enclosed the components related to the

application. Attribute android:icon will point to the application icon available

underres/drawable-hdpi. The application uses the image named ic_launcher.png located in

the drawable folders.

The <activity> tag is used to specify an activity and android:name attribute specifies the

fully qualified class name of the Activity subclass and the android:label attributes specifies a

string to use as the label for the activity. You can specify multiple activities using <activity>

tags.

The action for the intent filter is named android.intent.action.MAIN to indicate that this
activity serves as the entry point for the application. The category for the intent-filter is named

31
android.intent.category.LAUNCHER to indicate that the application can be launched from the

device's launcher icon.

The @string refers to the strings.xml file explained below. Hence, @string/app_name refers

to the app_name string defined in the strings.xml file, which is "HelloWorld". Similar way, other

strings get populated in the application.


Following is the list of tags which you will use in your manifest file to specify different

Android application components:


 <activity>elements for activities

 <service> elements for services

 <receiver> elements for broadcast receivers

 <provider> elements for content providers

Lesson 3. Strings File (Android - Application Components -


Tutorialspoint, n.d.)
The strings.xml file is located in the res/values folder and it contains all the text that your

application uses. For example, the names of buttons, labels, default text, and similar types of

strings go into this file. This file is responsible for their textual content. For example, a default

string file will look like as following file (Android - Application Components - Tutorialspoint,

n.d.):
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>

Lesson 4. R File (Android - Application Components - Tutorialspoint,


n.d.).

32
The gen/com.example.helloworld/R.java file is the glue between the activity Java files

likeMainActivity.java and the resources like strings.xml. It is an automatically generated file

and you should not modify the content of the R.java file. Following is a sample of R.java file

(Android - Application Components - Tutorialspoint, n.d.):

/* AUTO-GENERATED FILE. DO NOT MODIFY.


*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.helloworld;
public final class R {
public static final class attr {
}
public static final class dimen {
public static final int padding_large=0x7f040002;
public static final int padding_medium=0x7f040001;
public static final int padding_small=0x7f040000;
}
public static final class drawable {
public static final int ic_action_search=0x7f020000;
public static final int ic_launcher=0x7f020001;
}
public static final class id {
public static final int menu_settings=0x7f080000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int activity_main=0x7f070000;
}
public static final class string {
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050001;
public static final int menu_settings=0x7f050002;
public static final int title_activity_main=0x7f050003;
}
public static final class style {
public static final int AppTheme=0x7f060000;
}
}

33
Lesson 5. Layout File (Android - Application Components -

Tutorialspoint, n.d.)
The activity_main.xml is a layout file available in res/layout directory that is referenced by

your application when building its interface. You will modify this file very frequently to change

the layout of your application. For your "Hello World!" application, this file will have following

content related to default layout (Android - Application Components - Tutorialspoint, n.d.):

<RelativeLayout
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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>

This is an example of simple RelativeLayout. The TextView is an Android control used to

build the GUI and it has various attributes like android:layout_width, android:layout_height,
etc., which are being used to set its width and height etc. The @string refers to the strings.xml

file located in the res/values folder. Hence, @string/hello_world refers to the hello string

defined in the strings.xml file, which is "Hello World!".

Lesson 6. Different Resources folder


(Android - Application Components - Tutorialspoint, n.d.).
There are many more items which you use to build a good Android application. Apart from

coding for the application, you take care of various other resources like static content that your

34
code uses, such as bitmaps, colors, layout definitions, user interface strings, animation

instructions, and more. These resources are always maintained separately in various sub-

directories under res/ directory of the project.

You should place each type of resource in a specific subdirectory of your project's

res/directory. For example, here's the file hierarchy for a simple project:

MyProject/
src/
MyActivity.java
res/
drawable/
icon.png
layout/
activity_main.xml
info.xml
values/
strings.xml

The res/ directory contains all the resources in various sub-directories. Here we have an

image resource, two layout resources, and a string resource file. Following table gives a detail

about the resource directories supported inside project res/ directory.

Table 3.1 Resource Folder (TutorialsPoint, 2022)

Directory Resource Directory Resource Type

Type

anim/ XML files that define property animations. They are saved in

res/anim/ folder and accessed from the R.anim class.

color/ XML files that define a state list of colors. They are saved in
res/color/ and accessed from the R.color class.

35
drawable/ Image files like .png, .jpg, .gif or XML files that are compiled

into bitmaps, state lists, shapes, animation drawables. They

are saved in res/drawable/ and accessed from the R.drawable

class.Image files like .png, .jpg, .gif or XML files that are

compiled into bitmaps, state lists, shapes, animation

drawables. They are saved in res/drawable/ and accessed


from the R.drawable class.

layout/ XML files that define a user interface layout. They are saved in

res/layout/ and accessed from the R.layout class.

menu/ XML files that define application menus, such as an Options

Menu, Context Menu, or Sub Menu. They are saved in

res/menu/ and accessed from the R.menu class.

raw/ Arbitrary files to save in their raw form. You need to call
Resources.openRawResource() with the resource ID, which is

R.raw.filename to open such raw files.

values/ XML files that contain simple values, such as strings, integers,

and colors. For example, here are some filename conventions

for resources you can create in this directory:

 arrays.xml for resource arrays, and accessed from the


R.array class.
 integers.xml for resource integers, and accessed from the
R.integer class.

 bools.xml for resource boolean, and accessed from the

R.bool class.

 colors.xml for color values, and accessed from the R.color

class.
 dimens.xml for dimension values, and accessed from the

R.dimen class.

36
 strings.xml for string values, and accessed from the

R.string class.
 styles.xml for styles, and accessed from the R.style class.

xml/ Arbitrary XML files that can be read at runtime by calling

Resources.getXML(). You can save various configuration files

here which will be used at run time.

Lesson 7. How to access a resource


(Android - Application Components - Tutorialspoint, n.d.).

During your application development you will need to access defined resources either in

your code, or in your layout XML files. Following section explains how to access yourresources

in both the scenarios. When your Android application is compiled, a R class gets generated,

which contains resource IDs for all the resources available in your res/ directory. You can use

R class to access that resource using sub-directory and resource name or directly resource ID

(Android Resources Organizing & Accessing - Tutorialspoint, n.d.).

Accessing resources through code

Example: To access res/drawable/myimage.png and set an ImageView you will use following

code:
ImageView imageView = (ImageView)
findViewById(R.id.myimageview);
imageView.setImageResource(R.drawable.myimage);

Here first line of the code uses the R.id.myimageview to get ImageView defined with id

myimageview in a Layout file. Second line of code uses the R.drawable.myimage to get an

image with name myimage available in drawable sub-directory under /res.

Example: Consider next example where res/values/strings.xml has following definition.

37
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello, World!</string>
</resources>

Now you can set the text on a TextView object with ID msg using a resource ID as follows
TextView msgTextView = (TextView) findViewById(R.id.msg);
msgTextView.setText(R.string.hello);

Example: Consider a layout res/layout/activity_main.xml with the following definition:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>

This application code will load this layout for an Activity, in the onCreate() method as follows:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}

38
Accessing Resources through XML
Consider the following resource XML res/values/strings.xml file that includes a color
resource and a string resource:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="opaque_red">#f00</color>
<string name="hello">Hello!</string>
</resources>

Now you can use these resources in the following layout file to set the text color and text
string as follows
<?xml version="1.0" encoding="utf-8"?>
<EditText
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@color/opaque_red"
android:text="@string/hello" />

Now if you go through the previous chapter once again where we have explained Hello
World! example, surely you will have better understanding on all the concepts explained in
this chapter.

Assessment Task

1. With the additional information, modify the hello world example to display your full
name only and get the string value from the strings.xml file. Provide the codes of the
UI Layout XML only and Strings XML.

Summary
There are many more items which you use to build a good Android application. Apart
from coding for the application, you take care of various other resources like static content
that your code uses, such as bitmaps, colors, layout definitions, user interface strings,

39
animation instructions, and more. These resources are always maintained separately in
various sub-directories under res/ directory of the project.

References

Android - Activities - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from


https://www.tutorialspoint.com/android/android_acitivities.htm

Android - Application Components - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from
https://www.tutorialspoint.com/android/android_application_components.htm

Android - Architecture - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from


https://www.tutorialspoint.com/android/android_architecture.htm

Android - Overview - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from


https://www.tutorialspoint.com/android/android_overview.htm

Android Resources Organizing & Accessing - Tutorialspoint. (n.d.). Retrieved August 20,
2020, from https://www.tutorialspoint.com/android/android_resources.htm

Darwin, I. F. (2017). Android Cookbook: Problems and Solutions for Android Developers (2nd
ed.). O’Reilly Media. https://www.amazon.com/Android-Cookbook-Problems-Solutions-
Developers/dp/1449374433

Meier, R., & Lake, I. (2018). Professional Android (D. Ulery, E. Woodward, C. Krause, & M.
Yener (Eds.); 4th ed.). John Wiley & Sons, Inc. https://www.wiley.com/en-
us/Professional+Android%2C+4th+Edition-p-9781118949528

40
MODULE 4
ANDROID ACTIVITIES

Introduction

Android applications (or simply “apps”) are software programs that are installed and
run natively on Android devices. To write high-quality applications, it’s important to understand
the components they consist of, and how those components work together. This chapter
introduces each of the application components, with special attention paid to Activities.

In this chapter, you learn how the Android Run Time manages your application, and
the impact this has on the application life cycle. An application’s state determines its priority
that, in turn, affects the likelihood of its being terminated when the system requires more
resources (Meier & Lake, 2018, p. 58).

Learning Outcomes
At the end of this module, students should be able to:

1. Recognize the android life cycle.


2. Examine the different callback events in android application.
3. Write codes for an android application that will use the events to handle the different
states in the activity lifetimes.

Lesson 1. What is android activity.

An activity represents one screen with a user interface. For instance, an email application

may need one activity that shows a listing of recent emails, another activity to compose an

email, and another activity for reading emails. If an application has over one activity, then one

41
of them should be marked as the activity that is presented when the application is launched

(Android - Activities - Tutorialspoint, n.d.).

Lesson 2. Android Activity Life Cycle

According to Meier & Lake, 2018, p. 59, each Android application runs in its own process,

each of which is running a separate instance of the Android Run Time (ART). Memory and

process management is handled exclusively by the run time.

Android system initiates its program within an Activity starting with a call on onCreate()

callback method. There is a sequence of callback methods that start up an activity and a

sequence of callback methods that tear down an activity as shown in the below Activity

lifecycle diagram.

Figure 4.1 Android Activity Life Cycle

Source: TutorialsPoint – Android Activities

The Activity class defines the following callbacks i.e. events. You don't need to implement
all the callback methods. However, it's important that you understand each one and implement

those that ensure your app behaves the way users expect (Android - Activities - Tutorialspoint,

n.d.).

Table 4.1 Activity Callback (TutorialsPoint, 2022)

Callback Description

onCreate() This is the first callback and called when the activity is first created.

42
onStart() This callback is called when the activity becomes visible to the user

onResume() This is called when the user starts interacting with the application.

onPause() The paused activity does not receive user input and cannot execute

any code and called when the current activity is being paused and

the previous activity is being resumed.

onStop() This callback is called when the activity is no longer visible.

onDestroy() This callback is called before the activity is destroyed by the

system.

onRestart() This callback is called when the activity restarts after stopping it.

Example: This example will take you through simple steps to show Android application activity life

cycle. Follow the below mentioned steps to modify the Android application we created inHello

World Example chapter.

STEP 1: You will use Android Studio to create an Android application and name it as

HelloWorld under a package com.example.helloworld as explained in the Hello World Example

chapter.

STEP 2: Modify main activity file MainActivity.java as explained below. Keep rest of the files

unchanged.
STEP 3: Run the application to launch Android emulator and verify the result of the changes
done in the application.

Following is the content of the modified main activity file

src/com.example.helloworld/MainActivity.java. This file includes each of the fundamental

lifecycle methods. The Log.d() method has been used to generate log messages:

43
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class MainActivity extends Activity {

String msg = "Android : ";


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, "The onCreate() event");
}

/** Called when the activity is about to become visible. */


@Override
protected void onStart() {
super.onStart();
Log.d(msg, "The onStart() event");
}

/** Called when the activity has become visible. */


@Override
protected void onResume() {
super.onResume();
Log.d(msg, "The onResume() event");
}

/** Called when another activity is taking focus. */


@Override
protected void onPause() {
super.onPause();
Log.d(msg, "The onPause() event");
}

44
Code continuation

/** Called when the activity is no longer visible. */


@Override
protected void onStop() {
super.onStop();
Log.d(msg, "The onStop() event");
}

/** Called just before the activity is destroyed. */


@Override
public void onDestroy() {
super.onDestroy();
Log.d(msg, "The onDestroy() event");
}
}

An activity class loads all the UI component using the XML file available in res/layout folder
of the project. Following statement loads UI components from res/layout/activity_main.xml file:

setContentView(R.layout.activity_main);

An application can have one or more activities without any restrictions. Every activity you

define for your application must be declared in your AndroidManifest.xml file and the main

activity for your app must be declared in the manifest with an <intent-filter> that includes the

MAIN action and LAUNCHER category as follows:

45
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category

android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

If either the MAIN action or LAUNCHER category are not declared for one of your activities,

then your app icon will not appear in the Home screen's list of apps. Let's try to run our

modified Hello World! application we just modified. We assume, you had created your AVD

while doing environment setup. if everything is fine with your setup and application, it willdisplay

Emulator window and you should see following log messages in LogCat window

07-19 15:00:43.405: D/Android :(866): The onCreate() event


07-19 15:00:43.405: D/Android :(866): The onStart() event
07-19 15:00:43.415: D/Android :(866): The onResume() event

Let us try to click Red button on the Android emulator and it will generate following events
messages in LogCat window.

46
07-19 15:01:10.995: D/Android :(866): The onPause() event
07-19 15:01:12.705: D/Android :(866): The onStop() event

Let us again try to click Menu button on the Android emulator and it will generate following

events messages in LogCat window.

07-19 15:01:13.995: D/Android :(866): The onStart() event


07-19 15:01:14.705: D/Android :(866): The onResume() event

Next, let us again try to click Back button on the Android emulator and it will generate

following events messages in LogCat window and this completes the Activity Life Cycle for an

Android Application.

07-19 15:33:15.687: D/Android :(992): The onPause() event


07-19 15:33:15.525: D/Android :(992): The onStop() event
07-19 15:33:15.525: D/Android :(992): The onDestroy() event

Lesson 3. Activity State

In accordance in the discussion of Meier & Lake (2018, pp. 65–66), throughout an

application’s life cycle, its Activities move in and out of the Activity stack, as shown in Figure

4.2. As they do so, they transition through four possible states:

Figure 4.2 Activity State

Source: Meier & Lake (2018)

47
Active - When an Activity is at the highest of the stack it is the visible, focused, foreground

Activity that is receiving user input. android will decide to keep it alive at all costs, killing

applications that own Activities more down the stack as needed, to make sure this Activity has

the resources it needs. when another Activity becomes active, this one are going to be

paused—and when it is no longer visible, it will be stopped, as described within the following

points (Meier & Lake, 2018, p. 65).

Paused - In some cases your Activity are going to be visible but will not have focus; at this

time it’s paused. This state might also be reached within which your application is being used

in a multiwindow environment—where multiple applications could also be visible, however

only the Activity with which the user last interacted is considered active. Similarly, if your

Activity features a clear or non–full-screen Activity active in front of it, it will remain in a paused

state. When paused, an Activity is treated as if it were active; however, it doesn’t receive user

input events. In extreme cases android will kill a paused Activity to recover resources for the

active Activity. When an Activity becomes entirely obscured, it is stopped; all Activities

transition through the paused state before changing into stopped (Meier & Lake, 2018, p. 65).

Stopped - When an Activity isn’t visible, it “stops.” The Activity will remain in memory,

retaining all state information; however, it is now a likely candidate for termination when the

system requires memory. When an Activity is in a stopped state, it’s important to save data

and the current UI state, and to stop any non-critical operations. Once an Activity has exited
or closed, it becomes inactive (Meier & Lake, 2018, p. 66).
Inactive - After an Activity has been killed, as well as before it’s been launched, it’s inactive.
Inactive Activities have been removed from the Activity stack and need to be restarted before
they can be displayed and used (Meier & Lake, 2018, p. 66).

State transitions occur through user and system actions, meaning your application has no

control over when they happen. Similarly, application termination is handled by the Android

memory manager, which will start by closing applications that contain inactive Activities,
followed by those that are stopped. In extreme cases, it will remove those that are paused

(Meier & Lake, 2018, p. 66).

48
Lesson 4. Activity Lifetimes

According to Meier & Lake (2018), to ensure that Activities can react to state changes,

Android provides a series of event handlers that are fired as an Activity transitions through its

full, visible, and active lifetimes. Figure 4.3 summarizes these lifetimes in terms of the Activity

states described in the previous section.

Figure 4.3 Activity Lifetime

Source: Meier & Lake (2018)

Within an Activity’s full lifetime, between creation and destruction, it goes through one or
more iterations of the active and visible lifetimes. Each transition triggers the method handlers

previously described. The following sections provide a closer look at each of these lifetimes

and the events that bracket them (Meier & Lake, 2018, p. 66).

The Full Lifetime

According to Meier & Lake (2018, p. 67), the full lifetime of your Activity occurs between

the first call to onCreate and when it is destroyed. It’s not uncommon for an Activity’s process

to be terminated without the corresponding onDestroy handler being called.

Use the onCreate method to initialize your Activity: inflate the user interface, get references

to Fragments, allocate references to class variables, bind data to controls, andstart Services.

If the Activity was terminated unexpectedly by the run time, the onCreate method is passed a

Bundle object containing the state saved in the last call to onSaveInstanceState. You should

use this Bundle to restore the UI to its previous state, either within the onCreate method or

onRestoreInstanceState (Meier & Lake, 2018, p. 67).

49
Override onDestroy to clean up any resources created in onCreate, and ensure that all

external connections, such as network or database links, are closed.

As part of Android’s guidelines for writing efficient code, it’s recommended that you avoid

repeated creation of short-term objects. The rapid creation and destruction of objects forces

additional garbage collection, a process that can have a direct negative impact on the user

experience. If your Activity creates the same set of objects regularly, consider creating them

in the onCreate method, as it’s called only once during the Activity’s lifetime (Meier & Lake,

2018, p. 67).

The Visible Lifetime

As explained by Meier & Lake, 2018, p. 67, an Activity’s visible lifetimes are bounded

between calls to onStart and onStop. Between these calls your Activity will be visible to the

user, although it may not have focus and may be partially obscured. Activities are likely to go

through several visible lifetimes during their full lifetime as they move between the foreground

and background. Since Android 3.0 Honeycomb (API Level 11), you can safely assume onStop

will be called before your application process is terminated (Meier & Lake, 2018, p. 67).

The onStop method should be used to pause or stop animations, threads, Sensor listeners,

GPS lookups, Timers, Services, or other processes that are used exclusively to update the UI.

There’s little value in consuming resources (such as memory, CPU cycles, or network

bandwidth) to update the UI when it isn’t visible. Use the onStart method to resumeor restart

these processes when the UI is visible again (Meier & Lake, 2018, p. 68).

The onRestart method is called immediately prior to all but the first call to onStart. Use it

to implement special processing that you want done only when the Activity restarts within its

full lifetime (Meier & Lake, 2018, p. 68).

The onStart/onStop methods should also be used to register and unregister Broadcast

Receivers used exclusively to update the UI.

The Active Lifetime

50
The active lifetime starts with a call to onResume and ends with a corresponding call to

onPause. An active Activity is in the foreground and is receiving user input events. Your Activity

is likely to go through many active lifetimes before it’s destroyed, as the active lifetimewill end

when a new Activity is displayed, the device goes to sleep, or the Activity loses focus.Try to

keep code in the onPause and onResume methods fast and lightweight to ensure that your

application remains responsive when moving in and out of the foreground. You can safely

assume that during the active lifetime onPause will be called before the process is terminated

(Meier & Lake, 2018, p. 68).

Remark: If the system determines that this Activity state may need to be resumed, then

immediately before onPause a call is made to onSaveInstanceState. This method provides

an opportunity to save the Activity’s UI state in a Bundle that may be passed to the onCreate

and onRestoreInstanceState methods. Use onSaveInstanceState to save the UI state toensure

that the Activity can present the same UI when it next becomes active. The

onSaveInstanceState handler will not be called if the system determines that the current state

will not be resumed—for example, if the Activity is closed by pressing the Back button.

Since Android 3.0 Honeycomb (API Level 11), the completion of the onStop handler marks

the point beyond which an Activity may be killed without warning. This allows you to move all

time-consuming operations required to save state into onStop, keeping your onPause

lightweight and focused on suspending memory- or CPU-intensive operations while the


Activity isn’t active. Depending on your application architecture, that may include suspending

threads, processes, or Broadcast Receivers while your Activity is not in the foreground (Meier

& Lake, 2018, p. 68).

The corresponding onResume method should also be lightweight. You do not need to

reload the UI state here, because this should handled by the onCreate and

onRestoreInstanceState methods as required. Use onResume to reverse actions performed

within onPause—such as allocating released resources, initializing or registering removed or

unregistered components, and resuming any suspended behavior.

51
Lesson 5. Process Priority

According to Meier & Lake (2018), Android aggressively manages its resources, doing

whatever is necessary to ensure a smooth and stable user experience. In practice, that means

processes (and therefore applications) will be killed, in some cases without warning, to free

resources if higher priority applications require them.

The order in which processes are killed to reclaim resources is determined by the priority

of their hosted applications. An application’s priority is equal to that of its highest priority

component. If two applications have the same priority, the process that has been at that

priority longest will typically be killed first. Process priority is also affected by interprocess

dependencies; if an application has a dependency on a Service or Content Provider supplied

by a second application, the secondary application is assigned at least as high a priority as the

application it supports (Meier & Lake, 2018, p. 60).

It’s important to structure your application to ensure that its priority is appropriate for the

work it’s doing. If you don’t, your application could be killed while it’s in the middle of something

important, or it could remain running when it could safely be terminated to free resources and

maintain a smooth user experience (Meier & Lake, 2018, p. 60).


Figure 4.2 shows the priority tree used to determine the order of application termination.

Figure 4.4 Activity Priority Tree

Source: Meier & Lake (2018)

52
Active processes (Top Priority)

Active (foreground) processes have application components the user is interacting with. These

are the processes Android tries to keep running smoothly and responsively by reclaiming

resources from other applications. There are generally very few of these processes(Meier &

Lake, 2018, p. 60).

Active processes include one or more of the following components:

 Activities in an active state—that is, those in the foreground responding to user events.

You explore Activity states in greater detail later in this chapter.


 Broadcast Receivers executing onReceive event handlers.

 Services executing onStart, onCreate, or onDestroy event handlers.

Visible processes (High Priority)

Visible but inactive processes are those hosting “visible” Activities or foreground Services.

As the name suggests, visible Activities are visible but they aren’t in the foreground or

responding to user input. This happens when an Activity is only partially obscured (by a non–

full-screen or transparent Activity), or the non-active window in a multi-window environment.

There are generally very few visible processes, and they’ll be killed only under extreme

circumstances to allow active processes to continue. Since Android 6.0 Marshmallow (API Level

23), running Services that have been flagged to run in the foreground have a slightly lower

priority than active processes, making it possible—though unlikely—for a foreground Service

to be killed to allow an active Activity with significant memory requirements to continue running

(Meier & Lake, 2018, p. 61).

Started background Service processes (Medium Priority)

Processes hosting background Services that have been started. Because these Services

don’t interact directly with the user, they receive a slightly lower priority than visible Activities

or foreground Services (Meier & Lake, 2018, p. 61).

53
Background processes (Low Priority)

Processes hosting Activities that aren’t visible and that don’t have any running Services.

Every time you switch between applications by pressing the home key, or using the “recent

apps” selector, the previously active application goes to the background. There will generally

be a large number of background apps that Android will kill using a last-seen-first-killed

pattern, giving some consideration to prioritize killing applications consuming more memory,

in order to obtain resources for foreground processes (Meier & Lake, 2018, p. 61).

Assessment Task

1. Modify the MainActivity Java File so that it will pass your name in the Log Cat when
you launch the activity. Given that there are two variables named num1 and num2 with
the values 5 and 10 respectively, add 3 to each variable every time the application has
been launched and paused.

Summary
This section explains the activity lifecycle in detail and begins by describing the lifecycle
paradigm. Next, it explains each of the callbacks: what happens internally while they execute,
and what you should implement during them. It then briefly introduces the relationship
between activity state and a process’s vulnerability to being killed by the system. Last, it
discusses several topics related to transitions between activity states.

54
References
Android - Activities - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from
https://www.tutorialspoint.com/android/android_acitivities.htm

Android - Application Components - Tutorialspoint. (n.d.). Retrieved August 20, 2020,


from
https://www.tutorialspoint.com/android/android_application_components.htm

Android - Architecture - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from


https://www.tutorialspoint.com/android/android_architecture.htm

Android - Overview - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from


https://www.tutorialspoint.com/android/android_overview.htm

Android Resources Organizing & Accessing - Tutorialspoint. (n.d.). Retrieved August


20, 2020, from https://www.tutorialspoint.com/android/android_resources.htm

Darwin, I. F. (2017). Android Cookbook: Problems and Solutions for Android


Developers (2nd ed.). O’Reilly Media. https://www.amazon.com/Android-
Cookbook-Problems-Solutions-Developers/dp/1449374433

Meier, R., & Lake, I. (2018). Professional Android (D. Ulery, E. Woodward, C. Krause,
& M. Yener (Eds.); 4th ed.). John Wiley & Sons, Inc. https://www.wiley.com/en-
us/Professional+Android%2C+4th+Edition-p-9781118949528

- END OF MODULE FOR PRELIMINARY TERM PERIOD –


SUBMIISION OF ASSESSMENT TASKS AND EXAMINATION FOR PRELIM PERIOD
WILL BE ANNOUNCED VIA PinNaCle.
MAKE SURE TO CHECK AND DO NOT FORGET TO TAKE IT AS SCHEDULED.

55

You might also like