0% found this document useful (0 votes)
128 views

Mobile Application Development: Wireless Transmission

1. The document discusses the evolution of mobile wireless technologies from 1G to 5G. It describes the key characteristics of each generation including available speeds and underlying technologies. 2. 1G networks were the first generation of cellular technology and used analog signals with speeds up to 2.4 kbps. 2G introduced digital networks and speeds up to 50 kbps. 3G brought multimedia capabilities and speeds from 144 kbps to 2 Mbps. 3. 4G networks such as LTE further increased speeds to 1 Gbps using technologies like MIMO and OFDM. 5G is currently being developed to offer speeds over 35 Gbps using technologies like massive MIMO and millimeter wave communications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views

Mobile Application Development: Wireless Transmission

1. The document discusses the evolution of mobile wireless technologies from 1G to 5G. It describes the key characteristics of each generation including available speeds and underlying technologies. 2. 1G networks were the first generation of cellular technology and used analog signals with speeds up to 2.4 kbps. 2G introduced digital networks and speeds up to 50 kbps. 3G brought multimedia capabilities and speeds from 144 kbps to 2 Mbps. 3. 4G networks such as LTE further increased speeds to 1 Gbps using technologies like MIMO and OFDM. 5G is currently being developed to offer speeds over 35 Gbps using technologies like massive MIMO and millimeter wave communications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

Mobile Application Development Department of CSE

Mobile Application Development


Wireless Transmission
Wireless transmission is a form of unguided media. Wireless communication involves no physical link
established between two or more devices, communicating wirelessly. Wireless signals are spread over in the
air and are received and interpreted by appropriate antennas.

When an antenna is attached to electrical circuit of a computer or wireless device, it converts the digital data
into wireless signals and spread all over within its frequency range. The receptor on the other end receives
these signals and converts them back to digital data.

Voice and Data Communication Standards: (1G, 2G, 3G, 4G and 5G)
Simply, the "G" stands for "GENERATION". While you connected to internet, the speed of your
internet is depends upon the signal strength that has been shown in alphabets like 2G, 3G, 4G etc. right
next to the signal bar on your home screen. Each Generation is defined as a set of telephone network
standards, which detail the technological implementation of a particular mobile phone system. The
speed increases and the technology used to achieve that speed also changes. For eg, 1G offers 2.4
kbps, 2G offers 64 Kbps and is based on GSM, 3G offers 144 kbps-2 mbps whereas 4G offers 100 Mbps
- 1 Gbps and is based on LTE technology.

The aim of wireless communication is to provide high quality, reliable communication just like wired
communication (optical fiber) and each new generation of services represents a big step (a leap
rather) in that direction. This evolution journey was started in 1979 from 1G and it is still continuing to
5G. Each of the Generations has standards that must be met to officially use the G terminology. There
are institutions in charge of standardizing each generation of mobile technology. Each generation has
requirements that specify things like throughput, delay, etc. that need to be met to be considered part
of that generation. Each generation built upon the research and development which happened since
the last generation. 1G was not used to identify wireless technology until 2G, or the second
generation, was released. That was a major jump in the technology when the wireless networks went
from analog to digital.

1G - First Generation:

B. V. Raju Institute of Technology Page: 1


Mobile Application Development Department of CSE

This was the first generation of cell phone technology. The very first generation of commercial cellular
network was introduced in the late 70's with fully implemented standards being established
throughout the 80's. It was introduced in 1987 by Telecom (known today as Telstra), Australia received
its first cellular mobile phone network utilizing a 1G analog system. 1G is an analog technology and the
phones generally had poor battery life and voice quality was large without much security, and would
sometimes experience dropped calls. These are the analog telecommunications standards that were
introduced in the 1980s and continued until being replaced by 2G digital telecommunications. The
maximum speed of 1G is 2.4 Kbps.

2G - Second Generation:
Cell phones received their first major upgrade when they went from 1G to 2G. The main difference
between the two mobile telephone systems (1G and 2G), is that the radio signals used by 1G network
are analog, while 2G networks are digital. Main motive of this generation was to provide secure and
reliable communication channel. It implemented the concept of CDMA and GSM. Provided small data
service like sms and mms. Second generation 2G cellular telecom networks were commercially
launched on the GSM standard in Finland by Radiolinja (now part of Elisa Oyj) in 1991. 2G capabilities
are achieved by allowing multiple users on a single channel via multiplexing. During 2G Cellular phones
are used for data also along with voice. The advance in technology from 1G to 2G introduced many of
the fundamental services that we still use today, such as SMS, internal roaming, conference calls, call
hold and billing based on services e.g. charges based on long distance calls and real time billing. The
max speed of 2G with General Packet Radio Service (GPRS) is 50 Kbps or 1 Mbps with Enhanced Data
Rates for GSM Evolution (EDGE). Before making the major leap from 2G to 3G wireless networks, the
lesser-known 2.5G and 2.75G was an interim standard that bridged the gap.

3G - Third Generation:
This generation set the standards for most of the wireless technology we have come to know and love.
Web browsing, email, video downloading, picture sharing and other Smartphone technology were
introduced in the third generation. Introduced commercially in 2001, the goals set out for third
generation mobile communication were to facilitate greater voice and data capacity, support a wider
range of applications, and increase data transmission at a lower cost.

B. V. Raju Institute of Technology Page: 2


Mobile Application Development Department of CSE

