ITP107 Mobile Dev Draft Module
ITP107 Mobile Dev Draft Module
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
iv
List of Table
Table Description
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
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.).
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.
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.).
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:
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.
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:
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:
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.).
8
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcasted as an Intent object.
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.).
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:
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.
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).
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 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:
13
3. Write a simple android program.
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:
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.
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.
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
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.
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.
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.
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
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.
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.
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.
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
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.
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
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;
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.
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:
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 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:
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 -
folder. The onCreate() method is one of many methods that are fired when an activity is
loaded.
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>
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
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
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>
32
The gen/com.example.helloworld/R.java file is the glue between the activity Java files
and you should not modify the content of the R.java file. Following is a sample of R.java file
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
<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>
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
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-
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
Type
anim/ XML files that define property animations. They are saved in
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
class.Image files like .png, .jpg, .gif or XML files that are
layout/ XML files that define a user interface layout. They are saved in
raw/ Arbitrary files to save in their raw form. You need to call
Resources.openRawResource() with the resource ID, which is
values/ XML files that contain simple values, such as strings, integers,
R.bool class.
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.
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
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
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);
<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 - Application Components - Tutorialspoint. (n.d.). Retrieved August 20, 2020, from
https://www.tutorialspoint.com/android/android_application_components.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:
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
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
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.
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.).
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
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
STEP 1: You will use Android Studio to create an Android application and name it as
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.
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 {
44
Code continuation
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
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
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
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.
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
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
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
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
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
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).
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
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
49
Override onDestroy to clean up any resources created in onCreate, and ensure that all
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).
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
The onStart/onStop methods should also be used to register and unregister Broadcast
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
Remark: If the system determines that this Activity state may need to be resumed, then
an opportunity to save the Activity’s UI state in a Bundle that may be passed to the onCreate
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
threads, processes, or Broadcast Receivers while your Activity is not in the foreground (Meier
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
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
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
by a second application, the secondary application is assigned at least as high a priority as the
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
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 &
Activities in an active state—that is, those in the foreground responding to user events.
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–
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
to be killed to allow an active Activity with significant memory requirements to continue running
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
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
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
55