GL612 Mobile Applications Development
GL612 Mobile Applications Development
SEMESTER 1
COURSE OBJECTIVES:
• Program mobile applications for the Android operating system that use basic
and advanced phone features, and
OUTCOMES
At the end of the course, the students should design, implementation, and pilot
test mobile phone software applications.
KEY POINT TO SEE:
Page 1 of 91
Deployment of a mobile application.
COURSE CONTENT:
Page 2 of 91
Unit 1: Introduction to mobile computing and embedded system
Mobile phones have changed the way we live our lives providing voice calling, text
messaging and mobile Internet access. The very first mobile phones were two-way radios that
allowed taxi drivers and the emergency services to communicate. Motorola, on 3 April 1973
was first company to mass produce the first handheld mobile phone.
Mobile Computing Description
Mobile Computing is a technology that provides an environment that enables users to transmit
data from one device to another device without the use of any physical link or cables.
In other words, you can say that mobile computing allows transmission of data, voice and
video via a computer or any other wireless-enabled device without being connected to a fixed
physical link. In this technology, data transmission is done wirelessly with the help of
wireless devices such as mobiles, laptops etc.
This is only because of Mobile Computing technology that you can access and transmit data
from any remote locations without being present there physically. Mobile computing
technology provides a vast coverage diameter for communication. It is one of the fastest and
most reliable sectors of the computing technology field.
o Mobile Communication
o Mobile Hardware
o Mobile Software
1- Mobile Communication
Mobile Communication specifies a framework that is responsible for the working of mobile
computing technology. In this case, mobile communication refers to an infrastructure that
ensures seamless and reliable communication among wireless devices. This framework
ensures the consistency and reliability of communication between wireless devices. The
mobile communication framework consists of communication devices such as protocols,
services, bandwidth, and portals necessary to facilitate and support the stated services. These
devices are responsible for delivering a smooth communication process.
Page 3 of 91
Mobile communication can be divided in the following four types:
Fixed and Wired: In Fixed and Wired configuration, the devices are fixed at a
position, and they are connected through a physical link to communicate with other
devices.
Fixed and Wireless: In Fixed and Wireless configuration, the devices are fixed at a
position, and they are connected through a wireless link to make communication with
other devices.
Mobile and Wired: In Mobile and Wired configuration, some devices are wired, and
some are mobile. They altogether make communication with other devices.
Mobile and Wireless: In Mobile and Wireless configuration, the devices can
communicate with each other irrespective of their position. They can also connect to
any network without the use of any wired device.
2- Mobile Hardware
Page 4 of 91
Mobile hardware consists of mobile devices or device components that can be used to receive
or access the service of mobility. Examples of mobile hardware can be smartphones, laptops,
portable PCs, tablet PCs, Personal Digital Assistants, etc.
These devices are inbuilt with a receptor medium that can send and receive signals. These
devices are capable of operating in full-duplex. It means they can send and receive signals at
the same time. They don't have to wait until one device has finished communicating for the
other device to initiate communications.
3- Mobile Software
Mobile software is a program that runs on mobile hardware. This is designed to deal capably
with the characteristics and requirements of mobile applications. This is the operating system
for the appliance of mobile devices. In other words, you can say it the heart of the mobile
systems. This is an essential component that operates the mobile device.
Page 5 of 91
This provides portability to mobile devices, which ensures wireless communication.
Following is a list of some significant fields in which mobile computing is generally applied:
o Emergency services.
o Entertainment services.
o Educational services.
Page 6 of 91
Lesson 2: Embedded system
While embedded systems are computing systems, they can range from having no user
interface (UI) for example, on devices designed to perform a single task to complex graphical
user interfaces (GUIs), such as in mobile devices. User interfaces can include buttons, LEDs
(light-emitting diodes) and touchscreen sensing. Some systems use remote user interfaces as
well.
Some research firm, predicted that the embedded market will be worth $116.2 billion by
2025. Chip manufacturers for embedded systems include many well-known technology
companies, such as Apple, IBM, Intel and Texas Instruments. The expected growth is
partially due to the continued investment in artificial intelligence (AI), mobile computing and
the need for chips designed for high-level processing.
Automobiles.
Page 7 of 91
systems perform basic utility functions and others provide entertainment or user-facing
functions. Some embedded systems in consumer vehicles include cruise control, backup
sensors, suspension control, navigation systems and airbag systems.
Mobile phones.
These consist of many embedded systems, including GUI software and hardware, operating
systems (OS), cameras, microphones, and USB (Universal Serial Bus) I/O (input/output)
modules.
Industrial machines.
They can contain embedded systems, like sensors, and can be embedded systems
themselves. Industrial machines often have embedded automation systems that perform
specific monitoring and control functions.
Medical equipment.
These may contain embedded systems like sensors and control mechanisms. Medical
equipment, such as industrial machines, also must be very user-friendly so that human
health isn't jeopardized by preventable machine mistakes. This means they'll often include
a more complex OS and GUI designed for an appropriate UI.
Page 8 of 91
A photo of an embedded system motherboard with attached cables.
The processor may be a microprocessor or microcontroller. Microcontrollers are simply
microprocessors with peripheral interfaces and integrated memory included. Microprocessors
use separate integrated circuits for memory and peripherals instead of including them on the
chip. Both can be used, but microprocessors typically require more support circuitry than
microcontrollers because there is less integrated into the microprocessor. The term system on
a chip (SoC) is often used. SoCs include multiple processors and interfaces on a single chip.
They are often used for high-volume embedded systems. Some example SoC types are the
application-specific integrated circuit (ASIC) and the field-programmable gate array (FPGA).
can be embedded in a larger system to perform a specific function, as they are built for
specialized tasks within the system, not various tasks;
are often used for sensing and real-time computing in internet of things (IoT) devices,
which are devices that are internet-connected and do not require a user to operate;
can vary in complexity and in function, which affects the type of software, firmware
and hardware they use;
Page 9 of 91
Are often required to perform their function under a time constraint to keep the larger
system functioning properly.
Software and firmware. Software for embedded systems can vary in complexity.
However, industrial-grade microcontrollers and embedded IoT systems usually run
very simple software that requires little memory.
Real-time operating system. These are not always included in embedded systems,
especially smaller-scale systems. RTOS define how the system works by supervising
the software and setting rules during program execution.
In terms of hardware, a basic embedded system would consist of the following elements:
Digital-to-analog (D-A) converters change the digital data from the processor into
analog data.
Actuators compare actual output to memory-stored output and choose the correct one.
The sensor reads external inputs, the converters make that input readable to the processor, and
the processor turns that information into useful output for the embedded system.
Page 10 of 91
Diagram of the basic structure and flow of information in embedded systems.
Mobile embedded systems are small-sized systems that are designed to be portable.
Digital cameras are an example of this.
Standalone embedded systems are not reliant on a host system. Like any embedded
system, they perform a specialized task. However, they do not necessarily belong to a
host system, unlike other embedded systems. A calculator or MP3 player is an
example of this.
Real-time embedded systems give the required output in a defined time interval.
They are often used in medical, industrial and military sectors because they are
responsible for time-critical tasks. A traffic control system is an example of this.
Page 11 of 91
Medium-scale embedded systems use a larger microcontroller (16-32 bit) and often
link microcontrollers together.
The embedded system is expected to continue growing rapidly, driven in large part by the
internet of things. Expanding IoT applications, such as wearables, drones, smart homes, smart
buildings, video surveillance, 3D printers and smart transportation, are expected to fuel
embedded system growth.
Page 12 of 91
Unit 2: Android development
Android is a mobile operating system that is based on a modified version of Linux. It was
originally developed by a start-up of the same name, Android, Inc. In 2005, as part of its strategy
to enter the mobile space, Google purchased Android and took over its development work (as
well as its development team). Google wanted Android to be open and free; hence, most of the
Android code was released under the open-source Apache License, which means that anyone
who wants to use Android can do so by downloading the full Android source code. Moreover,
vendors (typically hardware manufacturers) can add their own proprietary extensions to
Android and customize Android to differentiate their products from others. This simple
development model makes Android very attractive and has thus piqued the interest of many
vendors. This has been especially true for companies affected by the phenomenon of
Apple‘s iPhone, a hugely successful product that revolutionized the smartphone industry. Such
companies include Motorola and Sony Ericsson, which for many years have been developing
their own mobile operating systems. When the iPhone was launched, many of these
manufacturers had to scramble to find new ways of revitalizing their products. These
manufacturers see Android as a solution — they will continue to design their own hardware
and use Android as the operating system that powers it. The main advantage of adopting
Android is that it offers a unified approach to application development. Developers need only
develop for Android, and their applications should be able to run on numerous different devices,
as long as the devices are powered using Android. In the world of smartphones, applications
are the most important part of the success chain. Device manufacturers therefore see Android
as their best hope to challenge the onslaught of the iPhone, which already commands a large
base of applications.
2- Android version
Android Versions Android has gone through quite a number of updates since its first release.
The following table shows the version details of android which is released by Google from 2007
to date.
Page 13 of 91
Code Name Version API level Release date
Page 14 of 91
Code Name Version API level Release date
3- Features of android
Page 15 of 91
Android is a powerful open-source operating system that open-source provides immense
features and some of these are listed below.
Android Open Source Project so we can customize the OS based on our requirements.
Android supports different types of connectivity for GSM, CDMA, Wi-Fi, Bluetooth,
etc. for telephonic conversation or data transfer.
Using wifi technology we can pair with other devices while playing games or using
other applications.
We can manage all data storage related activities by using the file manager.
It contains a wide range of media supports like AVI, MKV, FLV, MPEG4, etc. to play
or record a variety of audio/video.
It also supports different image formats like JPEG, PNG, GIF, BMP, MP3, etc.
Page 16 of 91
Android has an integrated open-source WebKit layout based web browser to support
User Interface like HTML5, CSS3.
Android supports multi-tasking means we can run multiple applications at a time and
can switch in between them.
1. Java
2. Kotlin
Developing the Android Application using Kotlin is preferred by Google, as Kotlin is made
an official language for Android Development, which is developed and maintained by
JetBrains. Previously before the Java is considered the official language for Android
Development. Kotlin is made official for Android Development in Google I/O 2017.
5- Android Applications
Android applications are usually developed in the Java language using the Android Software
Development Kit.
Once developed, Android applications can be packaged easily and sold out either through a
store such as Google Play, SlideME, Opera Mobile Store, Mobango, F-droid and
the Amazon Appstore.
Android powers hundreds of millions of mobile devices in more than 190 countries around
the world. It's the largest installed base of any mobile platform and growing fast. Every day
more than 1 million new Android devices are activated worldwide.
There are many android applications in the market. The top categories are −
Page 17 of 91
o Entertainment
o Tools
o Communication
o Productivity
o Personalization
o Social
Page 18 of 91
Lesson 2: Android architecture
Android architecture contains different number of components to support any android device
needs. Android software contains an open-source Linux Kernel having collection of number
of C/C++ libraries which are exposed through an application framework services.
Among all the components Linux Kernel provides main functionality of operating system
functions to smartphones and Dalvik Virtual Machine (DVM) provide platform for running an
android application.
Applications
Application Framework
Android Runtime
Platform Libraries
Linux Kernel
Page 19 of 91
Pictorial representation of android architecture with several main components and their sub
components –
Applications –
Applications is the top layer of android architecture. The pre-installed applications like home,
contacts, camera, gallery etc and third party applications downloaded from the play store like
chat applications, games etc. will be installed on this layer only.
It runs within the Android run time with the help of the classes and services provided by the
application framework.
Page 20 of 91
Application framework –
Application Framework provides several important classes which are used to create an
Android application. It provides a generic abstraction for hardware access and also helps in
managing the user interface with application resources. Generally, it provides the services
with the help of which we can create a particular class and make that class helpful for the
Applications creation.
It includes different types of services activity manager, notification manager, view system,
package manager etc. which are helpful for the development of our application according to
the prerequisite.
Application runtime –
Android Runtime environment is one of the most important part of Android. It contains
components like core libraries and the Dalvik virtual machine(DVM). Mainly, it provides the
base for the application framework and powers our application with the help of the core
libraries.
Like Java Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-based
virtual machine and specially designed and optimized for android to ensure that a device can
run multiple instances efficiently. It depends on the layer Linux kernel for threading and low-
level memory management. The core libraries enable us to implement android applications
using the standard JAVA or Kotlin programming languages.
Platform libraries –
The Platform Libraries includes various C/C++ core libraries and Java based libraries such as
Media, Graphics, Surface Manager, OpenGL etc. to provide a support for android
development.
Media library provides support to play and record an audio and video formats.
Page 21 of 91
SGL (Simple graphic library ) and Open GL( Graphic library) both cross-language,
cross-platform application program interface (API) are used for 2D and 3D computer
graphics.
SQLite provides database support and FreeType provides font support. This open-
source relational database engine is designed to be embedded in devices.
Web-Kit This open source web browser engine provides all the functionality to
display web content and to simplify page loading.
Linux Kernel –
Linux Kernel is heart of the android architecture. It manages all the available drivers such as
display drivers, camera drivers, Bluetooth drivers, audio drivers, memory drivers, etc. which
are required during the runtime.
The Linux Kernel will provide an abstraction layer between the device hardware and the other
components of android architecture. It is responsible for management of memory, power,
devices etc.
Security: The Linux kernel handles the security between the application and the
system.
Driver Model: It ensures that the application works properly on the device and
hardware manufacturers responsible for building their drivers into the Linux build.
Page 22 of 91
Lesson 3: Android application components
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
which can be added by some additional components
Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.
Services
2
They handle background processing associated with an application.
Page 23 of 91
Broadcast Receivers
3
They handle communication between Android OS and applications.
Content Providers
4
They handle data and database management issues.
1- Activities
An activity represents a single screen with a user interface, in-short Activity performs actions
on the screen. It can also be seen as the entry point for interacting with the user
For example, an email application might have one activity that shows a list of new emails,
another activity to compose an email, and another activity for reading emails. If an application
has more than one activity, then one of them should be marked as the activity that is presented
when the application is launched.
An activity facilitates the following key interactions between system and app:
Keeping track of what the user currently cares about (what is on screen)
Knowing that previously used processes contain things the user may return to (stopped
activities)
Helping the app handle having its process killed
Providing a way for apps to implement user flows between each other
Page 24 of 91
2- Services
3- Broadcast Receivers
A broadcast receiver is a component that enables the system to deliver events to the app
outside of a regular user flow, allowing the app to respond to system-wide broadcast
announcements. It simply respond to broadcast messages from other applications or from the
system. For example, applications can also initiate broadcasts to let other applications know
that some data has been downloaded to the device and is available for them to use, so this is
broadcast receiver who will intercept this communication and will initiate appropriate action.
Because broadcast receivers are another well-defined entry into the app, the system can
deliver broadcasts even to apps that aren’t currently running.
Page 25 of 91
Although broadcast receivers don’t display a user interface, they may create a status bar
notification to alert the user when a broadcast event occurs.
4- Content Providers
A content provider manages a shared set of app data that you can store in the file system, in
a SQLite database, on the web, or on any other persistent storage location that your app can
access thus it supplies data from one application to others on request. Such requests are handled
by the methods of the ContentResolver class. The data may be stored in the file system, the
database or somewhere else entirely.
Content providers are also useful for reading and writing data that is private to your app
and not shared.
5- Additional Components
There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are −
Fragments
1
Represents a behaviour or a portion of user interface in an Activity.
Page 26 of 91
Views
2
UI elements that are drawn on-screen including buttons, lists forms etc.
Layouts
3
View hierarchies that control screen format and appearance of the views.
Intents
4
Messages wiring components together.
Resources
5
External elements, such as strings, constants and drawables pictures.
Manifest
6
Configuration file for the application.
Activating components
Three of the four component types—activities, services, and broadcast receivers—are activated
by an asynchronous message called an intent.
Intents bind individual components to each other at runtime. You can think of them as the
messengers that request an action from other components, whether the component belongs to your
app or another.
What is LogCAT?
Logcat is an excellent tool which comes with ADT. It gives you all information about what is
happening in your Android Emulator or Phone if you are using an android phone for testing your
applications.
Page 27 of 91
Why it is Used ?
Android provides a useful logging utility class called android.util.Log. Logging messages are
categorized by severity (and verbosity), with errors being the most severe.
Logcat displays filterable messages that show you what is happening in your android device. You
can filter messages with verbose, warnings, errors etc. • Logcat is the place where all the errors in
application will be printed, whenever you launch your application you can refer Logcat to see what
is happening, in case of any error or force close application.
Below table lists some commonly used logging methods of the Log class.
logCAT in android
Log.wtf () : Logs messages for events that should not happen (like during a failed assert)
The first parameter of each Log method is a string called a tag. One common
Android programming practice is to define a global static string to represent the overall application
or the specific activity within the application such that log filters can be created to limit the log
output to specific data.
Page 28 of 91
For example, you could define a string called TAG, as follows:
Excessive use of the Log utility can result in decreased application performance. Debug and
verbose logging should be used only for development purposes and removed before
application publication.
Page 29 of 91
Lesson 4: Environment setup (CA) and first hello world
In other to start with android, we need some software such as JDK install on our computer
and android studio including the SDK
Page 30 of 91
consider that you are going to setup your environment on Windows machine having Windows
10 operating system.
Installation
So let's launch Android Studio.exe,Make sure before launch Android Studio, Our Machine
should required installed Java JDK. To install Java JDK, take a references of Android
environment setup
Once you launched Android Studio, it’s time to mention JDK path or later version in android
studio installer.
Page 31 of 91
Below the image initiating JDK to android SDK
Page 32 of 91
Need to check the components, which are required to create applications, below the image has
selected Android Studio, Android SDK, Android Virtual Machine and performance
(Intel chip).
Page 33 of 91
Need to specify the location of local machine path for Android studio and Android SDK,
below the image has taken default location of windows 10 x64 bit architecture.
Page 34 of 91
Need to specify the ram space for Android emulator by default it would take 512MB of local
machine RAM.
Page 35 of 91
At final stage, it would extract SDK packages into our local machine, it would take a while
time to finish the task and would take 2626MB of Hard disk space.
Page 36 of 91
After done all above steps perfectly, you must get finish button and it gonna be open android
studio project with Welcome to android studio message
So let us proceed to write a simple Android Application which will print "Hello World!".
Page 37 of 91
You can start your application development by calling start a new android studio project. in a
new installation frame should ask Application name, package information and location of the
project.−
Page 38 of 91
After entered application name, it going to be called select the form factors your application
runs on, here need to specify Minimum SDK, in our tutorial, I have declared as API23:
Android 6.0(Mashmallow) −
Page 39 of 91
The next level of installation should contain selecting the activity to mobile, it specifies the
default layout for Applications.
At the final stage it going to be open development tool to write the application code.
Page 40 of 91
Anatomy of Android Application
Before you run your app, you should be aware of a few directories and files in the Android
project −
Java
1 This contains the .java source files for your project. By default, it includes
an MainActivity.java source file having an activity class that runs when your app is
launched using the app icon.
res/drawable-hdpi
2
This is a directory for drawable objects that are designed for high-density screens.
res/layout
3
This is a directory for files that define your app's user interface.
res/values
4 This is a directory for other various XML files that contain a collection of resources,
such as strings and colours definitions.
AndroidManifest.xml
5 This is the manifest file which describes the fundamental characteristics of the app
and defines each of its components.
Page 41 of 91
Build.gradle
Following section will give a brief overview of the important application files.
package com.example.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
Page 42 of 91
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 −
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<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 android.intent.category.LAUNCHER to indicate that the application can be launched
from the device's launcher icon.
Page 43 of 91
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 −
<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>
<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" >
Page 44 of 91
<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>
your project's activity files and click Run icon from the tool bar. Android studio installs
the app on your AVD and starts it and if everything is fine with your set-up and application, it
will display following Emulator window −
Page 45 of 91
Page 46 of 91
Lesson 5: Step by step description of the building of and android app
Page 47 of 91
Other view
Page 48 of 91
Lesson 6: Android activities
1- Overview on activity
An activity represents a single screen with a user interface just like window or frame of
Java.Android activity is the subclass of ContextThemeWrapper class.
In other word, an activity is a single, focused thing that the user can do. Serve as the entry
point for a user's interaction with an app
If you have worked with C, C++ or Java programming language then you must have seen that
your program starts from main() function. Very similar way, Android system initiates its
program with in 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 life cycle diagram: (image courtesy :
android.com )
An activity provides the window in which the app draws its UI.
Most apps contain multiple screens, which means they comprise multiple activities.
Each activity is only loosely bound to the other activities; there are usually minimal
dependencies among the activities in an app.
Often presented to the user as full-screen windows, can also be used as floating windows or
embedded inside of another activity.
2- Creating an activity
Step 1: Firstly, click on app > res > layout > Right Click on layout. After that Select
New > Activity and choose your Activity as per requirement. Here we choose Blank
Activity as shown in figure below.
Page 49 of 91
Step 2: After that Customize the Activity in Android Studio. Enter the “Activity
Name” and “Package name” in the Text box and Click on Finish button.
Page 50 of 91
Step 3: After that your new Activity in Layout will be created. Your XML Code is in
Text and your Design Output is in Design.
Page 51 of 91
4- Exploring the Activity Lifecycle
The figure above shows different states that activity goes through during its lifecycle:
Notice different callbacks between states. The OS invokes these callbacks when the activity
moves from one state to another. You can override those methods in your own activities to
perform tasks in response to those lifecycle state changes
Page 52 of 91
5- Activity-lifecycle concepts (Callbacks)
Many disruptive things could happen while app is running Incoming call or text message, user
switches to another app, etc
- Lose the user's state/progress (e.g state of chess game app) if they leave your app and
return later
- Crash or lose the user's progress when the screen rotates between landscape and portrait
orientation. E.g. Youtube video should continue at correct point after rotation
To navigate transitions between stages of the activity lifecycle, the Activity class provides a
core set of six callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(),
and onDestroy(). The system invokes each of these callbacks as an activity enters a new state.
Page 53 of 91
Figure 1. A simplified illustration of the activity lifecycle
The Activity class defines the following call backs i.e. events. You don't need to implement all
the callbacks methods. However, it's important that you understand each one and implement
those that ensure your app behaves the way users expect.
Page 54 of 91
onCreate()
This is the first callback and called when the activity is first created. You must implement
1 this callback, which fires when the system creates your activity. Your implementation
should initialize the essential components of your activity: For example, your app should
create views and bind data to lists here. Most importantly, this is where you must
call setContentView() to define the layout for the activity's user interface.
onStart()
This callback is called when the activity becomes visible to the user. This callback
2
contains what amounts to the activity’s final preparations for coming to the foreground
and becoming interactive.
onResume()
This is called when the user starts interacting with the application. The system invokes
this callback just before the activity starts interacting with the user. At this point, the
activity is at the top of the activity stack, and captures all user input. Such an event might
3
be, for instance, receiving a phone call, the user’s navigating to another activity, or the
device screen’s turning off. Most of an app’s core functionality is implemented in
the onResume() method.
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. The
4 system calls this method as the first indication that the user is leaving your activity
(though it does not always mean the activity is being destroyed); it indicates that the
activity is no longer in the foreground (though it may still be visible if the user is in multi-
window mode). Use the onPause() method to pause or adjust operations that should not
continue (or should continue in moderation) while the Activity is in the Paused state, and
Page 55 of 91
that you expect to resume shortly. There are several reasons why an activity may enter
this state. For example:
Some event interrupts app execution. This is the most common case.
In Android 7.0 (API level 24) or higher, multiple apps run in multi-window mode.
Because only one of the apps (windows) has focus at any time, the system pauses
all of the other apps.
onStop()
This callback is called when the activity is no longer visible. This may happen because the
activity is being destroyed, a new activity is starting, or an existing activity is entering a Resumed
state and is covering the stopped activity. In all of these cases, the stopped activity is no longer
5 visible at all.
The next callback that the system calls is either onRestart(), if the activity is coming back
to interact with the user, or by onDestroy() if this activity is completely terminating.
onDestroy()
This callback is called before the activity is destroyed by the system. This callback is the
final one that the activity receives. onDestroy() is usually implemented to ensure that all
of an activity’s resources are released when the activity, or the process containing it, is
6
destroyed.
1. the activity is finishing (due to the user completely dismissing the activity or due
to finish() being called on the activity), or
Page 56 of 91
2. the system is temporarily destroying the activity due to a configuration change
(such as device rotation or multi-window mode)
onRestart()
This callback is called when the activity restarts after stopping it. onRestart() restores the
Page 57 of 91
Illustrations
Page 58 of 91
Page 59 of 91
Page 60 of 91
Page 61 of 91
Page 62 of 91
Page 63 of 91
Page 64 of 91
Example (follow it step by step)
This example will take you through simple steps to show Android application activity life
cycle. Follow the following steps to modify the Android application we created in Hello World
Example chapter −
Step Description
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.
2 Modify main activity file MainActivity.java as explained below. Keep rest of the files
unchanged.
Page 65 of 91
3 Run the application to launch Android emulator and verify the result of the changes done
in the application.
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
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
Page 67 of 91
activity for your app must be declared in the manifest with an <intent-filter> that includes the
MAIN action and LAUNCHER category as follows:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</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. I assume you had
created your AVD while doing environment setup. To run the app from Android studio, open
one of your project's activity files and click Run icon from the toolbar. Android studio
installs the app on your AVD and starts it and if everything is fine with your setup and
application, it will display Emulator window and you should see following log messages
in LogCat window in Android studio −
Page 68 of 91
08-23 10:32:07.685 4480-4480/com.example.helloworld D/Android :: The onResume() event
Let us try to click lock screen button on the Android emulator and it will generate following
events messages in LogCat window in android studio:
Let us again try to unlock your screen on the Android emulator and it will generate following
events messages in LogCat window in Android studio:
Next, let us again try to click Back button on the Android emulator and it will generate
following events messages in LogCat window in Android studio and this completes the
Activity Life Cycle for an Android Application.
Page 69 of 91
In this lesson you will learn about the Android UI layout and Controls/Widgets and its
application with practical example.
1- UI LAYOUTS
The basic building block for user interface is a View object which is created from the View
class and occupies a rectangular area on the screen and is responsible for drawing and event
handling. View is the base class for widgets, which are used to create interactive UI
components like buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold other Views
or other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either at
run time using View/ViewGroup objects or you can declare your layout using simple XML
file main_layout.xml which is located in the res/layout folder of your project.
Layout params
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout
may contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a
simple example of XML file having LinearLayout −
Page 70 of 91
<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="This is a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />
</LinearLayout>
Once your layout has created, you can load the layout resource from your application code, in
your Activity.onCreate() callback implementation as shown below −
There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.
Page 71 of 91
1 Linear Layout
LinearLayout is a view group that aligns all children in a single direction, vertically
or horizontally.
2 Relative Layout
3 Table Layout
4 Absolute Layout
5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a single
view.
6 List View
7 Grid View
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are
few common attributes among all the layouts and their are other attributes which are specific
to that layout. Following are common attributes and will be applied to all the layouts:
Page 72 of 91
1
android:id
2
android:layout_width
3
android:layout_height
4
android:layout_marginTop
5
android:layout_marginBottom
6
android:layout_marginLeft
7
android:layout_marginRight
8
android:layout_gravity
9
android:layout_weight
This specifies how much of the extra space in the layout should be allocated to the
View.
Page 73 of 91
10
android:layout_x
11
android:layout_y
12
android:layout_width
13
android:paddingLeft
14
android:paddingRight
15
android:paddingTop
16
android:paddingBottom
Here width and height are the dimension of the layout/view which can be specified in terms of
dp (Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of
an inch), px( Pixels), mm ( Millimeters) and finally in (inches).
You can specify width and height with exact measurements but more often, you will use one
of these constants to set the width or height −
Page 74 of 91
android:layout_width=fill_parent tells your view to become as big as its parent view.
Gravity attribute plays important role in positioning the view object and it can take one or
more (separated by '|') of the following constant values.
Page 75 of 91
center 0x11 Place the object in the center of its container in
both the vertical and horizontal axis, not changing
its size.
fill 0x77 Grow the horizontal and vertical size of the object
if needed so it completely fills its container.
clip_vertical 0x80 Additional option that can be set to have the top
and/or bottom edges of the child clipped to its
container's bounds. The clip will be based on the
vertical gravity: a top gravity will clip the bottom
edge, a bottom gravity will clip the top edge, and
neither will clip both edges.
clip_horizontal 0x08 Additional option that can be set to have the left
and/or right edges of the child clipped to its
container's bounds. The clip will be based on the
horizontal gravity: a left gravity will clip the right
edge, a right gravity will clip the left edge, and
neither will clip both edges.
View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely
within the tree. The syntax for an ID, inside an XML tag is −
Page 76 of 91
android:id="@+id/my_button"
The at-symbol (@) at the beginning of the string indicates that the XML parser should
parse and expand the rest of the ID string and identify it as an ID resource.
The plus-symbol (+) means that this is a new resource name that must be created and
added to our resources. To create an instance of the view object and capture it from the
layout, use the following −
6- UI Controls
Input controls are the interactive components in your app's user interface. Android provides a
wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check
box, zoom buttons, toggle buttons, and many more.
UI Elements
A View is an object that draws something on the screen that the user can interact with and
a ViewGroup is an object that holds other View (and ViewGroup) objects in order to
define the layout of the user interface.
You define your layout in an XML file which offers a human-readable structure for the layout,
similar to HTML. For example, a simple vertical layout with a text view and a button looks
like this −
Page 77 of 91
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="I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>
Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical
user interface for your app.
1 TextView
2 EditText
3 AutoCompleteTextView
Page 78 of 91
4 Button
5 ImageButton
6 CheckBox
An on/off switch that can be toggled by the user. You should use check box when
presenting users with a group of selectable options that are not mutually exclusive.
7 ToggleButton
8 RadioButton
9 RadioGroup
10 ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks, such as
when you are performing a task in the background.
11 Spinner
A drop-down list that allows users to select one value from a set.
Page 79 of 91
12 TimePicker
The TimePicker view enables users to select a time of the day, in either 24-hour mode
or AM/PM mode.
13 DatePicker
Create UI Controls
Input controls are the interactive components in your app's user interface. Android provides a
wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check
box, zoom buttons, toggle buttons, and many more.
As explained in previous chapter, a view object may have a unique ID assigned to it which will
identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/text_id"
To create a UI Control/View/Widget you will have to define a view/widget in the layout file
and assign it a unique ID as follows −
<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>
Then finally create an instance of the Control object and capture it from the layout, use the
following −
Page 80 of 91
TextView myText = (TextView) findViewById(R.id.text_id);
Page 81 of 91
Lesson 8 : Android - Event Handling
Events are a useful way to collect data about a user's interaction with interactive
components of Applications. Like button presses or screen touch etc. The Android
framework maintains an event queue as first-in, first-out (FIFO) basis. You can capture these
events in your program and take appropriate action as per requirements.
Event Listeners − An event listener is an interface in the View class that contains a
single callback method. These methods will be called by the Android framework when
the View to which the listener has been registered is triggered by user interaction with
the item in the UI.
Event Handlers − When an event happens and we have registered an event listener for
the event, the event listener calls the Event Handlers, which is the method that actually
handles the event.
OnClickListener()
onClick() This is called when the user either clicks or touches or focuses
upon any widget like button, text, image etc. You will use
onClick() event handler to handle such event.
OnLongClickListener()
onLongClick() This is called when the user either clicks or touches or focuses
upon any widget like button, text, image etc. for one or more
Page 82 of 91
seconds. You will use onLongClick() event handler to handle such
event.
OnFocusChangeListener()
This is called when the widget looses its focus ie. user goes away
onFocusChange()
from the view item. You will use onFocusChange() event handler
to handle such event.
OnFocusChangeListener()
This is called when the user is focused on the item and presses or
onKey()
releases a hardware key on the device. You will use onKey() event
handler to handle such event.
OnTouchListener()
This is called when the user presses the key, releases the key, or
onTouch()
any movement gesture on the screen. You will use onTouch()
event handler to handle such event.
OnMenuItemClickListener()
onMenuItemClick() This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.
onCreateContextMenuItemListener()
onCreateContextMenu() This is called when the context menu is being built(as the result
of a sustained "long click)
There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc which may be needed for your application. So I recommend to refer
Page 83 of 91
official documentation for Android application development in case you are going to develop
a sophisticated apps.
Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. Though there are
several tricky ways to register your event listener for any event, but I'm going to list down only
top 3 ways, out of which you can use any of them based on the situation.
Below section will provide you detailed examples on all the three scenarios −
Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the
screen.Touching the screen puts the device into touch mode. The user can then interact with it
by touching the on-screen virtual buttons, images, etc.You can check if the device is in touch
mode by calling the View class’s isInTouchMode() method.
Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This
indicates that it’s ready to accept input from the user.
android:foucsUp="@=id/button_l"
onTouchEvent()
Page 84 of 91
public boolean onTouchEvent(motionEvent event){
switch(event.getAction()){
case TOUCH_DOWN:
Toast.makeText(this,"you have clicked down Touch
button",Toast.LENTH_LONG).show();
break();
case TOUCH_UP:
Toast.makeText(this,"you have clicked up touch button",Toast.LENTH_LONG).show();
break;
case TOUCH_MOVE:
Toast.makeText(this,"you have clicked move touch
button"Toast.LENTH_LONG).show();
break;
}
return super.onTouchEvent(event) ;
}
Here you will create an anonymous implementation of the listener and will be useful if each
class is applied to a single control only and you have advantage to pass arguments to event
handler. In this approach event handler methods can access private data of Activity. No
reference is needed to call to Activity.
But if you applied the handler to more than one control, you would have to cut and paste the
code for the handler and if the code for the handler is long, it makes the code harder to maintain.
Following are the simple steps to show how we will make use of separate Listener class to
register and capture click event. Similar way you can implement your listener for any other
required event type.
Page 85 of 91
Step Description
1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.
2 Modify src/MainActivity.java file to add click event listeners and handlers for the two
buttons defined.
4 No need to declare default string constants.Android studio takes care default constants.
5 Run the application to launch Android emulator and verify the result of the changes
done in the aplication.
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
Page 86 of 91
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(25);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(55);
}
});
}
}
Page 87 of 91
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Handling "
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Page 88 of 91
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small font"
android:id="@+id/button"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Font"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25dp" />
</RelativeLayout>
Page 89 of 91
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your myapplication application. I assume you had created your AVD while
doing environment setup. To run the app from Android Studio, open one of your project's
activity files and click Run icon from the toolbar. Android Studio installs the app on your
Page 90 of 91
AVD and starts it and if everything is fine with your setup and application, it will display
following Emulator window −
Now you try to click on two buttons, one by one and you will see that font of the Hello
World text will change, which happens because registered click event handler method is being
called against each click event.
Exercise
I will recommend to try writing different event handlers for different event types and
understand exact difference in different event types and their handling. Events related to menu,
spinner, pickers widgets are little different but they are also based on the same concepts as
explained above.
Page 91 of 91