The 3G standard utilizes a new technology called UMTS as its core network architecture - Universal
Mobile Telecommunications System. This network combines aspects of the 2G network with some new
technology and protocols to deliver a significantly faster data rate. Based on a set of standards used
for mobile devices and mobile telecommunications use services and networks that comply with the
International Mobile Telecommunications-2000 (IMT-2000) specifications by the International
Telecommunication Union. One of requirements set by IMT-2000 was that speed should be at least
200Kbps to call it as 3G service.
3G has Multimedia services support along with streaming are more popular. In 3G, Universal access
and portability across different device types are made possible (Telephones, PDA's, etc.). 3G increased
the efficiency of frequency spectrum by improving how audio is compressed during a call, so more
simultaneous calls can happen in the same frequency range. The UN's International
Telecommunications Union IMT-2000 standard requires stationary speeds of 2Mbps and mobile
speeds of 384kbps for a "true" 3G. The theoretical max speed for HSPA+ is 21.6 Mbps.
Like 2G, 3G evolved into 3.5G and 3.75G as more features were introduced in order to bring about 4G.
A 3G phone cannot communicate through a 4G network, but newer generations of phones are
practically always designed to be backward compatible, so a 4G phone can communicate through a 3G
or even 2G network.

4G - Fourth Generation:
4G is a very different technology as compared to 3G and was made possible practically only because
of the advancements in the technology in the last 10 years. Its purpose is to provide high speed, high
quality and high capacity to users while improving security and lower the cost of voice and data
services, multimedia and internet over IP. Potential and current applications include amended mobile
web access, IP telephony, gaming services, high-definition mobile TV, video conferencing, 3D
television, and cloud computing.
The key technologies that have made this possible are MIMO (Multiple Input Multiple Output)
and OFDM (Orthogonal Frequency Division Multiplexing). The two important 4G standards are WiMAX
(has now fizzled out) and LTE (has seen widespread deployment). LTE (Long Term Evolution) is a series
of upgrades to existing UMTS technology and will be rolled out on Telstra's existing 1800MHz
frequency band. The max speed of a 4G network when the device is moving is 100 Mbps or 1 Gbps for
low mobility communication like when stationary or walking, latency reduced from around 300ms to
B. V. Raju Institute of Technology Page: 3
Mobile Application Development Department of CSE

less than 100ms, and significantly lower congestion. When 4G first became available, it was simply a
little faster than 3G. 4G is not the same as 4G LTE which is very close to meeting the criteria of the
standards. To download a new game or stream a TV show in HD, you can do it without buffering.
Newer generations of phones are usually designed to be backward-compatible, so a 4G phone can
communicate through a 3G or even 2G network. All carriers seem to agree that OFDM is one of the
chief indicators that a service can be legitimately marketed as being 4G. OFDM is a type of digital
modulation in which a signal is split into several narrowband channels at different frequencies. There
is a significant amount of infrastructure changes needed to be implemented by service providers in
order to supply because voice calls in GSM, UMTS and CDMA2000 are circuit switched, so with the
adoption of LTE, carriers will have to re-engineer their voice call network. And again, we have the
fractional parts: 4.5G and 4.9G marking the transition of LTE (in the stage called LTE-Advanced Pro)
getting us more MIMO, more D2D on the way to IMT-2020 and the requirements of 5G.

5G - Fifth Generation:
5G is a generation currently under development, that's intended to improve on 4G. 5G promises
significantly faster data rates, higher connection density, much lower latency, among other
improvements. Some of the plans for 5G include device-to-device communication, better battery
consumption, and improved overall wireless coverage. The max speed of 5G is aimed at being as fast
as 35.46 Gbps, which is over 35 times faster than 4G.
Key technologies to look out for: Massive MIMO, Millimeter Wave Mobile Communications etc.
Massive MIMO, millimeter wave, small cells, Li-Fi all the new technologies from the previous decade
could be used to give 10Gb/s to a user, with an unseen low latency, and allow connections for at
least 100 billion devices . Different estimations have been made for the date of commercial
introduction of 5G networks. Next Generation Mobile Networks Alliance feel that 5G should be rolled
out by 2020 to meet business and consumer demands.

B. V. Raju Institute of Technology Page: 4


Mobile Application Development Department of CSE

Wireless Personal Area Network: (WPAN)

Wireless Personal Area Network in short known as WPAN. Actually WPAN is PAN (Personal Area
Network) where the interconnected devices are centered around a person’s workspace and connected
through wireless medium. That’s why it is also called as Person’s centered short range wireless connectivity.
Typically, the range is within about 10 meters means very short range. Plugging in is one of the key concept in
WPAN as within a close proximity WPAN-equipped devices communicate with each other as like they are
connected through cable. Unlike WLAN (Wireless Local Area Network) where there is a requirement of
infrastructure setup, in WPAN connection involves little or no infrastructure. In general, if we will see this
WPAN provides power efficient and inexpensive solutions to be implemented for a wide range of devices
within a short range distance.

As in WPAN mostly the connection between the devices happens within the building or in a room (short
range) So, let’s take an example of Wi-Fi connection through which two friends are chatting, sharing
documents with each other in room.

Some more examples of WPAN includes Wireless mouse, Wearable devices, USB flash drives, Digital cameras,
Bluetooth, Wi-Fi, Thermostats, Security systems, Lighting controls, Motion sensors, Personal server and Leak
sensors etc.

As per IEEE, Wireless Personal Area Network is classified into 3 classes i.e.

1. High-rate WPAN (HR-WPAN): It is defined in the IEEE 802.15.3 standard. Data throughput is > 20
Mbps.

2. Medium-rate WPAN (MR-WPAN): It is defined in the IEEE 802.15.1 standard. Data throughput is 1
Mbps.

3. Low-rate WPAN (LR-WPAN): It is defined in the IEEE 802.15.4 standard. Data throughput is < 0.25
Mbps.

Applications of WPAN:
 Short range connectivity for multimedia applications

 Hands free devices connection

 Industrial sensor applications

WPAN Topologies:
As mostly use of WPAN is within short range so it is mainly used for general purpose uses and with little
industrial requirement implementations which supports below network connectivity arrangements (network
topology)

 Star Topology

 Mesh Topology

 Cluster Tree Topology

Technologies used in WPAN:


B. V. Raju Institute of Technology Page: 5
Mobile Application Development Department of CSE

1. Bluetooth

2. ZigBee

3. Infrared

4. Z-wave

5. Wireless Body Area Network (WBAN)

Features of WPAN:
 Low cost, Little or No infrastructure setup

 Short range communication

 Small personal network, use anywhere

 Wide range of devices

 Low power consumption

 No complex connectivity

Advantages of WPAN:
 Security

 Portability

 Easy Connectivity

 Stability

Disadvantages of WPAN:
 Short range

 Transfer speed

Wireless Local Area Network: (WLAN)

WLAN stands for Wireless Local Area Network. WLAN is a local area network that uses radio communication
to provide mobility to the network users, while maintaining the connectivity to the wired network. A WLAN
basically, extends wired local area network. WLAN’s are built attaching a device called the access point(AP) to
the edge of the wired network. Clients communicate with the AP using a wireless network adapter which is
similar in function to a Ethernet adapter. It is also called a LAWN that is Local area wireless network.

The performance of WLAN is high compared to other wireless networks. The coverage of WLAN is within a
campus or building or that tech parks. It is used in the mobile propagation of wired networks. The standards of
WLAN are HiperLAN, Wi-Fi, and IEEE 802.11. It offers service to the desktop laptop, mobile application and all
the devices works on the Internet. WLAN is an affordable method and can be set up in 24 hours. WLAN gives
users the mobility to move around within a local coverage area and still be connected to the network. Latest
brands are based on IEE 802.11 standards, which are the WI-FI brand name.

Characteristics:

 Seamless operation.

B. V. Raju Institute of Technology Page: 6


Mobile Application Development Department of CSE

 Low power for battery use.

 Simple management, easy to use for everyone.

 Protection of investment in wired networks.

 Robust transmission technology

Advantages:
 Installation speed and simplicity.

 Installation flexibility.

 Reduced cost of ownership.

 Reliability.

 Mobility.

 Robustness.

Disadvantages:

 Slower bandwidth.

 Security for wireless LAN’s is the prime concern.

 Less capacity.

 Wireless networks cost four times more than wired network cards.

 Wireless devices emit low levels of RF which can be harmful to our health.

Mobile Computing Architecture:

Mobile computing architecture refers to the definition of multiple layers between user application
interfaces, devices, and network hardware. A well-defined architecture is necessary for systematic calculations
and access to data and software objects.

Mobile computing usually implies wireless transmission but, wireless transmission does not imply mobile
computing.

B. V. Raju Institute of Technology Page: 7


Mobile Application Development Department of CSE

1. Layer-1: Presentation Layer (UI)

2. Layer-2: Application Layer(AL)

3. Layer-3: Data Access Layer(DA)

Each tier is distributed to a different place or places in a network. These tiers do not necessarily correspond
to physical locations on various computers on a network, but rather to logical layers of the application.

Presentation Layer (UI):

 This layer presents data to the user and optionally permits data manipulation and data entry, also this
layer requests the data form Business layer.

 This layer accomplished through use of Dynamic HTML and client-side data sources and data cursors.

Application Layer (AL):

 The business logic acts as the server for client requests from workstations. It acts according Business
rules fetch or insert data through the Data Layer.

 In turn, it determines what data is needed (and where it is located) and acts as a client in relation to a
third tier of programming that might be located on a local or mainframe computer.

 Because these middle-tier components are not tied to a specific client, they can be used by all
applications and can be moved to different locations, as response time and other rules require.

Data Access Layer (DA):

 The third tier of the 3-tier system is made up of the DBMS that provides all the data for the above two
layers.

B. V. Raju Institute of Technology Page: 8


Mobile Application Development Department of CSE

 This is the actual DBMS access layer.

 Avoiding dependencies on the storage mechanisms allows for updates or changes without the
application tier clients being affected by or even aware of the change.

GSM
GSM stands for Global System for Mobile Communication. It is a digital cellular technology used for
transmitting mobile voice and data services.

 The concept of GSM emerged from a cell-based mobile radio system at Bell Laboratories in the early
1970s.

 GSM is a circuit-switched system that divides each 200 kHz channel into eight 25 kHz time-slots. GSM
operates on the mobile communication bands 900 MHz and 1800 MHz in most parts of the world. In
the US, GSM operates in the bands 850 MHz and 1900 MHz.

 GSM makes use of narrowband Time Division Multiple Access (TDMA) technique for transmitting
signals.

 GSM was developed using digital technology. It has an ability to carry 64 kbps to 120 Mbps of data
rates.

 GSM provides basic to advanced voice and data services including roaming service. Roaming is the
ability to use your GSM phone number in another GSM network.

GSM digitizes and compresses data, then sends it down through a channel with two other streams of user
data, each in its own timeslot.

GSM is having 4 different sizes of cells are used in GSM:

1. Macro: In this size of cell, Base Station antenna is installed.

2. Micro: In this size of cell, antenna height is less than the average roof level.

3. Pico: Small cells’ diameter of few meters.

4. Umbrella: It covers the shadowed (Fill the gaps between cells) regions.

Features of GSM

 Improved spectrum efficiency

 International roaming

 Low-cost mobile sets and base stations (BSs)

 High-quality speech

 Compatibility with Integrated Services Digital Network (ISDN) and other telephone company services

B. V. Raju Institute of Technology Page: 9


Mobile Application Development Department of CSE

 Support for new services

GSM Architecture:
GSM is nothing but a larger system which is divided into further 3 subsystems.

1. BSS: BSS stands for Base Station Subsystem. BSS handles traffic and signaling between a mobile phone
and the network switching subsystem. BSS having two components BTS and BSC.

2. NSS: NSS stands for Network and Switching Subsystem. NSS is to core network of GSM. That carried
out call and mobility management functions for mobile phone present in network. NSS have different
components like VLR, HLR and EIR.

3. OSS: OSS stands for Operating Subsystem. OSS is a functional entity which the network operator
monitor and control the system. OMC is the part of OSS.

Suppose there are 3 Mobile stations which are connected with the tower and that tower is connected to BTS
through TRX, then further connected to BSC and MSC. Let’s understand the functionality of different
components.

1. MS: MS stands for Mobile System. MS comprises user equipment and software needed for communication
with a mobile network. Mobile Station (MS) = Mobile Equipment(ME) + Subscriber Identity Module (SIM).
Now, these mobile stations are connected to tower and that tower connected with BTS through TRX. TRX is a

B. V. Raju Institute of Technology Page: 10


Mobile Application Development Department of CSE

transceiver which comprises transmitter and receiver. Transceiver has two performances of sending and
receiving.

2. BTS: BTS stands for Base Transceiver Station which facilitates wireless communication between user
equipment and a network. Every tower has BTS.

3. BSC: BSC stands for Base Station Controller. BSC has multiple BTS. You can consider the BSC as a local
exchange of your area which has multiple towers and multiple towers have BTS.

4. MSC: MSC stands for Mobile Switching Center. MSC is associated with communication switching functions
such as call setup, call release and routing. Call tracing, call forwarding all functions are performed at the MSC
level. MSC is having further components like VLR, HLR, AUC, EIR and PSTN.

 VLR: VLR stands for Visitor Location Register. VLR is a database which contains the exact location of all
mobile subscribers currently present in the service area of MSC. If you are going from one state to
another state, then your entry is marked into the database of VLR.

 HLR: HLR stands for Home Location Register. HLR is a database containing pertinent data regarding
subscribers authorized to use a GSM network. If you purchase SIM card from in the HLR. HLR is like a
home which contains all data like your ID proof, which plan you are taking, which caller tune you are
using etc.

 OMC: OMC stands for Operation Maintenance Center. OMC monitor and maintain the performance of
each MS, BSC and MSC within a GSM system.

 AUC: AUC stands for Authentication Center. AUC authenticates the mobile subscriber that wants to
connect in the network.

 EIR: EIR stands for Equipment Identity Register. EIR is a database that keeps the record of all allowed
or banned in the network. If you are banned in the network them you can’t enter the network, and
you can’t make the calls.

 PSTN: PSTN stands for Public Switched Telephone Network. PSTN connects with MSC. PSTN originally
a network of fixed line analog telephone systems. Now almost entirely digital in its core network and
includes mobile and other networks as well as fixed telephones. The earlier landline phones which
places at our home is nothing but PSTN.

Three subsystem BSS, NSS and OSS are connected with each other via some interfaces. Total three interfaces
are there:

1. Air Interface: Air interface is also known as UM interface. Interface between MS and BTS is called as
UM interface because it is mobile analog to the U interface of ISDN.

2. Abis Interface: It is a BSS internal interface linking with BTS and BSC.

3. A Interface: It provides communication between BSS and MSC.

GPRS
GPRS stands for General Packet Radio Service. It is the modified version of GSM architecture service. In
GSM architecture we can only transport the voice signal. But if signal consists of the data then only GSM

B. V. Raju Institute of Technology Page: 11


Mobile Application Development Department of CSE

architecture cannot use. For that there are two more software components are used, SGSN (Serving GPRS
supporting Node) and GGSN (Gateway GPRS supporting Node).

GPRS Architecture:

In GSM architecture there is one component called BSC. But in GPRS there is one component is added to BSC
called PCU. PCU stands for Packet Control Unit. If signal comes to BSC and that signal contains data, then PCU
routes to the SGSN. Interface is used between BSC and PCU is FRI interface. After signal comes to SGSN, it
delivers the data packet to the GGSN. GGSN routes the data packet to the data network (PDN- Predefined
Data Network).

Task of SGSN:
1. Packet Delivery

2. Mobility management

 apply/ sign off of terminals

 localization

3. LLC (Logical Link Control) management

4. Authentication

5. Billing

Task of GGSN:
1. Mediator between GPRS between backbone and external data networks.

2. Saves current data for the SGSN address of the participant as well as their profile and data for
authentication and invoice.

B. V. Raju Institute of Technology Page: 12


Mobile Application Development Department of CSE

EDGE

EDGE (Enhanced Data Rate For GSM Evolution) provides a higher rate of data transmission than normal GSM.
It uses a backward-compatible extension of GSM of digital mobile technology. EDGE has a pre-3G radio
technology and uses part of ITU’s 3G definition. It can work on any network deployed with GPRS (with
necessary upgrades).

In order to increase data transmission speed, EDGE was deployed on the GSM network in 2003 by Cingular in
the USA.

Working

It uses 8PSK modulation in order to achieve a higher data transmission rate. The modulation format is changed
to 8PSK from GMSK. This provides an advantage as it is able to convey 3 bits per symbol, and increases the
maximum data rate. However, this upgrade required a change in the base station.

Features

 It provides an evolutionary migration path from GPRS to UMTS.

 It is standardized by 3GPP.

 EDGE is used for any packet switched application, like an Internet connection.

 EDGE delivers higher bit-rates per radio channel and it increase the capacity and performance.

Advantage

 It has higher speed.

B. V. Raju Institute of Technology Page: 13


Mobile Application Development Department of CSE

 It is an “always-on” connection

 It is more reliable and efficient

 It is cost efficient

Disadvantage

 It consumes more battery.

 hardware needs upgradation.

B. V. Raju Institute of Technology Page: 14


Mobile Application Development Department of CSE

Introduction to Android
The Android operating system is the largest installed base among various mobile platforms across the globe.
Hundreds of millions of mobile devices are powered by Android in more than 190 countries of the world. It
conquered around 75% of the global market share by the end of 2020, and this trend is growing bigger every
other day. The company named Open Handset Alliance developed Android for the first time that is
based on the modified version of the Linux kernel and other open-source software. Google sponsored the
project at initial stages and in the year 2005, it acquired the whole company. In September 2008, the first
Android-powered device launched in the market. Android dominates the mobile OS industry because of the
long list of features it provides. It’s user-friendly, has huge community support, provides a greater extent of
customization, and a large number of companies build Android-compatible smartphones. As a result, the
market observes a sharp increase in the demand for developing Android mobile applications, and with that
companies need smart developers with the right skill set. At first, the purpose of Android was thought of as a
mobile operating system. However, with the advancement of code libraries and its popularity among
developers of the divergent domain, Android becomes an absolute set of software for all devices like tablets,
wearables, set-top boxes, smart TVs, notebooks, etc.

Features of Android

 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.

 It contains multiple APIs to support location-tracking services such as GPS.


B. V. Raju Institute of Technology Page: 15
Mobile Application Development Department of CSE

 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.

 It supports multimedia hardware control to perform playback or recording using a camera and
microphone.

 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.

 It provides support for virtual reality or 2D/3D Graphics

Android Versions

Programming Languages used in Developing Android Applications

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.
B. V. Raju Institute of Technology Page: 16
Mobile Application Development Department of CSE

Advantages of Android Development

 The Android is an open-source Operating system and hence possesses a vast community for support.

 The design of the Android Application has guidelines from Google, which becomes easier for
developers to produce more intuitive user applications.

 Fragmentation gives more power to Android Applications. This means the application can run two
activities on a single screen.

 Releasing the Android application in the Google play store is easier when it is compared to other
platforms.

Disadvantages of Android Development

 Fragmentation provides a very intuitive approach for user experience but it has some drawbacks,
where the development team needs time to adjust with the various screen sizes of mobile
smartphones that are now available in the market and invoke the particular features in the
application.

 The Android devices might vary broadly. So the testing of the application becomes more difficult.

 As the development and testing consume more time, the cost of the application may increase,
depending on the application’s complexity and features.

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.

The main components of android architecture are following:

 Applications

 Application Framework

 Android Runtime

 Platform Libraries

 Linux Kernel
B. V. Raju Institute of Technology Page: 17
Mobile Application Development Department of CSE

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.

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.
B. V. Raju Institute of Technology Page: 18
Mobile Application Development Department of CSE

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.

 Surface manager responsible for managing access to the display subsystem.

 SGL and OpenGL 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.

 Web-Kit This open source web browser engine provides all the functionality to display web content
and to simplify page loading.

 SSL (Secure Sockets Layer) is security technology to establish an encrypted link between a web server
and a web browser.

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.

The features of Linux kernel are:

 Security: The Linux kernel handles the security between the application and the system.

 Memory Management: It efficiently handles the memory management thereby providing the freedom
to develop our apps.

 Process Management: It manages the process well, allocates resources to processes whenever they
need them.

 Network Stack: It effectively handles the network communication.

 Driver Model: It ensures that the application works properly on the device and hardware
manufacturers responsible for building their drivers into the Linux build.

Exploring the designer

The workflow to develop an app for Android is conceptually the same as other app platforms. However, to
efficiently build a well-designed app for Android, you need some specialized tools. The following list provides

B. V. Raju Institute of Technology Page: 19


Mobile Application Development Department of CSE

an overview of the process to build an Android app and includes links to some Android Studio tools you should
use during each phase of development.

B. V. Raju Institute of Technology Page: 20


Mobile Application Development Department of CSE

1. Set up your workspace


This is the phase you probably already finished: Install Android Studio and create a project.

2. Write your app


Now you can get to work. Android Studio includes a variety of tools and intelligence to help you work
faster, write quality code, design a UI, and create resources for different device types.

3. Build and run


During this phase, you build your project into a debuggable APK package that you can install and run on
the emulator or an Android-powered device.

You can also begin customizing your build. For example, you can create build variants that produce
different versions of your app from the same project, and shrink your code and resources to make your
app smaller.

4. Debug, profile, and test


This is the iterative phase in which you continue writing your app but with a focus on eliminating bugs and
optimizing app performance. Of course, creating tests will help you in those endeavors.

To view and analyze various performance metrics such as memory usage, network traffic, CPU impact,
and more, see Performance profiling tools.

5. Publish
When you're ready to release your app to users, there are just a few more things to consider, such as
versioning your app, building an Android App Bundle, and signing it with a key.

Components
An android component is simply a piece of code that has a well-defined life cycle e.g. Activity, Receiver,
Service etc.

The core building blocks or fundamental components of android are activities, views, intents, services,
content providers, fragments and AndroidManifest.xml.

Activity
An activity is a class that represents a single screen. It is like a Frame in AWT.

View
A view is the UI element such as button, label, text field etc. Anything that you see is a view.

Intent
Intent is used to invoke components. It is mainly used to:

B. V. Raju Institute of Technology Page: 21


Mobile Application Development Department of CSE

 Start the service

 Launch an activity

 Display a web page

 Display a list of contacts

 Broadcast a message

 Dial a phone call etc.

For example, you may write the following code to view the webpage.

Intent intent=new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent);

Service
Service is a background process that can run for a long time.

There are two types of services local and remote. Local service is accessed from within the application
whereas remote service is accessed remotely from other applications running on the same device.

Content Provider
Content Providers are used to share data between the applications.

Fragment
Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same
time.

AndroidManifest.xml
It contains information about activities, content providers, permissions etc. It is like the web.xml file in Java EE.

Android Virtual Device (AVD)


It is used to test the android application without the need for mobile or tablet etc. It can be created in
different configurations to emulate different types of real devices.

B. V. Raju Institute of Technology Page: 22


Mobile Application Development Department of CSE

Creating an Android Application


You need to follow the 3 steps mentioned above for creating the Hello android application.

1) Create the New Android project


For creating the new android studio project:

1) Select Start a new Android Studio project

2) Provide the following information: Application name, Company domain, Project location and Package
name of application and click next.

B. V. Raju Institute of Technology Page: 23


Mobile Application Development Department of CSE

3) Select the API level of application and click next.

B. V. Raju Institute of Technology Page: 24


Mobile Application Development Department of CSE

4) Select the Activity type (Empty Activity).

5) Provide the Activity Name and click finish.

B. V. Raju Institute of Technology Page: 25


Mobile Application Development Department of CSE

After finishing the Activity configuration, Android Studio auto generates the activity class and other required
configuration files.

Now an android project has been created. You can explore the android project and see the simple program, it
looks like this:

2) Write the message

File: activity_main.xml

Android studio auto generates code for activity_main.xml file. You may edit this file according to your
requirement.

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


<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.co
m/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="first.javatpoint.com.welcome.MainActivity">

<TextView

B. V. Raju Institute of Technology Page: 26


Mobile Application Development Department of CSE

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
}

File: MainActivity.java

package first.javatpoint.com.welcome;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


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

3) Run the android application

To run the android application, click the run icon on the toolbar or simply press Shift + F10.

The android emulator might take 2 or 3 minutes to boot. So please have patience. After booting the emulator,
the android studio installs the application and launches the activity. You will see something like this:

B. V. Raju Institute of Technology Page: 27


Mobile Application Development Department of CSE

Anotomy Hello Android Example


Android application contains different components such as java source code, string resources, images,
manifest file, apk file etc. Let's understand the project structure of android application.

B. V. Raju Institute of Technology Page: 28


Mobile Application Development Department of CSE

Java Source Code


Let's see the java source file created by the Eclipse IDE:
File: MainActivity.java

package com.example.helloandroid;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {//(1)
@Override
protected void onCreate(Bundle savedInstanceState) {//(2)
super.onCreate(savedInstanceState);
B. V. Raju Institute of Technology Page: 29
Mobile Application Development Department of CSE

setContentView(R.layout.activity_main);//(3)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {//(4)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

(1) Activity is a java class that creates and default window on the screen where we can place different
components such as Button, EditText, TextView, Spinner etc. It is like the Frame of Java AWT.

It provides life cycle methods for activity such as onCreate, onStop, OnResume etc.

(2) The onCreate method is called when Activity class is first created.

(3) The setContentView(R.layout.activity_main) gives information about our layout resource. Here, our layout
resources are defined in activity_main.xml file.

File: activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
As you can see, a textview is created by the framework automatically. But the message for this string is
defined in the strings.xml file. The @string/hello_world provides information about the textview message.
The value of the attribute hello_world is defined in the strings.xml file.

File: strings.xml
B. V. Raju Institute of Technology Page: 30
Mobile Application Development Department of CSE

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


<resources>
<string name="app_name">helloandroid</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
You can change the value of the hello_world attribute from this file.

Generated R.java file


It is the auto-generated file that contains IDs for all the resources of res directory. It is generated by
aapt(Android Asset Packaging Tool). Whenever you create any component on activity_main, a corresponding
ID is created in the R.java file which can be used in the Java Source file later.

File: R.java
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.helloandroid;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int menu_settings=0x7f070000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int activity_main=0x7f060000;
}
public static final class string {
B. V. Raju Institute of Technology Page: 31
Mobile Application Development Department of CSE

public static final int app_name=0x7f040000;


public static final int hello_world=0x7f040001;
public static final int menu_settings=0x7f040002;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f050000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f050001;
}
}
APK File
An apk file is created by the framework automatically. If you want to run the android application on the
mobile, transfer and install it.

Resources
It contains resource files including activity_main, strings, styles etc.

Manifest file
It contains information about package including components such as activities, services, content providers etc.

B. V. Raju Institute of Technology Page: 32


Mobile Application Development Department of CSE

Android Emulator
The Android emulator is an Android Virtual Device (AVD), which represents a specific Android device. We can
use the Android emulator as a target device to execute and test our Android application on our PC. The
Android emulator provides almost all the functionality of a real device. We can get the incoming phone calls
and text messages. It also gives the location of the device and simulates different network speeds. Android
emulator simulates rotation and other hardware sensors. It accesses the Google Play store, and much more

Testing Android applications on emulator are sometimes faster and easier than doing on a real device. For
example, we can transfer data faster to the emulator than to a real device connected through USB.

The Android emulator comes with predefined configurations for several Android phones, Wear OS, tablet,
Android TV devices.

Requirement and recommendations

The Android emulator takes additional requirements beyond the basic system requirement for Android Studio.
These requirements are given below:

 SDK Tools 26.1.1 or higher

 64-bit processor

 Windows: CPU with UG (unrestricted guest) support

 HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)

Install the emulator

B. V. Raju Institute of Technology Page: 33


Mobile Application Development Department of CSE

The Android emulator is installed while installing the Android Studio. However some components of emulator
may or may not be installed while installing Android Studio. To install the emulator component, select
the Android Emulator component in the SDK Tools tab of the SDK Manager.

Run an Android app on the Emulator

We can run an Android app form the Android Studio project, or we can run an app which is installed on the
Android Emulator as we run any app on a device.

To start the Android Emulator and run an application in our project:

1. In Android Studio, we need to create an Android Virtual Device (AVD) that the emulator can use to install
and run your app.

To create a new AVD:


1.1 Open the AVD Manager by clicking Tools > AVD Manager.

1.2 Click on Create Virtual Device, at the bottom of the AVD Manager dialog. Then Select Hardware page
appears.

B. V. Raju Institute of Technology Page: 34


Mobile Application Development Department of CSE

1.3 Select a hardware profile and then click Next. If we don?t see the hardware profile we want, then we can
create or import a hardware profile. The System Image page appears.

B. V. Raju Institute of Technology Page: 35


Mobile Application Development Department of CSE

1.4 Select the system image for the particular API level and click Next. This leads to open a Verify
Configuration page.

1.5 Change AVD properties if needed, and then click Finish.

2. In the toolbar, choose the AVD, which we want to run our app from the target device from the drop-down
menu.

B. V. Raju Institute of Technology Page: 36


Mobile Application Development Department of CSE

3. Click Run.

Launch the Emulator without first running an app

To start the emulator:

1. Open the AVD Manager.

2. Double-click an AVD, or click Run

While the emulator is running, we can run the Android Studio project and select the emulator as the target
device. We can also drag an APKs file to install on an emulator, and then run them.

Start the emulator from the command line

The Android SDK includes the Android device emulator. Android emulator lets you develop and test out the
application without using a physical device.

Starting the emulator


Using the emulator command, we will start an emulator. It is an alternative to run our project or start through
the AVD Manager.

Here is the basic command-line syntax for starting a virtual device:

$ emulator -avd avd_name [ {-option [value]} ... ]

or

$ emulator @avd_name [ {-option [value]} ... ]

B. V. Raju Institute of Technology Page: 37


Mobile Application Development Department of CSE

For example, if we execute the emulator from Android Studio on a Mac, the default command line will be
similar as follows:

$ /Users/user_name/Library/Android/sdk/emulator/emulator -avd Nexus_5X_API_23 -


netdelay none -netspeed full
To display the list of AVD names, enter the following command:

$ emulator -list-avds

Run and stop an emulator, and clear data

From the Virtual Device page, we can perform the following operation on emulator:

 To run an Android emulator that uses an AVD, double-click the AVD, or click Launch

 To stop the running emulator, right-click and select Stop, or click Menu ▼ and select Stop.

 If we want to clear the data from an emulator and return it to the initial state when it was first
defined, then right-click an AVD and select Wipe Data. Or click menu ▼ and select Wipe Data.

B. V. Raju Institute of Technology Page: 38


Mobile Application Development Department of CSE

Android UI Layouts
Android Layout is used to define the user interface that holds the UI controls or widgets that will appear on
the screen of an android application or activity screen. Generally, every application is a combination of View
and ViewGroup. As we know, an android application contains a large number of activities and we can say each
activity is one page of the application. So, each activity contains multiple user interface components and those
components are the instances of the View and ViewGroup. All the elements in a layout are built using a
hierarchyof View and ViewGroup objects.

View

B. V. Raju Institute of Technology Page: 39


Mobile Application Development Department of CSE

A View is defined as the user interface which is used to create interactive UI components such
as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event handling and drawing. They
are Generally Called Widgets.

A ViewGroup act as a base class for layouts and layouts parameters that hold other Views or ViewGroups and
to define the layout properties. They are Generally Called layouts.

The Android framework will allow us to use UI elements or widgets in two ways:

 Use UI elements in the XML file

 Create elements in the Kotlin file dynamically

Types of Android Layout

 Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View elements one
by one either in a particular direction either horizontally or vertically based on the orientation
property.

 Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the position of child
View elements relative to each other like (A to the right of B) or relative to the parent (fix to the top of
the parent).
B. V. Raju Institute of Technology Page: 40
Mobile Application Development Department of CSE

 Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the position of
layout constraints for every child View relative to other views present. A ConstraintLayout is similar to
a RelativeLayout, but having more power.

 Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of View
elements it contains on the top of each other to display only a single View inside the FrameLayout.

 Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View elements in
rows and columns.

 Android Web View: WebView is a browser that is used to display the web pages in our activity layout.

 Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single column.

 Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of items in a grid
view of rows and columns.

Android UI Controls
In android UI or input controls are the interactive or View components that are used to design the user
interface of an application. In android we have a wide variety of UI or input controls available, those
are TextView, EditText, Buttons, Checkbox, Progressbar, Spinners, etc.

Generally, in android the user interface of an app is made with a collection of View and ViewGroup objects.

The View is a base class for all UI components in android and it is used to create interactive UI components
such as TextView, EditText, Checkbox, Radio Button, etc. and it is responsible for event handling and drawing.

The ViewGroup is a subclass of View and it will act as a base class for layouts and layout parameters. The
ViewGroup will provide invisible containers to hold other Views or ViewGroups and to define the layout
properties.

In android, we can define a UI or input controls in two ways, those are

 Declare UI elements in XML

 Create UI elements at runtime

The android framework will allow us to use either or both of these methods to define our application’s UI.

B. V. Raju Institute of Technology Page: 41


Mobile Application Development Department of CSE

Declare UI Elements in XML


In android, we can create layouts same as web pages in HTML by using default Views and ViewGroups in the
XML file. The layout file must contain only one root element, which must be a View or ViewGroup object.
Once we define the root element, then we can add additional layout objects or widgets as a child elements to
build View hierarchy that defines our layout.

Following is the example of defining UI controls (TextView, EditText, Button) in the XML file using Linear Layout
(activity_main.xml)

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Name" />
<EditText
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"/>
<Button
android:id="@+id/getName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Name" />
</LinearLayout>

In android, each input control is having a specific set of events and these events will be raised when the user
performs particular action like, entering the text or touches the button.

Note: we need to create a user interface (UI) layout files in /res/layout project directory, then only the layout
files will compile properly.

Load XML Layout File from an Activity


Once we are done with the creation of layout with UI controls, we need to load the XML layout resource from
our activity onCreate() callback method like as shown below.

B. V. Raju Institute of Technology Page: 42


Mobile Application Development Department of CSE

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file name activity_main.

Generally, during the launch of our activity, onCreate() callback method will be called by android framework
to get the required layout for an activity.

Create UI Element at Runtime


If we want to create UI elements at runtime, we need to create our own custom View and ViewGroup objects
programmatically with required layouts.

Following is the example of creating UI elements (TextView, EditText, Button) in LinearLayout using
custom View and ViewGroup objects in an activity programmatically.

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView1 = new TextView(this);
textView1.setText("Name:");
EditText editText1 = new EditText(this);
editText1.setText("Enter Name");
Button button1 = new Button(this);
button1.setText("Add Name");
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.addView(textView1);
linearLayout.addView(editText1);
linearLayout.addView(button1);
setContentView(linearLayout);
}
}

By creating a custom View and ViewGroups programmatically, we can define UI controls in layouts based on
our requirements in android applications.

Width and Height


When we define a UI controls in a layout using an XML file, we need to set width and height for
every View and ViewGroup elements using layout_width and layout_height attributes.

Following is the example of setting width and height for View and ViewGroup elements in the XML layout file.

B. V. Raju Institute of Technology Page: 43


Mobile Application Development Department of CSE

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Name" />
</LinearLayout>

If you observe above example, we used different values to set layout_width and layout_height, those are

 match_parent

 wrap_content

If we set value match_parent, then the View or ViewGroup will try to match with parent width or height.

If we set value wrap_content, then the View or ViewGroup will try to adjust its width or height based on the
content.

Android Different Types of UI Controls


We have a different type of UI controls available in android to implement the user interface for our android
applications.

Following are the commonly used UI or input controls in android applications.

 TextView
 EditText
 AutoCompleteTextView
 Button
 ImageButton
 ToggleButton
 CheckBox
 RadioButton
 RadioGroup

B. V. Raju Institute of Technology Page: 44


Mobile Application Development Department of CSE

 ProgressBar
 Spinner
 TimePicker
 DatePicker
 SeekBar
 AlertDialog
 Switch
 RatingBar

TextView
In android, TextView is a user interface control that is used to set and display the text to the user based on
our requirements. The TextView control will act as like label control and it won’t allow users to edit the text.

In android, we can create a TextView control in two ways either in XML layout file or create it in Activity file
programmatically.

Create a TextView in Layout File


Following is the sample way to define TextView control in XML layout file in android application.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to Tutlane"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>
If you observe above code snippet, here we defined a TextView control in xml layout file to display the text in
android application.

Create a TextView in Activity File


In android, we can create a TextView control programmatically in an activity file based on our requirements.

Following is the example of creating a TextView control dynamically in an activity file.

B. V. Raju Institute of Technology Page: 45


Mobile Application Development Department of CSE

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearla
yout);
TextView textView = new TextView(this);
textView.setText("Welcome to Tutlane");
linearLayout.addView(textView);
}
}

Set the Text of Android TextView


In android, we can set the text of TextView control either while declaring it in Layout file or by
using setText() method in Activity file.

Following is the example to set the text of TextView control while declaring it in the XML Layout file.

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to Tutlane" />

If you observe above example we used android:text property to the set required text for TextView control in
XML Layout file.

Following is another way to set the text of textview control programmatically in activity file
using setText() method.

TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText("Welcome to Tutlane");

If you observe above code snippet, we are getting the TextView control which we defined in XML layout
file using id property and setting the text using setText() method.

Android TextView Attributes


The following are some of the commonly used attributes related to TextView control in android applications.

Attribute Description

android: id It is used to uniquely identify the control

B. V. Raju Institute of Technology Page: 46


Mobile Application Development Department of CSE

Attribute Description

android:autoLink It will automatically found and convert URLs and email addresses as
clickable links.

android: ems It is used to make the textview be exactly this many ems wide.

android:hint It is used to display the hint text when text is empty

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

android:text It is used to display the text.

android:textColor It is used to change the color of the text.

android:gravity It is used to specify how to align the text by the view's x and y-axis.

android:maxWidth It is used to make the TextView be at most this many pixels wide.

android:minWidth It is used to make the TextView be at least this many pixels wide.

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:textAllCaps It is used to present the text in all CAPS

android:typeface It is used to specify the Typeface (normal, sans, serif, monospace) for the
text.

android:textColor It is used to change the color of the text.

android:textColorHighlight It is used to change the color of text selection highlight.

android:textColorLink It is used to change the text color of links.

android:inputType It is used to specify the type of text being placed in text fields.

android:fontFamily It is used to specify the fontFamily for the text.

android:editable If we set, it specifies that this TextView has an input method.

Android TextView Example


Create a new android application using android studio and give names as TextViewExample. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.

B. V. Raju Institute of Technology Page: 47


Mobile Application Development Department of CSE

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to Tutlane"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:textAllCaps="true" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Tutlane"
android:textStyle="bold"
android:textColor="#fff"
android:background="#7F3AB5"
android:layout_marginBottom="15dp"/>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="email|web"
android:text="For more details visit http://tutlane.com and send mail
to [email protected]" />
</LinearLayout>
Once we are done with creation of layout with required controls, we need to load the XML layout resource
from our activity onCreate() callback method, for that open main activity file

MainActivity.java from \java\com.tutlane.textviewexample path and write the code like as shown below.

MainActivity.java
B. V. Raju Institute of Technology Page: 48
Mobile Application Development Department of CSE

package com.tutlane.textviewexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText("Welcome to Tutlane");
}
}

If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file
name activity_main and we are setting text to one of our TextView control (textView2) in our activity file.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android TextView Example


When we run the above example using the android virtual device (AVD) we will get a result like as shown
below.

B. V. Raju Institute of Technology Page: 49


Mobile Application Development Department of CSE

EditText

EditText is a user interface control which is used to allow the user to enter or modify the text. While
using EditText control in our android applications, we need to specify the type of data the text field can accept
using the inputType attribute.

For example, if it accept plain text, then we need to specify the inputType as “text”. In case if EditText field is
for password, then we need to specify the inputType as “textPassword”.

In android, EditText control is an extended version of TextView control with additional features and it is used
to allow users to enter input values.

In android, we can create EditText control in two ways either in XML layout file or create it in Activity file
programmatically.

Create a EditText in Layout File


Following is the sample way to define EditText control in XML layout file in android application.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
B. V. Raju Institute of Technology Page: 50
Mobile Application Development Department of CSE

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"
android:inputType="text"/>
</LinearLayout>

If you observe above code snippet, here we defined EditText control to accept plain text by using inpuType as
“text” in xml layout file.

Create EditText Control in Activity File


In android, we can create EditText control programmatically in an activity file to allow users to enter text
based on our requirements.

Following is the example of creating EditText control dynamically in an activity file.

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearla
yout);
EditText et = new EditText(this);
et.setHint("Subject");
linearLayout.addView(et);
}
}

Set the Text of Android EditText


In android, we can set the text of EditText control either while declaring it in Layout file or by
using setText() method in Activity file.

Following is the example to set the text of TextView control while declaring it in XML Layout file.

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"

B. V. Raju Institute of Technology Page: 51


Mobile Application Development Department of CSE

android:layout_height="wrap_content"
android:text="Welcome to Tutlane" />

If you observe above example we used android:text property to the set required text for EditText control in
XML Layout file.

Following is another way to set the text of EditText control programmatically in activity file using setText()
method.

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text.

android:hint It is used to display the hint text when text is empty

android:textColor It is used to change the color of the text.

android:textColorHint It is used to change the text color of hint text.

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for edit text control

android:ems It is used to make the textview be exactly this many ems wide.

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

android:maxWidth It is used to make the TextView be at most this many pixels wide.

android:minWidth It is used to make the TextView be at least this many pixels wide.

android:textAllCaps It is used to present the text in all CAPS

android:typeface It is used to specify the Typeface (normal, sans, serif, monospace) for the
text.

android:textColorHighlight It is used to change the color of text selection highlight.

android:inputType It is used to specify the type of text being placed in text fields.

android:fontFamily It is used to specify the fontFamily for the text.

B. V. Raju Institute of Technology Page: 52


Mobile Application Development Department of CSE

android:editable If we set false, EditText won't allow us to enter or modify the text

EditText et = (EditText)findViewById(R.id.editText1);
et.setText("Welcome to Tutlane");

If you observe above code snippet, we are finding the EditText control which we defined in XML layout file
using id property and setting the text using setText() method.

Get Text of Android EditText


In android, we can get the text of EditText control by using getText() method in Activity file.

Following is the example to get text of EditText control programmatically in activity file
using getText() method.

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.txtSub);
String name = et.getText().toString();
}
}

If you observe above code snippet, we are finding the EditText control which we defined in XML layout file
using id property and getting the text of EditText control using getText() method.

Android EditText Attributes


The following are some of the commonly used attributes related to EditText control in android applications.

Android EditText Control Example


Following is the example of using multiple EditText controls with different input types like password, phone,
etc. in LinearLayout to build an android application.
Create a new android application using android studio and give names as EditTextExample. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

B. V. Raju Institute of Technology Page: 53


Mobile Application Development Department of CSE

activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="40dp"
android:orientation="vertical" android:id="@+id/linearlayout" >
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="Name"
android:inputType="text"
android:selectAllOnFocus="true" />
<EditText
android:id="@+id/txtPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password 0 to 9"
android:inputType="numberPassword" />
<EditText
android:id="@+id/txtEmai"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress" />
<EditText
android:id="@+id/txtDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:ems="10"
android:hint="Date"
android:inputType="date" />
<EditText
android:id="@+id/txtPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Phone Number"
android:inputType="phone"
android:textColorHint="#FE8DAB"/>
<Button
android:id="@+id/btnSend"

B. V. Raju Institute of Technology Page: 54


Mobile Application Development Department of CSE

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
android:textSize="16sp"
android:textStyle="normal|bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_marginTop="25dp"
android:textSize="15dp"/>
</LinearLayout>

If you observe above code we created multiple EditText controls with different inputTypes, such as password,
email address, date, phone number, plain text.
Once we are done with the creation of layout with required controls, we need to load the XML layout resource
from our activity onCreate() callback method, for that open main activity file
MainActivity.java from \java\com.tutlane.edittextexample path and write the code like as shown below.

MainActivity.java
package com.tutlane.edittextexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {


Button btnSubmit;
EditText name, password, email, dob, phoneno;
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.txtName);
password = (EditText)findViewById(R.id.txtPwd);
email = (EditText)findViewById(R.id.txtEmai);
dob = (EditText)findViewById(R.id.txtDate);
phoneno= (EditText)findViewById(R.id.txtPhone);
btnSubmit = (Button)findViewById(R.id.btnSend);
result = (TextView)findViewById(R.id.resultView);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
B. V. Raju Institute of Technology Page: 55
Mobile Application Development Department of CSE

public void onClick(View v) {


if (name.getText().toString().isEmpty() || password.getText().
toString().isEmpty() || email.getText().toString().isEmpty() || dob.getText().
toString().isEmpty()
|| phoneno.getText().toString().isEmpty()) {
result.setText("Please Fill All the Details");
} else {
result.setText("Name - " + name.getText().toString()
+ " \n" + "Password - " + password.getText().toString()
+ " \n" + "E-Mail - " + email.getText().toString(
) + " \n" + "DOB - " + dob.getText().toString()
+ " \n" + "Contact - " + phoneno.getText().toStri
ng());
}
}
});
}
}

If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file
name activity_main and we are getting the text of our EditText controls whenever we click on button.
Generally, during the launch of our activity, the onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android EditText Example

When we run the above example using the android virtual device (AVD) we will get a result like as shown
below.

B. V. Raju Institute of Technology Page: 56


Mobile Application Development Department of CSE

If you observe the above result, the system displaying an appropriate on-screen keyboard for
each EditText control based on the defined inputType attribute and displayed a message if we click on the
button without entering details in fields.

Once we enter details in all fields and click on Button we will get a result like as shown below.

AutoCompleteTextView
AutoCompleteTextView is an editable text view which is used to show the list of suggestions based on the
user typing text. The list of suggestions will be shown as a dropdown menu from which the user can choose
an item to replace the content of the textbox.

The AutoCompleteTextView is a subclass of EditText class so we can inherit all the properties of EditText in
AutoCompleteTextView based on our requirements.

Following is the pictorial representation of using AutoCompleteTextView in android applications.

B. V. Raju Institute of Technology Page: 57


Mobile Application Development Department of CSE

Generally, the dropdown list of suggestions can be obtained from the data adaptor and those suggestions will
be appeared only after giving the number characters defined in the Threshold limit.
The Threshold property of AutoCompleteTextView is used to define the minimum number of characters the
user must type to see the list of suggestions.
The dropdown list of suggestions can be closed at any time in case if no item is selected from the list or by
pressing the back or enter key.
In android, we can create an AutoCompleteTextView control in two ways either in the XML layout file or
create it in the Activity file programmatically.

Create AutoCompleteTextView in Layout File


Following is the sample way to define AutoCompleteTextView control in the XML layout file in the
android application.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="@+id/autoComplete_Country"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
If you observe above code snippet, here we defined AutoCompleteTextView control in xml layout file.

Create AutoCompleteTextView Control in Activity File

In android, we can create AutoCompleteTextView control programmatically in an activity file to show the
list of suggestions based on the user entered text.
Following is the example of creating AutoCompleteTextView control dynamically in activity file.

LinearLayout l_layout = (LinearLayout) findViewById(R.id.linear_Layout);


AutoCompleteTextView actv = new AutoCompleteTextView(this);
l_layout.addView(actv);

Set the Text of Android AutoCompleteTextView

In android, we can set the text of AutoCompleteTextView control by using setAdapter() method in Activity
file.
B. V. Raju Institute of Technology Page: 58
Mobile Application Development Department of CSE

Following is example of binding data AutoCompleteTextView in activity file using setAdapter() method.

String[] Countries = { "India", "USA", "Australia", "UK", "Italy", "Ireland"


, "Africa" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout
.simple_dropdown_item_1line, Countries);
AutoCompleteTextView actv = AutoCompleteTextView)findViewById(R.id.autoComplet
e_Country);
actv.setAdapter(adapter);

If you observe above code snippet, we are finding the AutoCompleteTextView control which we defined in
XML layout file using id property and binding the data using setAdapter() method.

Android AutoCompleteTextView Attributes


Following are the some of commonly used attributes related to AutoCompleteTextView control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text.

android:hint It is used to display the hint text when text is empty

android:textColor It is used to change the color of the text.

android:textColorHint It is used to change the text color of hint text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for autocomplete textview control

android:ems It is used to make the textview be exactly this many ems wide.

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

B. V. Raju Institute of Technology Page: 59


Mobile Application Development Department of CSE

Attribute Description

android:textColorHighlight It is used to change the color of the text selection highlight.

android:fontFamily It is used to specify the fontFamily for the text.

Android AutoCompleteTextView Control Example

Following is the example of defining AutoCompleteTextView control in LinearLayout to bind the data to
defined control using a data adapter and getting the selected list item value in the android application.

Create a new android application using android studio and give names as AutoCompleteTextViewExample .
In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical"
android:id="@+id/linear_Layout">
<AutoCompleteTextView
android:id="@+id/ac_Country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:hint="Enter Country Name"/>
</LinearLayout>
If you observe above code we created AutoCompleteTextView control in XML Layout file.

Once we are done with the creation of layout with required control, we need to load the XML layout resource
from our activity onCreate() callback method, for that open main activity file
MainActivity.java from \java\com.tutlane.autocompletetextviewexample path and write the code like
as shown below.

MainActivity.java
B. V. Raju Institute of Technology Page: 60
Mobile Application Development Department of CSE

package com.tutlane.autocompletetextviewexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


String[] Countries = { "India", "USA", "Australia", "UK", "Italy", "Irelan
d", "Africa" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, Countries);
AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.id.ac
_Country);
actv.setThreshold(1);
actv.setAdapter(adapter);
actv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int posi
tion, long id) {
Toast.makeText(getApplicationContext(), "Selected Item: " + pa
rent.getSelectedItem(), Toast.LENGTH_SHORT).show();
}
});
}
}

If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used
file name activity_main and binding data to our AutoCompleteTextView using ArrayAdapter and getting
selected list item value using getSelectedItem() method.

Generally, during the launch of our activity, onCreate() callback method will be called by the android
framework to get the required layout for an activity.

B. V. Raju Institute of Technology Page: 61


Mobile Application Development Department of CSE

Output of Android AutoCompleteTextView Example

When we run above example using the android virtual device (AVD) we will get a result like as shown
below.

Button
Button is a user interface control that is used to perform an action whenever the user clicks or tap on it.
Generally, Buttons in android will contain a text or an icon or both and perform an action when the user
touches it.
Following is the pictorial representation of using Buttons in android applications.

In android, we have a different type of buttons available to use based on our requirements, those
are ImageButton, ToggleButton, RadioButton.

B. V. Raju Institute of Technology Page: 62


Mobile Application Development Department of CSE

In android, we can create a Button control in two ways either in the XML layout file or create it in
the Activity file programmatically.

Create Button in XML Layout File


Following is the sample way to define Button control in the XML layout file in the android application.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>
If you observe above code snippet, here we defined Button control in xml layout file.

Create Button Control in Activity File


In android, we can create Button control programmatically in an activity file based on our requirements.
Following is the example of creating Button control dynamically in the activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


Button btn = new Button(this);
btn.setText("Test");
layout.addView(btn);

Android Handle Button Click Events


Generally, whenever the user clicks on a Button, the Button object will receives an on-click event.

In android, we can define a button click event in two ways either in the XML layout file or create it in
the Activity file programmatically.

Define Button Click Event in XML Layout File


We can define click event handler for button by adding android:onClick attribute to the <Button> element
in our XML layout file.

B. V. Raju Institute of Technology Page: 63


Mobile Application Development Department of CSE

The value of android:onClick attribute must be the name of the method which we need to call in response
to a click event and the Activity file which hosting XML layout must implement the corresponding method.

Following is the example of defining a button click event using android:onClick attribute in an XML layout
file.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:onClick="addOperation"/>
</LinearLayout>
In Activity that hosts our XML layout file, we need to implement click event method like as shown below

/** Called when the user touches the button */


public void addOperation(View view) {
// Do something in response to the button click
}

Define Button Click Event in Activity File


In android, we can define the button click event programmatically in the Activity file rather than XML layout
file.
To define button click programmatically, create View.OnClickListener object and assign it to the button by
calling setOnClickListener(View.OnClickListener) like as shown below.

Button btnAdd = (Button)findViewById(R.id.addBtn);


btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
}

This is how we can handle button click events in android applications based on our requirements.

B. V. Raju Institute of Technology Page: 64


Mobile Application Development Department of CSE

Android Button Control Attributes


Following are the some of commonly used attributes related to Button control in android applications.

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for button control.

android:padding It is used to set the padding from left, right, top and bottom.

android:drawableBottom It’s drawable to be drawn to the below of text.

android:drawableRight It’s drawable to be drawn to the right of text.

android:drawableLeft It’s drawable to be drawn to the left of the text.

Android Button Control Example


Following is the example of defining a one Button and two EditText controls in LinearLayout to get the data
of EditText controls when click on Button in android application.
Create a new android application using android studio and give names as ButtonExample. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
B. V. Raju Institute of Technology Page: 65
Mobile Application Development Department of CSE

android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="First Number" />
<EditText
android:id="@+id/firstNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Number"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/secondNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Add" />
</LinearLayout>
If you observe above code we created one Button, two TextView controls and two EditText controls in XML
Layout file.

Once we are done with the creation of layout with required control, we need to load the XML layout resource
from our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.buttonexample path and write the code like as shown
below.

MainActivity.java

package com.tutlane.buttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
B. V. Raju Institute of Technology Page: 66
Mobile Application Development Department of CSE

import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText firstNum = (EditText)findViewById(R.id.firstNum);
final EditText secNum = (EditText)findViewById(R.id.secondNum);
Button btnAdd = (Button)findViewById(R.id.addBtn);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(firstNum.getText().toString().isEmpty() || secNum.getText()
.toString().isEmpty())
{
Toast.makeText(getApplicationContext(), "Please fill all t
he fields", Toast.LENGTH_SHORT).show();
}
else {
int num1 = Integer.parseInt(firstNum.getText().toString())
;
int num2 = Integer.parseInt(secNum.getText().toString());
Toast.makeText(getApplicationContext(), "SUM = " + (num1 +
num2), Toast.LENGTH_SHORT).show();
}
}
});
}
}

If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used
file name activity_main and we are getting the values from two EditText controls on Button click and
performing an addition operation.

Generally, during the launch of our activity, onCreate() callback method will be called by the android
framework to get the required layout for an activity.

B. V. Raju Institute of Technology Page: 67


Mobile Application Development Department of CSE

Output of Android Button Example


When we run above example using android virtual device (AVD) we will get a result like as shown below.

CheckBox
CheckBox is a two-states button that can be either checked (ON) or unchecked (OFF) and it will allow users
to toggle between the two states (ON / OFF) based on the requirements.
Generally, we can use multiple CheckBox controls in android application to allow users to select one or more
options from the set of values.

By default, the android CheckBox will be in the OFF (Unchecked) state. We can change the default state
of CheckBox by using android:checked attribute.

B. V. Raju Institute of Technology Page: 68


Mobile Application Development Department of CSE

In case, if we want to change the state of CheckBox to ON (Checked), then we need to


set android:checked = “true” in our XML layout file.

In android, we can create CheckBox control in two ways either in the XML layout file or create it in
the Activity file programmatically.

Create CheckBox in XML Layout File


Following is the sample way to define CheckBox control in XML layout file in android application.

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java" /> </RelativeLayout>

If you observe above code snippet, here we defined CheckBox control and setting CheckBox
state ON using android:checked attribute in xml layout file.

Create CheckBox Control in Activity File

In android, we can create CheckBox control programmatically in activity file based on our requirements.

Following is the example of creating a CheckBox control dynamically in an activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


CheckBox cb = new CheckBox(this);
cb.setText("Tutlane");
cb.setChecked(true);
layout.addView(cb);

This is how we can define CheckBox in XML layout file or programmatically in activity file based on our
requirements.

B. V. Raju Institute of Technology Page: 69


Mobile Application Development Department of CSE

Handle Android CheckBox Click Events


Generally, whenever the user clicks on CheckBox to Select or Deselect the CheckBox object will receive
an on-click event.
In android, we can define the CheckBox click event in two ways either in the XML layout file or create it in
the Activity file programmatically.

Define CheckBox Click Event in XML Layout File

We can define a click event handler for button by adding the android:onClick attribute to the <CheckBox>
element in our XML layout file.
The value of android:onClick attribute must be the name of method which we need to call in response to a
click event and the Activity file which hosting XML layout must implement the corresponding method.
Following is the example of defining a CheckBox click event using android:onClick attribute in XML layout
file.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java"
android:onClick="onCheckBoxClick"/>
</LinearLayout>

In Activity that hosts our XML layout file, we need to implement click event method like as shown below.

public void onCheckboxClicked(View view) {


// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.chk1:
if (checked)
// Do your coding
else
// Do your coding
B. V. Raju Institute of Technology Page: 70
Mobile Application Development Department of CSE

break;
// Perform your logic
}
}

Define CheckBox Click Event in Activity File

In android, we can define CheckBox click event programmatically in Activity file rather than XML layout file.

To define checkbox click event programmatically, create View.OnClickListener object and assign it to the
button by calling setOnClickListener(View.OnClickListener) like as shown below.

CheckBox chk = (CheckBox) findViewById(R.id.chk1);


chk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean checked = ((CheckBox) v).isChecked();
// Check which checkbox was clicked
if (checked){
// Do your coding
}
else{
// Do your coding
}
}
});

This is how we can handle CheckBox click events in android applications based on our requirements.

Android CheckBox Control Attributes

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of checkbox

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text for a checkbox.

android:textColor It is used to change the color of text.

B. V. Raju Institute of Technology Page: 71


Mobile Application Development Department of CSE

Attribute Description

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for checkbox control.

android:padding It is used to set the padding from left, right, top and bottom.

android:onClick It’s the name of the method to invoke when the checkbox clicked.

android:visibility It is used to control the visibility of control.

Android CheckBox Control Example


Following is the example of defining multiple CheckBox controls and one Button control in LinearLayout to
get the selected values of CheckBox controls when we click on Button in the android application.

Create a new android application using android studio and give names as CheckBoxExample. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/chkJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"

B. V. Raju Institute of Technology Page: 72


Mobile Application Development Department of CSE

android:text="Python"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onCheckboxClicked"/>
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Get Details" />
</LinearLayout>

If you observe above code we created a multiple CheckBox controls and one Button control in XML Layout
file.

Once we are done with the creation of layout with required controls, we need to load the XML layout resource
from our activity onCreate() callback method, for that open main activity file
MainActivity.java from \java\com.tutlane.checkboxexample path and write the code like as shown
below.

MainActivity.java
package com.tutlane.checkboxexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

B. V. Raju Institute of Technology Page: 73


Mobile Application Development Department of CSE

public class MainActivity extends AppCompatActivity {


CheckBox android, java, angular, python;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (CheckBox)findViewById(R.id.chkAndroid);
angular = (CheckBox)findViewById(R.id.chkAngular);
java = (CheckBox)findViewById(R.id.chkJava);
python = (CheckBox)findViewById(R.id.chkPython);
Button btn = (Button)findViewById(R.id.getBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String result = "Selected Courses";
if(android.isChecked()){
result += "\nAndroid";
}
if(angular.isChecked()){
result += "\nAngularJS";
}
if(java.isChecked()){
result += "\nJava";
}
if(python.isChecked()){
result += "\nPython";
}
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_S
HORT).show();
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.chkAndroid:
str = checked?"Android Selected":"Android Deselected";
break;
case R.id.chkAngular:
str = checked?"AngularJS Selected":"AngularJS Deselected";
break;
case R.id.chkJava:
str = checked?"Java Selected":"Java Deselected";
break;
B. V. Raju Institute of Technology Page: 74
Mobile Application Development Department of CSE

case R.id.chkPython:
str = checked?"Python Selected":"Python Deselected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(
);
}
}

If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used
file name activity_main and we are getting the status of CheckBox controls when
they Select / Deselect and getting the selected CheckBox control values on Button click.

Generally, during the launch of our activity, onCreate() callback method will be called by android framework
to get the required layout for an activity.

Output of Android CheckBox Example


When we execute the above example using the android virtual device (AVD) we will get a result like as
shown below.

B. V. Raju Institute of Technology Page: 75


Mobile Application Development Department of CSE

Options Menu
Options Menu is a primary collection of menu items for an activity and it is useful to implement actions that
have a global impact on the app, such as Settings, Search, etc.

Following is the pictorial representation of using Options Menu in our android applications.

By using Options Menu, we can combine multiple actions and other options that are relevant to our
current activity. We can define items for the options menu from either our Activity or Fragment class.
In case, if we define items for the options menu in both activity or fragment, then those items will be
combined and display in UI.

Create Android Options Menu in XML File


In android, to define options menu, we need to create a new folder menu inside of our project resource
directory (res/menu/) and add a new XML (menu_example) file to build the menu.

Following is the example of defining a menu in an XML file (menu_example.xml).

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


<menu xmlns:android="http://schemas.android.com/apk/res/android">
B. V. Raju Institute of Technology Page: 76
Mobile Application Development Department of CSE

<item android:id="@+id/mail"
android:icon="@drawable/ic_mail"
android:title="@string/mail" />
<item android:id="@+id/upload"
android:icon="@drawable/ic_upload"
android:title="@string/upload"
android:showAsAction="ifRoom" />
<item android:id="@+id/share"
android:icon="@drawable/ic_share"
android:title="@string/share" />
</menu>

Load Android Options Menu from an Activity


To specify the options menu for an activity, we need to override onCreateOptionsMenu() method and load
the defined menu resource using MenuInflater.inflate() like as shown below.

@Override
public void onCreateOptionsMenu(ContextMenu menu, View v, ContextMenuInfo menu
Info) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_example, menu);
}

If you observe above code we are calling our menu using MenuInflater.inflate() method in the form
of R.menu.menu_file_name. Here our xml file name is menu_example.xml so we used file
name menu_example.

Handle Android Options Menu Click Events


In android, we can handle options menu item click events using the onOptionsItemSelected() event
method.
Following is the example of handling a options menu item click event using onOptionsItemSelected().

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mail:
// do something
return true;
case R.id.share:
B. V. Raju Institute of Technology Page: 77
Mobile Application Development Department of CSE

// do something
return true;
default:
return super.onContextItemSelected(item);
}
}

Android Options Menu Attributes


Following are the some of commonly used attributes related to options menu control in android
applications.

Attribute Description

android:id It is used to uniquely identify an element in application.

android:icon It is used to set the item's icon from the drawable folder.

android:title It is used to set the item's title

android:showAsAction It is used to specify how the item should appear as an action item in the app
bar.

Note: If you are using Android 3.0 +, the Options Menu won’t support any item shortcuts and item icons in
the menu.

Android Options Menu Example


Create a new android application using android studio and give names as OptionsMenu. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.
In android, to define options menu, we need to create a new folder menu inside of our project resource
directory (res/menu/) and add a new XML (options_menu.xml) file to build the menu.
Now open newly created xml (options_menu.xml) file and write the code like as shown below.

options_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/search_item"
android:title="Search" />
<item android:id="@+id/upload_item"
android:title="Upload" />
B. V. Raju Institute of Technology Page: 78
Mobile Application Development Department of CSE

<item android:id="@+id/copy_item"
android:title="Copy" />
<item android:id="@+id/print_item"
android:title="Print" />
<item android:id="@+id/share_item"
android:title="Share" />
<item android:id="@+id/bookmark_item"
android:title="BookMark" />
</menu>

Once we are done with creation of menu, we need to load this menu XML resource from
our activity using onCreateOptionsMenu() callback method, for that open main activity file
MainActivity.java from \java\com.tutlane.optionsmenu path and write the code like as shown below.

MainActivity.java
package com.tutlane.optionsmenu;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_
SHORT).show();
switch (item.getItemId()) {
case R.id.search_item:
// do your code
return true;
case R.id.upload_item:
B. V. Raju Institute of Technology Page: 79
Mobile Application Development Department of CSE

// do your code
return true;
case R.id.copy_item:
// do your code
return true;
case R.id.print_item:
// do your code
return true;
case R.id.share_item:
// do your code
return true;
case R.id.bookmark_item:
// do your code
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

If you observe above code we are overriding onCreateOptionsMenu() method in activity to create options
menu and loaded defined menu resource using MenuInflater.inflate().
Generally, during the launch of our activity, onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android Options Menu Example


When we run above example using an android virtual device (AVD) we will get a result like as shown below.

B. V. Raju Institute of Technology Page: 80


Mobile Application Development Department of CSE

Android Intents
Intent is a messaging object which is used to request an action from another app component such

as activities, services, broadcast receivers, and content providers.

Generally, in android, Intents will help us to maintain the communication between app components from
the same application as well as with the components of other applications.

In android, Intents are the objects of android.content.Intent types and intents are mainly useful to perform
the following things.

Component Description

Starting an By sending an Intent object to startActivity() method we can start a new


Activity Activity or existing Activity to perform required things.

Starting a Service By sending an Intent object to startService() method we can start a


new Service or send required instructions to an existing Service.

Delivering a By sending an Intent object to sendBroadcast() method we can deliver our


Broadcast messages to other app broadcast receivers.

Building an Intent Object


Generally, in android Intent object contains the information required to determine which component to start
and the information about the action to be performed by the recipient component.
The Intent object in android is having following characteristics to help the android system to understand
which component should start.

Component Name

It defines the name of the component to start and by using the component name android system will deliver
intent to the specific app component defined by the component name. In case if we didn’t define component
name then the android system will decide which component should receive intent based on other intent
information such as action, data, etc.
In android, we can specify the component name for intent by using a fully qualified class name of the target
component and package name, for example, com.tutlane.sampleActivity. We can set the component name
by using setComponent(), setClass(), setClassName() or by using the Intent constructor.

B. V. Raju Institute of Technology Page: 81


Mobile Application Development Department of CSE

Action

It defines the name of the action to be performed to start an activity. The following are some of the common
actions to start an activity.

Action Description

ACTION_VIEW We can use this action in intent with startActivity(), when we have information
that activity can show to the user.

ACTION_SEND We can use this action in intent with startActivity(), when we have some data that
the user can share through another app such as an email app, social sharing app.

We can specify the action name of intent by using setAction() or with an Intent constructor.
Data

It specifies a type of data to an intent filter. When we create an intent, it’s important to specify the type of
data (MIME type) in addition to its URI. By specifying a MIME type of data, it helps the android system to
decide which is the best component to receive our intent.

Category

Generally, the android category is optional for intents and it specifies the additional information about the
type of component that should handle an intent.
We can specify a category for intent by using addCategory().
The above properties (Component Name, Action, Data, and Category) will represent the characteristics of an
intent. By using these properties, the android system will easily decide which app component to start.

Android Intent Types


There are two types of intents available in android, those are Implicit Intents and Explicit Intents.

B. V. Raju Institute of Technology Page: 82


Mobile Application Development Department of CSE

Implicit Intents won’t specify any name of the component to start instead, it declare an action to

perform and it allows a component from other apps to handle it. For example, by using implicit intents we
can request another app to show the location details of the user or etc.

Following is the pictorial representation of how Implicit intents send a request to the android system to
start another activity.

If you observe the above image Activity A creates an intent with the required action and sends it to an
android system using the startActivity() method. The android system will search for an intent filter that
matches the intent in all apps. Whenever the match found the system starts matching activity (Activity B) by
invoking the onCreate() method.

In android when we create implicit intents, the android system will search for matching components by
comparing the contents of intent with intent filters which defined in the manifest file of other apps on the
device. If the matching component found, the system starts that component and sends it to the Intent object.
In case, if multiple intent filters are matched then the system displays a dialog so that the user can pick which
app to use.

In android, an Intent Filter is an expression in the app’s manifest file and it is used to specify the type of
intents that the component would like to receive. In case if we create an Intent Filter for activity, there is a
possibility for other apps to start our activity by sending a certain type of intent otherwise the activity can be
started only by an explicit intent.

B. V. Raju Institute of Technology Page: 83


Mobile Application Development Department of CSE

Following is the simple code snippet of implicit intent in the android application.

Intent intent=new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse("http://www.tutlane.com"));
startActivity(intent);

If you observe above implicit intent we didn’t defined any specific name of component to start, instead we
defined an action (ACTION_VIEW) to open the defined URL (http://www.tutlane.com) in browser within the
device.

Android Implicit Intent Example


Following is the complete example of implementing an implicit intent in the android application.

Create a new android application using android studio and open an activity_main.xml file
from \src\main\res\layout path. In case if you are not aware of creating an app in android studio check this
article Android Hello World App.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.tutlane.intents.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/urlText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:ems="10" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnNavigate"
android:layout_below="@+id/urlText"
android:text="Navigate"

B. V. Raju Institute of Technology Page: 84


Mobile Application Development Department of CSE

android:layout_centerHorizontal="true" />
</RelativeLayout>
Now open the main activity
file MainActivity.java from \src\main\java\com\tutlane\com.tutlane.helloworld path and write the
following code to open a new browser window on button click to load given url.

MainActivity.java
package com.tutlane.intents;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText)findViewById(R.id.urlText);
Button btn = (Button) findViewById(R.id.btnNavigate);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = editText.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url))
;
startActivity(intent);
}
});
}
}

Output of Android Implicit Intent Example


When we run above example using android virtual device (AVD) we will get a result like as shown below

B. V. Raju Institute of Technology Page: 85


Mobile Application Development Department of CSE

When we enter the website URL and click on the button it will open a website in a new browser window in
the same application.

Explicit intents explicitly specify the name of the component to be invoked by activity and we use

explicit intents to start a component in our own app. For example, we can start a new activity in response to
a user action using explicit intents.

By using explicit intents we can send or share data/content from one activity to another activity based on our
requirements. To create an Explicit Intent, we need to define the component name for an Intent object.

Following is the simple code snippet of explicit intent in the android application.

Intent di = new Intent(this, ActivityView.class);


di.setData(Uri.parse("http://www.tutlane.com"));
startService(di);

If you observe above explicit intent we specified an app context and external class name (ActivityView)
object. The intent explicitly start the ActivityView class in the app.

Android Explicit Intent Example


Following is the complete example of implementing an explicit intent in the android application. Here we will
do an addition of two numbers in one activity and sending that information to another activity to display the
result.

B. V. Raju Institute of Technology Page: 86


Mobile Application Development Department of CSE

Create a new android application using android studio and open an activity_main.xml file
from \src\main\res\layout path. In case if you are not aware of creating an app in android studio check this
article Android Hello World App.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="First Number"
/>
<EditText
android:id="@+id/firstNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10">
</EditText>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Number"
android:layout_marginLeft="100dp"
/>
<EditText
android:id="@+id/secondNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"

B. V. Raju Institute of Technology Page: 87


Mobile Application Development Department of CSE

android:text="Add" />
</LinearLayout>

Now we will create another layout resource file result.xml in \src\main\res\layout path to get the first
activity (activity_main.xml) details in second activity file for that right click on your layout folder  Go
to New  select Layout Resource File and give name as result.xml.
Once we create a new layout resource file result.xml, open it and write the code like as shown below

result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"/>
</LinearLayout>

Now open our main activity file MainActivity.java from \src\main\java\com.tutlane.intents path and
write the code like as shown below

MainActivity.java
package com.tutlane.intents;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText firstNum = (EditText)findViewById(R.id.firstNum);
B. V. Raju Institute of Technology Page: 88
Mobile Application Development Department of CSE

final EditText secNum = (EditText)findViewById(R.id.secondNum);


Button btnAdd = (Button)findViewById(R.id.addBtn);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(firstNum.getText().toString());
int num2 = Integer.parseInt(secNum.getText().toString());
Intent intent = new Intent(MainActivity.this,ResultActivity.cl
ass);
intent.putExtra("SUM",num1+" + "+num2+" = "+(num1+num2));
startActivity(intent);
}
});
}
}
Now we will create another activity file ResultActivity.java in \src\main\java\com.tutlane.intents path
to get the first activity (MainActivity.java) details in second activity file for that right click on your application
folder  Go to New  select Java Class and give name as ResultActivity.java.
Once we create a new activity file ResultActivity.java, open it and write the code like as shown below

ResultActivity.java
package com.tutlane.intents;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

/**
* Created by surdasari on 27-07-2017.
*/

public class ResultActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView result = (TextView)findViewById(R.id.resultView);
Intent intent = getIntent();
String addition = (String)intent.getSerializableExtra("SUM");
result.setText(addition);
}
}
Now we need to add this newly created activity in ActivityManifest.xml file in like as shown below.
B. V. Raju Institute of Technology Page: 89
Mobile Application Development Department of CSE

ActivityMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.intents">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="Explicit Intent - Activity1"
android:roundIcon="@mipmap/ic_launcher_round"
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>
<activity android:name=".ResultActivity" android:label="Explicit Inten
t - Activity2">
</activity>
</application>
</manifest>
If you observe above example we are performing an addition operation in one activity (MainActivity.java)
and sending those details to another activity (ResultActivity.java) and added all the activities in
AndroidManifest.xml file.

Output of Android Explicit Intent Example


When we run above example in the android emulator we will get a result like as shown below

B. V. Raju Institute of Technology Page: 90


Mobile Application Development Department of CSE

Controlling Progress:

Composing Programs
Using Android Studio for Java Coding
First of all, we need to launch Android Studio and create an Android project as we did in the previous chapter.
We can name the project as we want and select any Android version and any screen layout for now. When the
project loads, the project files and folders will be like the following in the left pane of Android Studio.

Default file structure of new Android studio Project

B. V. Raju Institute of Technology Page: 91


Mobile Application Development Department of CSE

Create a new Java Class

Creating a new Java file (Java class)


The Default code is
package com.example.atomic.javabasics1;
public class JavaBasics {
}
The first line defines a package that contains our new Java class. Java classes are organized in packages.
Packages are like folders on your computer that hold several files inside.
The second line is the main class definition. All programs are classes in Java hence all Java files (programs)
should have a class definition for compilation. Please always remember that the class definition should match
the name of the Java file (in our case the filename is JavaBasics.java and the class name is JavaBasics).
The contents of the programs are written inside the curly brackets opened just after the class name definition
in the second line and closed in the third line in Code 4.1.
Our Java file only has basic package and class definitions by default. The body of the Java class is empty thus
this Java program does not do anything at all when it is compiled and run.

B. V. Raju Institute of Technology Page: 92


Mobile Application Development Department of CSE

package com.example.atomic.javabasics1;
public class JavaBasics {
System.out.println("Hello World");
}

package com.example.atomic.javabasics1;
public class JavaBasics {
public static void main(String args[]) {
System.out.println("Hello World");
}
}

B. V. Raju Institute of Technology Page: 93


Mobile Application Development Department of CSE

Defining variables

B. V. Raju Institute of Technology Page: 94


Mobile Application Development Department of CSE

package com.helloworld.quantum.helloworld;
public class JavaBasics {
public static void main(String args[]){
int myInteger = 5; myInteger = myInteger + 7;
System.out.print("Sum = " + myInteger);
}
}

package com.example.atomic.javabasics1;
public class JavaBasics3 {
public static void main(String args[]) {
char myChar = 'd'; System.out.println(a);
}
}

Performing Operations

package com.helloworld.quantum.helloworld;
public class JavaBasics2 {
public static void main(String args[]){
float myFloat = 1.12345678901234567890f;
double myDouble = 1.12345678901234567890;
System.out.println("myFloat is: " + myFloat + ", myDouble is:
" + myDouble); }
}

B. V. Raju Institute of Technology Page: 95


Mobile Application Development Department of CSE

B. V. Raju Institute of Technology Page: 96


Mobile Application Development Department of CSE

Branching Flow

package com.helloworld.quantum.helloworld;
public class JavaIfElse {
public static void main(String args[]){
int a = 4; int b = 4;
if (a == b){
System.out.println("a and b are equal");
}
else {
System.out.println("a and b are not equal");
}
}

package com.helloworld.quantum.helloworld;
public class JavaNestedIfElse {
public static void main(String args[]){
int a = 3; int b = 4;
if (a == b){
System.out.println("a and b are equal"); }
else if(a > b) {
B. V. Raju Institute of Technology Page: 97
Mobile Application Development Department of CSE

System.out.println("a is greater than b"); }


else { System.out.println("a is lower than b");
}

Notifications
Notification is a message which is used to alert the users about some events that happening in our app.
Generally, the android Notifications will be displayed outside of our app’s normal UI and alert the users
without interrupting their current activities.
In android, we can alert the users about our app notifications in different forms like a flash the LED or make
sounds or display an icon in the status bar, etc.
When we tell the system to issue a notification, first it will display an icon in notification bar like as shown
below.

To see the details of our android app notification, we need to open the notification drawer like as shown
below.

B. V. Raju Institute of Technology Page: 98


Mobile Application Development Department of CSE

Now we will see how to create and issue notifications in android applications with examples.

Here we are going to use NotificationCompat class to implement notification in our android application.
The NotificationCompat class supports different types of notification views, such as normal view, big view
and it provides the best support for a wide range of platforms.

Create a Notification in Android


To create a notification, we need to specify the UI content and required actions with
a NotificationCompat.Builder object. To display an icon, title and detailed text of notification we need to
set the following properties in Builder object.

 setSmallIcon() - It is used to set the small icon for our notification.


 setContentTitle() - It is used to set the title of our notification.
 setContentText() - It is used to set the detailed text to display in notification.

The above-mentioned properties are necessary to display a notification and we can set a different type of
properties to our notification like setStyle, setSound, setLights, setLargeIcon, etc. based on our requirements
using Builder object.

Following is the example of creating a notification using NotificationCompat.Build object and setting the
notification properties.

NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)


.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Sample notification")
.setContentText("Hi, Welcome to Tutlane.com");

B. V. Raju Institute of Technology Page: 99


Mobile Application Development Department of CSE

Looping Statements

B. V. Raju Institute of Technology Page: 100


Mobile Application Development Department of CSE

B. V. Raju Institute of Technology Page: 101


Mobile Application Development Department of CSE

B. V. Raju Institute of Technology Page: 102

You might also like