Reference Book
Reference Book
Development
Master of Science
MSCIT - 302 Informa on Technology
2019
Mobile Application
Development
Course Writer
Subject Reviewer
Editors
Acknowledgement: “The content in this book is modifications based on work created and
shared by the Android Open Source Project and used according to terms described in the
Creative Commons 2.5 Attribution License.”
ISBN-978-81-940577-2-7
Printed and published by: Dr. Babasaheb Ambedkar Open University, Ahmedabad
Dr. Babasaheb MSCIT-302
Ambedkar Open
University
iii
Block-1
Introduction to Android,
Tools and Basics
1
Unit-1: The Android Platform 1
Unit Structure
1.0. Learning Objectives
1.1. Introduction
1.13. Assignment
2
1.0 LEARNING OBJECTIVE
After studying this unit student should be able to:
1.1 INTRODUCTION
Android is an operating system that powers mobile devices and is one of the most
popular mobile platforms today. Android platform runs on hundreds of millions of
mobile devices throughout the world. It's the largest installed operating system of any
mobile operating system and growing rapidly day by day.
You can develop apps and games using Android and it gives you an open
marketplace for distributing your apps and games instantly.
Android is the operating system for powering screens of all sizes. Android version is
named after a dessert. The latest version of android is Android 9.0 – Pie. Following
table shows how the android platform evolves.
The Motorola DynaTAC 8000X was the first commercially available cell phone and it
is of brick size. First-generation mobile were expensive, not particularly full featured
and has Proprietary software.
As mobile phone prices dropped, batteries improved, and reception areas grew,
more and more people began carrying these handy devices. Customers began
pushing for more features and more games.They needed some way to provide a
portal for entertainment and information services without allowing direct access to
the handset.
3
Early phone have postage stamp-sized low-resolution screens and limited storage
and processing power, these phones couldn’t handle the data-intensive operations
required by traditional web browsers.The bandwidth requirements for data
transmission were also costly to the user.
WAP fell short of commercial expectations due to following reasons and Critics
began to call WAP “Wait and Pay.”
Writing robust applications with WAP, such as graphic-intensive video games, was
nearly impossible.Memory was getting cheaper, batteries were getting better, and
PDAs and other embedded devices were beginning to run compact versions of
common operating systems such as Linux and Windows.A variety of different
proprietary platforms emergedand developers are still actively creating applications
for them. Some of the examples of proprietary mobile platform are:
4
• Binary Runtime Environment for Wireless (BREW)
• Symbian OS
• OS X iPhone
The OHA hopes to deliver a better mobile software experience for consumers by
providing the platformneeded for innovative mobile development at a faster rate and
with higher quality than existingplatforms, without licensing fees for either software
developers or handset manufacturers.
Andy Rubin has been credited as the father of the Android platform. His company,
Android Inc., was acquired by Google in 2005.Working together, OHA members,
including Google, began developing a non-proprietary open standard platform based
upon technology developed at Android Inc. that would aim to solve the problems
hindering the mobile community.The result is the Android project.
5
What is android?
Android is called as “the first complete, open, and free mobile platform”:
Features of Android
What it is not?
Android is not:
6
• A mobile phone handset Android includes a reference design for mobile handset
manufacturers, but there is no single ‘‘Android phone.’’ Instead, Android has been
designed to support many alternative hardware devices.
• Google’s answer to the iPhone: The iPhone is a fully proprietary hardware and
software platform released by a single company (Apple), while Android is an
open-source software
Android is the operating system for powering screens of all sizes. Android version is
named after a dessert. The latest version of android is Android 9.0 – Pie. Following
table shows how the android platform evolves.
7
Android Name Feature API
Version Level
API and added a number of features such as
Details and reviews available when a user
searches for businesses on Maps, Ability to
show/hide dial pad and save attachments in
messages.
1.5 Cupcake Virtual keyboards with text prediction and user 3
dictionary for custom words, widgets, video
recording and playback, Bluetooth, Copy and
Paste, animated screen transition, auto rotation,
upload video on YouTube, upload photo to
Picasa.
1.6 Donut Voice and text entry search, Multi-lingual 4
speech synthesis, updated technology support
for CDMA/EVDO, 802.1x, VPNs, and a text-to-
speech engine, WVGA screen resolutions,
Expanded Gesture framework and new Gesture
Builder development tool
2.0 Éclair Customize your home screen just the way you 5
2.0.1 want it. Arrange apps and widgets across 6
2.1 multiple screens and in folders. Stunning live 7
wallpapers respond to your touch.
2.2-2.2.3 Froyo Voice Typing lets you input text, while Voice 8
Actions allow you to control your phone, just by
speaking.
2.3 Gingerbread New sensors make Android great for gaming – 9-10
so you can touch, tap, tilt and play away.
3.0 Honeycomb Optimized for tablets. 11-13
4.0 Ice Cream A new, refined design. Simple, beautiful and 14-15
Sandwich beyond smart.
4.1-4.3 Jelly Bean Fast and smooth with slick graphics. With 16-18
Google Now, you get just the right information
8
Android Name Feature API
Version Level
at the right time.
4.4 Kit Kat A more polished design, improved performance 19-20
and new features.
5.0 Lolipop Get the smarts of Android on screens big and 21-22
small with the right information at the right
moment.
6.0 Marshmallow New App Drawer, Doze mode, Native finger 23
print support, Android pay, USB type-C and
USB 3.1 support, Direct share.
7.0 Nougat Revamped notification, Split-screen use, file 24-25
based encryption, direct boot, data saver
8.0 Oreo Picture in picture, Google play protect, emoji 26-27
9.0 Pie Adaptive Battery, adaptive brightness, intuitive 28
navigation, dashboard, App timers, Wind down
and do not disturb, Digital wellbeing.
Android phones will normally come with a suite of generic preinstalled applications
that are part of theAndroid Open Source Project (AOSP), including, but not
necessarily limited to:
• An e-mail client
• An SMS management application
• A full PIM (personal information management) suite including a calendar and
contacts list
• AWebKit-based web browser
• A music player and picture gallery
• A camera and video recording application
• A calculator
9
• The home screen
• An alarm clock
In many cases Android devices will also ship with the following proprietary Google
mobileapplications:
11
specific type of hardware component, such as the camera or Bluetooth module.
When a framework API makes a call to access device hardware, the Android system
loads the library module for that hardware component.
Android Runtime
For devices running Android version 5.0 (API level 21) or higher, each app runs in its
own process and with its own instance of the Android Runtime (ART). ART is written
to run multiple virtual machines on low-memory devices by executing DEX files, a
byte code format designed especially for Android that's optimized for minimal
memory footprint. Build tool chains, such as Jack, compile Java sources into DEX
byte code, which can run on the Android platform.
12
code, you can use the Android NDK to access some of these native platform libraries
directly from your native code.
Developers have full access to the same framework APIs that Android system apps
use.
System Apps
Android comes with a set of core apps for email, SMS messaging, calendars,
internet browsing, contacts, and more. Apps included with the platform have no
special status among the apps the user chooses to install. So a third-party app can
become the user's default web browser, SMS messenger, or even the default
keyboard (some exceptions apply, such as the system's Settings app).
The system apps function both as apps for users and to provide key capabilities that
developers can access from their own app. For example, if your app would like to
deliver an SMS message, you don't need to build that functionality you—you can
instead invoke whichever SMS app is already installed to deliver a message to the
recipient you specify.
Following are some of the factors that affect app development time:
1.10Let us sum up
In this unit we have discussed the history of mobile application development, you
have got detailed understanding of android and its version, android SDK features
and architecture, and we also elaborate factors that should be given consideration
while developing mobile application
15
1.11Check your progress: Possible Answers
1-a True
1-b False
1-c Some of the examples of proprietary mobile platform are:
• Palm OS (now Garnet OS)
• RIM BlackBerry OS
• Java Micro Edition [Java ME]
• Binary Runtime Environment for Wireless (BREW)
• Symbian OS
• OS X iPhone
1-d OHA stands for Open Handset Alliance
1-e Due to following reasons and Critics began to call WAP “Wait and Pay.”
• Handset screens were too small for surfing.
• WAP browsers, especially in the early days, were slow and frustrating.
• Reading a sentence fragment at a time, and then waiting seconds for the next
segment to download, ruined the user experience, especially because every
second of downloading was often charged to the user.
• Mobile operators who provided the WAP portal often restricted which WAP
sites were accessible.
2-a True
2-b True
2-c Android version 9 Pie is the latest version of Android
2-d A software development kit that enables developers to create applications for
the Android platform. The Android SDK includes sample projects with source
code, development tools, an emulator, and required libraries to build Android
applications.
3-a) Following are the components of Android Software Stack
• The Linux Kernel
• Hardware Abstraction Layer (HAL)
• Android Runtime
• Native C/C++ Libraries
16
• Java API Framework
• System Apps
3-b) The foundation of the Android platform is the Linux kernel
3-c)
• JIT – Just In Time
• ART – Android Run Time
• HAL – Hardware Abstraction Layer
3-d) Following are the important features of Android Run Time
• Ahead-of-time (AOT) and just-in-time (JIT) compilation
• Optimized garbage collection (GC)
• On Android 9 (API level 28) and higher, conversion of an app package's
Dalvik Executable format (DEX) files to more compact machine code.
• Better debugging support, including a dedicated sampling profiler, detailed
diagnostic exceptions and crash reporting, and the ability to set watch points
to monitor specific fields
1.13Assignments
• What is android? Explain history of android version with API level
• Explain android architecture and features of android SDK
17
Unit-2: Installing Android Studio 2
Unit Structure
2.0 Learning Objectives
2.1 Introduction
2.11 Assignment
2.12 Activities
18
2.0 Learning Objectives
2.1 Introduction
For developing application for android platform, you will require Integrated
Development Environment (IDE). Android Studio is the official IDE for Android
application development. Android Studio provides everything you need to start
developing apps for Android, including the Android Studio IDE and the Android SDK
tools. First we discuss what the system requirements for android studio are and how
to install and configure android studio.
19
Figure-2
Click green button “Download Android Studio for Windows” it will open following
page.
Figure-3
Accept term and condition at the bottom and press blue button “Download Android
Studio for Windows”. It will start downloading android studio for windows. Do not
start installation before downloading and installing JDK 1.7 is over.
20
2.4 Downloading JDK
Figure-4
Go to bottom of the page and accept License agreement and download JDK for
Windows x86 or Windows x64 for windows 32 bit and windows 64 bit respectively.
Figure-5
21
2.5 Installing JDK
Double click downloaded JDK Installation file and follow instructions on screen.
Figure-6
Press Next Button
Figure-7
22
Press Next Button this will start installation as shown below.
Figure-8
After installation starts it will asks for Java Runtime Environment (JRE) Installation
location.
Figure-9
Figure-11
24
To ensure that JDK is properly installed, open a terminal and type javac –version
and press enter as shown below.
Figure-12
Figure-13
25
Figure-14
Figure-15
26
Figure-16
Specify path for Android Studio Installation and Android SDK Installation or use
default and press Next button.
Figure-17
27
Figure-18
Figure-19
28
Figure-20
Important Note:On some Windows systems, the launcher script does not find
where Java is installed. If you encounter this problem, you need to set an
environment variable indicating the correct location. Select Start menu >
Computer > System Properties > Advanced System Properties. Then open
Advanced tab > Environment Variables and add a new system variable
JAVA_HOME that points to your JDK folder, for example C:\Program
Files\Java\jdk1.7.0_XX.
Figure-21
Select last option and press OK. It will download updates and create virtual device
for you.
29
Figure-22
Press finish button to start Android Studio with following initial welcome screen.
Figure-23
30
Check your Progress – 1
2.11 Assignments
• Explain the steps for downloading, installing and launching Android Studio
2.13 Activities
• Download and install android studio
31
Unit-3: Android Studio for 3
Android Software Development
Unit Structure
3.0 Learning Objectives
3.1 Introduction
3.12 Assignment
3.13 Activities
32
3.0 Learning Objectives
3.1 Introduction
Android Studio is the official Integrated Development Environment (IDE) for Android
app development. Android Studio offers many features that enhance your
productivity when building Android apps. In this unit we will explore in great details
about Android Studio.
Android Studio has following salient features for android application development:
Intelligent code editor: Android Studio provides an intelligent code editor capable
of advanced code completion, refactoring, and code analysis. The powerful code
editor helps you be a more productive Android app developer.
Project Wizard: New project wizards make it easier than ever to start a new project.
Start projects using template code for patterns such as navigation drawer and view
pagers, and even import Google code samples from GitHub.
Multi-screen app development: Build apps for Android phones, tablets, Android
Wear, Android TV, Android Auto and Google Glass. With the new Android Project
33
View and module support in Android Studio, it's easier to manage app projects and
resources.
Virtual devices for all shapes and sizes: Android Studio comes pre-configured
with an optimized emulator image. The updated and streamlined Virtual Device
Manager provides pre-defined device profiles for common Android devices.
Android builds evolved, with Gradle: Create multiple APKs for your Android app
with different features using the same project.
To develop apps for Android, you use a set of tools that are included in Android
Studio. In addition to using the tools from Android Studio, you can also access most
of the SDK tools from the command line.
The basic steps for developing applications encompass four development phases,
which include:
• Environment Setup: During this phase you install and set up your development
environment. You also create Android Virtual Devices (AVDs) and connect
hardware devices on which you can install your applications.
• Project Setup and Development: During this phase you set up and develop
your Android Studio project and application modules, which contain all of the
source code and resource files for your application.
• Building, Debugging and Testing: During this phase you build your project into
a debuggable .apk package(s) that you can install and run on the emulator or an
Android-powered device. Android Studio uses a build system based on Gradle
that provides flexibility, customized build variants, dependency resolution, and
much more. If you're using another IDE, you can build your project using Gradle
and install it on a device using adb.
34
Next, with Android Studio you debug your application using the Android Debug
Monitor and device log messages along with the IntelliJ IDEA intelligent coding
features. You can also use a JDWP-compliant debugger along with the
debugging and logging tools that are provided with the Android SDK.
Last, you test your application using various Android SDK testing tools.
• Publishing: During this phase you configure and build your application for
release and distribute your application to users.
An Android Virtual Device (AVD) is an emulator configuration that lets you model an
actual device by defining hardware and software options to be emulated by the
Android Emulator.An AVD consists of:
A hardware profile: Defines the hardware features of the virtual device. For
example, you can define whether the device has a camera, whether it uses a
physical QWERTY keyboard or a dialing pad, how much memory it has, and so on.
A mapping to a system image: You can define what version of the Android
platform will run on the virtual device. You can choose a version of the standard
Android platform or the system image packaged with an SDK add-on.
Other options: You can specify the emulator skin you want to use with the AVD,
which lets you control the screen dimensions, appearance, and so on. You can also
specify the emulated SD card to use with the AVD.
A dedicated storage area on your development machine: the device's user data
(installed applications, settings, and so on) and emulated SD card are stored in this
area.
The easiest way to create an AVD is to use the graphical AVD Manager. You can
also start the AVD Manager from the command line by calling the android tool with
the avd options, from the <sdk>/tools/ directory.
35
You can also create AVDs on the command line by passing the android tool options.
You can create as many AVDs as you need, based on the types of device you want
to model. To thoroughly test your application, you should create an AVD for each
general device configuration (for example, different screen sizes and platform
versions) with which your application is compatible and test your application on each
one.Keep these points in mind when you are selecting a system image target for
your AVD:
• The API Level of the target is important, because your application will not be able
to run on a system image whose API Level is less than that required by your
application, as specified in the minSdkVersion attribute of the application's
manifest file.
• You should create at least one AVD that uses a target whose API Level is greater
than that required by your application, because it allows you to test the forward-
compatibility of your application. Forward-compatibility testing ensures that, when
users who have downloaded your application receive a system update, your
application will continue to function normally.
• If your application declares a uses-library element in its manifest file, the
application can only run on a system image in which that external library is
present. If you want to run your application on an emulator, create an AVD that
includes the required library. Usually, you must create such an AVD using an
Add-on component for the AVD's platform.
36
3.5 Using Hardware Device to test Application
When building a mobile application, it's important that you always test your
application on a real device before releasing it to users.
You can use any Android-powered device as an environment for running, debugging,
and testing your applications. The tools included in the SDK make it easy to install
and run your application on the device each time you compile. You can install your
application on the device directly from Android Studio or from the command line with
ADB.
Android Studio has just created an application project and opened the main window
as shown below.
37
Figure-25: Android studio IDE
Double click on the file to load it into the User Interface Designer tool which will
appear in the center panel of the Android Studio main window as shown below:
Designer Window
This is where you design your user interface. In the top of the Designer window is a
menu set to Nexus 4 device which is shown in the Designer panel.
38
Pellet
On left hand side of the panel is a palette containing different categories of user
interface components that may be used to construct a user interface, such as
buttons, labels and text fields. Android supports a variety of different layouts that
provide different levels of control over how visual user interface components are
positioned and managed on the screen.
Component Tree panel is by default located in the upper right hand corner of the
Designer panel and is shown in Figure and shows layout used for user interface.
Property Window
Property Window allows setting different properties of selected component.
39
XML Editing Panel
We can modify user interface by modifying the activity_hello_world.xml using UI
Designer tool but we can also modify design by editing XML file also. At the bottom
of the Designer panel are two tabs labeled Design and Text respectively. To switch
to the XML view simply select the Text tab as shown in Figure. At the right hand side
of the XML editing panel is the Preview panel and shows the current visual state of
the layout.
40
Figure-30:Previewing the Layout
We customize code editor for font, displaying quick help when mouse moves over
code.
Font Customization:
From File menu select settings option following dialog will open.
Figure-31
Select Colors & Fonts option. In scheme Default scheme is displayed. Click “Save
As…” Button and give new name as “My Settings” to scheme. Now select font
option as shown below and customize font as per your requirement.
41
Figure-32
From file menu select settings option following dialog box appears. Select General
option from list and scroll down to checkbox highlighted with red rectangle in below
figure. Then press OK.
Figure-33
42
3.8 Coding Best Practices
Following are some of the code editing practices you should follow when creating
Android Studio apps.
Table-2
43
The following tables list keyboard shortcuts for common operations.
You can change these shortcuts from file menu settings option as shown below.
44
d) We can customize the code editor for font, displaying quick help when mouse
moves over code. (True/False)
Figure-34
3.12 Assignment
• Explain different components of Android Studio
3.13 Activities
46
Block-2
Android Application
Development Basics
47
Unit-1: Building a sample
Android application using 1
Android Studio
1.0. Learning Objectives
1.1. Introduction
1.10. Assignment
1.11. Activities
48
1.0 Learning Objectives
1.1 Introduction
With all the tools and the SDK downloaded and installed, it is now time to start your
engine! Asin all programming books, the first example uses the ubiquitous Hello
World application. This willenable you to have a detailed look at the various
components that make up an Android project.
So, without any further ado, let’s dive straight in!Generally a program is defined in
terms of functionality and data, and an Android application is not an exception. It
performs processing, show information on the screen, and takes data from a variety
of sources.
To Develop Android applications for mobile devices with resource constraint requires
a systematic understanding of the application lifecycle. This unit introduces you with
the most important components of Android applications and provides you with a
more detailed understanding of how to create and run an Android application.
49
explore the use of the Android emulator environment to perform a test run of the
application.
The first step in the application development process is to create a new project within
the Android Studio environment. Launch Android Studio so that the “Welcome to
Android Studio” screen appears as shown Figure:
Figure-35
To create the new project, simply click on the Start a new Android Studio project
option to display the first screen of the New Project wizard as shown in Figure:
Figure-36
In the New Project window, set the Application name field to HelloWorld. The
application name is the name by which the application will be referenced and
50
identified within Android Studio and is also the name that will be used when the
completed application goes on sale in the Google Play store.
The Package Name is used to uniquely identify the application within the Android
application ecosystem. It should be based on the reversed URL of your domain
name followed by the name of the application. For example, if your domain is
www.baou.edu, and the application has been named HelloWorld, then the package
name might be specified as follows:
edu.baou.HelloWorld
The Project location setting will default to a location in the folder named
AndroidStudioProjects located in your home directory and may be changed by
clicking on the button to the right of the text field containing the current path setting.
On the form factors screen, enable the Phone and Tablet option and set the
minimum SDK setting to API 8: Android 2.2 (Froyo). The reason for selecting an
older SDK release is that this ensures that the finished application will be able to run
on the widest possible range of Android devices. The higher the minimum SDK
selection, the more the application will be restricted to newer Android devices.
Figure-37
Click Next to proceed.
51
1.5 Creating Activity
The next step is to define the type of initial activity that is to be created for the
application. A range of different activity types is available when developing Android
applications. For sack of simplicity we select the option to create a Blank Activity and
Click Next to proceed.
Figure-38
On the final screen name the activity and title HelloWorldActivity. The activity will
consist of a single user interface screen layout which, for the purposes of this
example, should be named activity_hello_world as shown in Figure and with a menu
resource named menu_hello_world:
Figure-39
Finally, click on Finish to initiate the project creation process.
52
1.6 Running a HelloWorld Application
1. Press Shift+F10 or ‘Run App’ button in taskbar. It will launch following dialog box.
Figure-40
2. Select Launch emulator option and select your Android virtual device and Press
OK.
3. The Android emulator starts up, which might take a moment
4. Press the Menu button to unlock the emulator.
5. The application starts, as shown in Figure below.
Figure-41
53
7. Pull up the Application Drawer to see installed applications. Your screen looks
something
8. like Figure shown below
Figure-42
Recall that earlier you created a few AVDs using the AVD Manager. So which one
will be launched by Android Studio when you run an Android application? Android
studio will check the target that you specified (when you created a new project),
comparing it against the list of AVDs that you have created. The first one that
matches will be launched to run your application.
If you have more than one suitable AVD running prior to debugging the application,
Android Studio will display the Android Device Chooser window, which enables you
to select the desired emulator/device to debug the application.
54
d) __________ should be based on the reversed URL of your domain name
followed by the name of the application.
1-a) The reason for selecting an older SDK release is that this ensures that the
finished application will be able to run on the widest possible range of Android
devices
1-b) Shift+F10
1-c) True
1-d) Package Name
1.10 Assignment
• Write steps for creating an Android Application
1.11 Activities
55
Unit-2: Android Project
Structure and Basics 2
Unit Structure
2.0 Learning Objectives
2.1 Introduction
2.14 Assignment
56
2.0 Learning Objectives
2.1 Introduction
The Android build system is organized around a specific directory tree structure for
the Androidproject, similar to theany Java project. The project prepares the actual
application that will run on the device or emulator. When you create a new Android
project, you get several items in the project’s root directory which is discussed in sub
sequent sections.
When you create an Android project as discussed in previous unit, you provide the
fully-qualifiedclass name of the “main” activity for the application
(e.g.,edu.baou.HelloWorld).
You will then find that your project’s src/ tree already has the namespace directory
tree inplace, plus a stub Activity subclass representing your main activity (e.g.,
src/edu/baou/HelloWorld.java). You can modify this file and add others to the src/
tree as per requirement implement your application.
When you compile the project for first time, in the “main” activity’s
namespacedirectory, the Android build chain will create R.java. This contains a
number of constants tiedto the various resources you placed out in the res/ directory
57
tree. You should not modify R.javayourself, letting the Android tools handle it for you.
You will see throughout many of the sampleswhere we reference things in R.java
(e.g., referring to a layout’s identifier via R.layout.main).
A module is the first level of control within a project that encapsulates specific types
of source code files and resources. There are several types of modules with a
project:
Module Description
Android It contain source code, resource files, and application level
Application settings, such as the module-level build file, resource files, and
Modules Android Manifest file.
Test Modules It contains code to test your application projects and is built into
test applications that run on a device.
Library It contains shareable Android source code and resources that you
Modules can reference in Android projects. This is useful when you have
common code that you want to reuse.
App Engine They are App Engine java Servlet Module for backend
Modules development, App Engine java Endpoints Module to convert
server-side Java code annotations into RESTful backend APIs,
and App Engine Backend with Google Cloud Messaging to send
push notifications from your server to your Android devices.
Table-4
When you use the Android development tools to create a new project and the
module, the essential files and folders will be created for you. As your application
grows in complexity, you might require new kinds of resources, directories, and files.
58
2.3 Android Project Files
Android Studio project files and settings provide project-wide settings that apply
across all modules in the project.
Figure-43
File Meaning
.idea Directory for IntelliJ IDEA settings.
App Application module directories and files.
Build This directory stores the build output for all project modules.
Gradle Contains the gradler-wrapper files.
.gitignore Specifies the untracked files that Git should ignore.
build.gradle Customizable properties for the build system.
gradle.properties Project-wide Gradle settings.
gradlew Gradle startup script for Unix.
gradlew.bat Gradle startup script for Windows.
local.properties Customizable computer-specific properties for the build system,
such as the path to the SDK installation.
.iml Module file created by the IntelliJ IDEA to store module
information.
settings.gradle Specifies the sub-projects to build.
Table-5
59
Check your progress-1
a) _________contains shareable Android source code and resources that you can
reference in Android projects.
b) _________ contain source code, resource files, and application level settings,
such as the module-level build file, resource files, and Android Manifest file.
c) When you compile the project for first time, in the “main” activity’s namespace
directory, the Android build chain will create _________
Android Application Modules contain things such as application source code and
resource files. Most code and resource files are generated for you by default, while
others should be created if required. The following directories and files comprise an
Android application module:
Figure-44
60
File Meaning
build/ Contains build folders for the specified build variants. Stored in the
main application module.
libs/ Contains private libraries. Stored in the main application module.
src/ Contains your stub Activity file, which is stored at
src/main/java/<ActivityName>.java. All other source code files
(such as .java or .aidl files) go here as well.
androidTest/ Contains the instrumentation tests.
main/jni/ Contains native code using the Java Native Interface (JNI).
main/gen/ Contains the Java files generated by Android Studio, such as your
R.java file and interfaces created from AIDL files.
main/assets/ This is empty. You can use it to store raw asset files. For example,
this is a good location for textures and game data. Files that you
save here are compiled into an .apk file as-is, and the original
filename is preserved. You can navigate this directory and read
files as a stream of bytes using the AssetManager.
main/res/ Contains application resources, such as drawable files, layout files,
and string values in the following directories.
anim/ For XML files that are compiled into animation objects.
color/ For XML files that describe colors.
drawable/ For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and
XML files that describe Drawable shapes or Drawable objects that
contain multiple states (normal, pressed, or focused).
mipmap/ For app launcher icons. The Android system retains the resources
in this folder (and density-specific folders such as mipmap-
xxxhdpi) regardless of the screen resolution of the device where
your app is installed. This behavior allows launcher apps to pick
the best resolution icon for your app to display on the home
screen.
layout/ XML files that are compiled into screen layouts (or part of a
screen).
menu/ For XML files that define application menus.
61
File Meaning
raw/ For arbitrary raw asset files. Saving asset files here is essentially
the same as saving them in the assets/ directory. The only
difference is how you access them. These files are processed by
aapt and must be referenced from the application using a resource
identifier in the R class. For example, this is a good place for
media, such as MP3 or Ogg files.
values/ For XML files that define resources by XML element type. Unlike
other resources in the res/ directory, resources written to XML files
in this folder are not referenced by the file name. Instead, the XML
element type controls how the resources defined within the XML
files are placed into the R class.
xml/ For miscellaneous XML files that configure application
components. For example, an XML file that defines a
PreferenceScreen, AppWidgetProviderInfo, or Searchability
Metadata.
AndroidManife The control file that describes the nature of the application and
st.xml each of its components. For instance, it describes: certain qualities
about the activities, services, intent receivers, and content
providers; what permissions are requested; what external libraries
are needed; what device features are required, what API Levels
are supported or required; and others.
.gitignore/ Specifies the untracked files ignored by git.
app.iml/ IntelliJ IDEA module
build.gradle Customizable properties for the build system. You can edit this file
to override default build settings used by the manifest file and also
set the location of your keystore and key alias so that the build
tools can sign your application when building in release mode. This
file is integral to the project, so maintain it in a source revision
control system.
proguard- ProGuard settings file.
rules.pro
Table-6
62
2.5 Types of Modules
Dynamic feature module: Itdenotes a modularized feature of your app that can take
advantage of Google Play's Dynamic Delivery. For example, with dynamic feature
modules, you can provide your users with certain features of your app on-demand or
as instant experiences through Google Play Instant.
Library module: Itprovides a container for your reusable code, which you can use
as a dependency in other app modules or import into other projects. Structurally, a
library module is the same as an app module, but when built, it creates a code
archive file instead of an APK, so it can't be installed on a device.
In the Create New Module window, Android Studio offers the following library
modules:
• Android Library: This type of library can hold all file types supported in an
Android project, including source code, resources, and manifest files. The
build result is an Android Archive file or AAR file that can be added as a
dependency for your Android app modules.
63
• Java Library: This type of library can contain only Java source files. The build
result is a Java Archive or JAR file that can be added as a dependency for
your Android app modules or other Java projects.
Google Cloud module: it provides a container for your Google Cloud backend
code. It has the required code and dependencies for a Java App Engine backend
that uses HTTP, Cloud Endpoints, and Cloud Messaging to connect to your app. You
can develop your backend to provide cloud services need by your app.
To change various settings for your Android Studio project, open the project
structure dialog by clicking File Project Structure. It contains the following sections:
• SDK Location: Sets the location of the JDK, Android SDK, and Android NDK
that your project uses.
• Project: Sets the version for Gradle and the Android plugin for Gradle, and
the repository location name.
• Developer Services: Contains settings for Android Studio add-in components
from Google or other third parties. See Developer Services, below.
• Modules: Allows you to edit module-specific build configurations, including
the target and minimum SDK, the app signature, and library dependencies.
To Develop Android applications for mobile devices with resource constraint requires
a systematic understanding of the application lifecycle. Important terminology for
application building blocks terms are Context, Activity, and Intent. This section
introduces you with the most important components of Android applications and
64
provides you with a more detailed understanding of how Android applications
function and interact with one another.
• Intent: Intent is a messaging object which can be used to request an action from
another app component. Each request is packaged as Intent. You can think of
each such request as a message stating intent to do something. Intent mainly
used for three tasks 1) to start an activity, 2) to start a service and 3) to deliver a
broadcast.
Table-7
The core libraries provide all the functionality you need to start creating applications
for Android,but it won’t be long before you’re ready to delve into the advanced APIs
that offer the really excitingfunctionality.
66
Android hopes to target a wide range of mobile hardware, so be aware that the
suitability and implementationof the following APIs will vary depending on the device
upon which they are implemented.
API Package Use
android.location Contains the framework API classes that define Android
location-based and related services.
android.media Provides classes that manage various media interfaces in
audio and video.
android.opengl Provides an OpenGL ES static interface and utilities.
android.hardware Provides support for hardware features, such as the camera
and other sensors.
android.bluetooth Provides classes that manage Bluetooth functionality, such as
scanning for devices, connecting with devices, and managing
data transfer between devices. The Bluetooth API supports
both "Classic Bluetooth" and Bluetooth Low Energy.
android.net.wifi Provides classes to manage Wi-Fi functionality on the device.
android.telephony Provides APIs for monitoring the basic phone information, such
as the network type and connection state, plus utilities for
manipulating phone number strings.
Table-8
b) _____ Package provide classes that manage various media interfaces in audio
and video.
d) Application Program Interface is a set of routines, protocols, and tools for building
software applications (True/False)
In this unit you have lean about the structure of Android Project, various types of
Android Project files, Android application modules and understand anatomy of an
android application. You have also learnt about basic and advanced Application
Program Interface.
2.13Further Reading
• https://developer.android.com/studio/projects
2.14Assignment
• Explain Android Project Structure
• Write detailed note on basic and advanced API packages
• Define: Activity, Service, Context, Intent
68
Unit-3: Android Manifest File 3
and its common settings
Unit Structure
1.3 Introduction
1.7 Permissions
1.15 Assignment
1.16 Activities
69
3.0 Learning Objectives
3.1 Introduction
Each and every android app project must have an AndroidManifest.xml file in theroot
of your project. The manifest file describes important information about your app.
The manifest file declares the following:
Android Studio generally builds the manifest file for you when you create a project.
For a simple application with a single activity and nothing else, the auto-generated
manifest willwork fine with little or no modifications.
Android manifest file is global application description file which defines your
application’s capabilities and permissions and how it runs.This topic describes some
of the most important characteristics of your app which is stored in the manifest file.
70
3.3 Package name and application ID
The manifest file's root element requires an attribute for your app's package name,
For example, the following snippet shows the root <manifest> element with the
package name "in.edu.baou.databasedemo":
While building your app into the final APK, the Android build tools use the package
attribute for two things:
It applies this name as the namespace for your app's generated R.java class. With
the above manifest, the R class is created at in.edu.baou.databasedemo.R.
Android manifest file uses package this name to resolve any relative class names
that are declared in the manifest file.
You should keep in mind that once the APK is compiled, the package attribute also
represents your app's universally unique application ID.After the build tools perform
the above tasks based on the package name, they replace the package value with
the value given to the applicationId property in your project's build.gradle file.
71
3.4 App Components
For each app component that you create in your app, you must declare a
corresponding XML element in the manifest file so that the system can start it.
The name of your subclass must be specified with the name attribute, using the full
package designation,e.g. an Activity subclass can be declared as follows
<manifest package="in.edu.baou.databasedemo" ... >
<application ... >
<activity android:name=".SQLiteDBActivity" ... >
...
</activity>
</application>
</manifest>
When an app issues intent to the system, the system locates an app component that
can handle the intent based on intent filter declarations in each app's manifest file.
The system launches an instance of the matching component and passes the Intent
object to that component. If more than one app can handle the intent, then the user
can select which app to use.An intent filters is defined with the <intent-filter> element
as shown below.
72
<activity
android:name=".SQLiteDBActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
A number of manifest elements have icon and label attributes for displaying a small
icon and a text label, respectively, to users for the corresponding app component.
For example, the icon and label that are set in the <application> element are the
default icon and label for each of the app's components.
The icon and label that are set in a component's <intent-filter> are shown to the user
whenever that component is presented as an option to fulfill intent.
3.5 Permissions
Android apps must request permission to access personnel user data such as
contacts, SMS, camera, files, internet etc. Each permission is identified by a unique
label. For example, an app that needs to send and receive SMS messages must
have the following line in the manifest:
From API level 23, the user can approve or reject some app permissions at runtime.
You must declare all permission requests with a <uses-permission> element in the
manifest. If the permission is granted, the app is able to use the protected features. If
73
not, its attempts to access those features fail.A new permission is declared with the
<permission> element.
In manifest file is you can declare what types of hardware or software features your
app requires and types of devices with which your app is compatible. It can’t be
installed on devices that don't provide the features or system version that your app
requires.The following table shows the most common tags for specifying device
compatibility.
Tag Description
<uses-feature> It allows you to declare hardware and software features your app
needs
Example
<manifest ... >
<uses-feature
android:name="android.hardware.sensor.compass"
android:required="true" />
...
</manifest>
<uses-sdk> It indicates the minimum version with which your app is
compatibleelement are overridden by corresponding properties in
the build.gradle file.
<manifest>
<uses-sdkandroid:minSdkVersion="5" />
...
</manifest>
Table-9
Following are the conventions and rules that generally apply to all elements and
attributes in the manifest file.
74
• Only the <manifest> and <application> elements are required. They each must
occur only once, other elements can occur zero or more times.
• Elements at the same level are generally not ordered hence elements can be
placed in any order
• All attributes are optional but attributes must be specified so that an element can
serve its purpose. If attributes are not provided then it indicates the default value
• Except for some attributes of the root <manifest> element, all attribute names
begin with an android: prefix.
Element Description
<action> It is used to add an action to an intent filter.
<activity> It is used to declare an activity component.
<activity-alias> It is used to declare an alias for an activity.
<application> It is used to declare the application.
<category> It is used to add category name to an intent filter.
<compatible-screens> It is used to specifies each screen configuration with which
the application is compatible.
<data> Adds a data specification to an intent filter.
<grant-uri-permission> Specifies the subsets of app data that the parent content
provider has permission to access.
<instrumentation> Declares an Instrumentation class that enables you to
monitor an application's interaction with the system.
<intent-filter> Specifies the types of intents that an activity, service, or
broadcast receiver can respond to.
<manifest> The root element of the AndroidManifest.xml file.
<meta-data> A name-value pair for an item of additional, arbitrary data
that can be supplied to the parent component.
<path-permission> Defines the path and required permissions for a specific
subset of data within a content provider.
<permission> Declares a security permission that can be used to limit
access to specific components or features of this or other
applications.
75
<permission-group> Declares a name for a logical grouping of related
permissions.
<permission-tree> Declares the base name for a tree of permissions.
<provider> Declares a content provider component.
<receiver> Declares a broadcast receiver component.
<service> Declares a service component.
<supports-gl-texture> Declares a single GL texture compression format that the
app supports.
<supports-screens> Declares the screen sizes your app supports and enables
screen compatibility mode for screens larger than what
your app supports.
<uses-configuration> Indicates specific input features the application requires.
<uses-feature> Declares a single hardware or software feature that is used
by the application.
<uses-library> Specifies a shared library that the application must be
linked against.
<uses-permission> Specifies a system permission that the user must grant in
order for the app to operate correctly.
<uses-sdk> Lets you express an application's compatibility with one or
more versions of the Android platform, by means of an API
level integer.
Table-10
The XML below is a simple example AndroidManifest.xml that declares two activities
for the app.
77
3.10 Let us sum up
1-a) True
1-b) False
1-c) <permission>
1-d) (iv) All of these
1-e) (iii) Both (i) and (ii)
• https://developer.android.com/guide/topics/manifest/manifest-intro
• http://www.androiddocs.com/guide/topics/manifest/manifest-intro.html
• https://www.javatpoint.com/AndroidManifest-xml-file-in-android
78
3.13 Assignment
3.14 Activities
• Create Android Studio Project and study the default AndroidManifest.xml file
created for you and try to modified as per your requirement
79
Block-3
Android Application Design
Essentials
80
Unit-1: Activities 1
Unit Structure
2.2 Introduction
2.7 Context
2.12 Assignment
2.13 Activities
81
1.0 Learning Objectives
1.1 Introduction
To Develop Android applications for mobile devices with resource constraint requires
a systematic understanding of the application lifecycle. Important terminology for
application building blocks terms are Context, Activity, and Intent. This unit
introduces you with the most important components of Android applications and
provides you with a more detailed understanding of how Android applications
function and interact with one another.
The Activity class is a crucial component of an Android app, and the way activities
are launched and put together is a fundamental part of the platform's application
model. Unlike programming paradigms in which apps are launched with a main()
method, the Android system initiates code in an Activity instance by invoking specific
callback methods that correspond to specific stages of its lifecycle.
This document introduces the concept of activities, and then provides some
lightweight guidance about how to work with them. For additional information about
best practices in architecting your app, see Guide to App Architecture.
The mobile-app experience differs from its desktop counterpart in that a user's
interaction with the app doesn't always begin in the same place. Instead, the user
82
journey often begins non-deterministically. For instance, if you open an email app
from your home screen, you might see a list of emails. By contrast, if you are using a
social media app that then launches your email app, you might go directly to the
email app's screen for composing an email.
The Activity class is designed to facilitate this paradigm. When one app invokes
another, the calling app invokes an activity in the other app, rather than the app as
an atomic whole. In this way, the activity serves as the entry point for an app's
interaction with the user. You implement an activity as a subclass of the Activity
class.
An activity provides the window in which the app draws its UI. This window typically
fills the screen, but may be smaller than the screen and float on top of other
windows. Generally, one activity implements one screen in an app. For instance, one
of an app’s activities may implement a Preferences screen, while another activity
implements a Select Photo screen.
Most apps contain multiple screens, which means they comprise multiple activities.
Typically, one activity in an app is specified as the main activity, which is the first
screen to appear when the user launches the app. Each activity can then start
another activity in order to perform different actions. For example, the main activity in
a simple e-mail app may provide the screen that shows an e-mail inbox. From there,
the main activity might launch other activities that provide screens for tasks like
writing e-mails and opening individual e-mails.
Although activities work together to form a cohesive user experience in an app, each
activity is only loosely bound to the other activities; there are usually minimal
dependencies among the activities in an app. In fact, activities often start up
activities belonging to other apps. For example, a browser app might launch the
Share activity of a social-media app.
To use activities in your app, you must register information about them in the app’s
manifest, and you must manage activity lifecycles appropriately. The rest of this
document introduces these subjects.
83
1.3 Configuring the AndroidManifest.xml
For your app to be able to use activities, you must declare the activities, and certain
of their attributes, in the manifest.
Declare activities: To declare your activity, open your manifest file and add an
<activity> element as a child of the <application> element. For example:
The only required attribute for this element is android:name, which specifies the
class name of the activity. You can also add attributes that define activity
characteristics such as label, icon, or UI theme.
Declare intent filters:Intent filters are a very powerful feature of the Android
platform. They provide the ability to launch an activity based not only on an explicit
request, but also an implicit one. For example, an explicit request might tell the
system to “Start the Send Email activity in the Gmail app". By contrast, an implicit
request tells the system to “Start a Send Email screen in any activity that can do the
job." When the system UI asks a user which app to use in performing a task, that’s
an intent filter at work.
You can take advantage of this feature by declaring an <intent-filter> attribute in the
<activity> element. The definition of this element includes an <action> element and,
optionally, a <category> element and/or a <data> element. These elements combine
to specify the type of intent to which your activity can respond. For example, the
following code snippet shows how to configure an activity that sends text data, and
receives requests from other activities to do so:
84
<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
In this example, the <action> element specifies that this activity sends data.
Declaring the <category> element as DEFAULT enables the activity to receive
launch requests. The <data> element specifies the type of data that this activity can
send. The following code snippet shows how to call the activity described above
If you intend for your app to be self-contained and not allow other apps to activate its
activities, you don't need any other intent filters. Activities that you don't want to
make available to other applications should have no intent filters, and you can start
them yourself using explicit intents.
Declare permissions: You can use the manifest's <activity> tag to control which
apps can start a particular activity. A parent activity cannot launch a child activity
unless both activities have the same permissions in their manifest. If you declare
a <uses-permission> element for a particular activity, the calling activity must have a
matching<uses-permission> element.
85
For example, if your app wants to use a hypothetical app named SocialApp to share
a post on social media, SocialApp itself must define the permission that an app
calling it must have:
<manifest>
<activity android:name="...."
android:permission=”com.google.socialapp.permission.SHARE_POST”
/>
Then, to be allowed to call SocialApp, your app must match the permission set in
SocialApp's manifest:
<manifest>
<uses-permission android:name="com.google.socialapp.permission.SHARE_POST"
/>
</manifest>
Activity States
Table-11
Activity Events
The Activity base class defines a series of events that governs the life cycle of an
activity. The Activity class defines the following events:
Event Description
onCreate() Called when the activity is first created
onStart() Called when the activity becomes visible to the user
onResume() Called when the activity starts interacting with the user
onPause() Called when the current activity is being paused and the previous
activity is being resumed
87
onStop() Called when the activity is no longer visible to the user
onDestroy() Called before the activity is destroyed by the system
onRestart() Called when the activity has been stopped and is restarting again
Table-12
By default, the activity created for you contains the onCreate() event. Within this
event handler is the code that helps to display the UI elements of your screen.
88
1.5 Understanding Life Cycle of an Activity
The best way to understand the various stages experienced by an activity is to
create a new project, implement the various events, and then subject the activity to
various user interactions.
1. Create a New Android Studio Project as discussed in section 1.4 with project
name ActivityDemo and Main Activity name as MainActivity
2. In the MainActivity.java file, add the following statements in bold:
package in.edu.baou.activitydemo;
import android.util.Log;
3. Press Shift+F10 or ‘Run App’ button in taskbar. It will launch following dialog box.
Press OK.
Figure-46
4. When the activity is first loaded, you should see the following in the LogCat
window.
Figure-47
5. Now press the back button on the Android Emulator, observe that the following is
printed:
Figure-48
90
6. Click the Home button and hold it there. Click the ActivityDemo icon and observe
the following:
Figure-49
7. On Android Emulator from notification area open settings on so that the activity is
pushed to the background. Observe the output in the LogCat window:
Figure-50
8. Notice that the onDestroy() event is not called, indicating that the activity is still in
memory. Exit the settings by pressing the Back button. The activity is now visible
again. Observe the output in the LogCat window:
Figure-51
Please note that the onRestart() event is now fired, followed by the onStart() and
onResume() events.
91
This application uses logging feature of Android. To add logging support to
ActivityDemo app, edit the file MainActivity.java to add the following import statement
for the Log class:
import android.util.Log;
Logging is a valuable resource for debugging and learning Android. Android logging
features are in the Log class of the android.util package. Some helpful methods in
the android.util.Log class are shown in Table. We have used Log.d() method to print
message in LogCat Window when particular event of activity fired.
Method Purpose
Log.e() Log errors
Log.w() Log warnings
Log.i() Log information messages
Log.d() Log debug messages
Log.v() Log verbose messages
Table-13
1.6 Context
As the name suggests, it is the context of current state of the application/object. It
lets newly created objects understand what has been going on. Typically you call it
to get information regarding other part of your program (activity,
package/application). The application Context is the central location for all top-level
application functionality. The Context class can be used to manage application-
specific configuration details as well as application-wide operations and data. Use
the application Context to access settings and resources shared across multiple
Activity instances.
92
Uses of the Application Context
After you have retrieved a valid application Context, it can be used to access
application-wide features and services. Typical uses of context are:
1) Creating new views, adapters, listeners object
93
1.7 Activity Transition
In the course of the lifetime of an Android application, the user might transition
betweena numbers of different Activity instances. At times, there might be multiple
Activity instanceson the activity stack. Developers need to pay attention to the
lifecycle of eachActivity during these transitions.
Launching a New Activity by Class Name: You can start activities in several
ways.The simplest method is to use the Application Context object to call the
startActivity() method, which takes a single parameter, an Intent.
94
Intent.ThisIntent requests the launch of the target Activity named MyDrawActivity by
its class.This class is implemented elsewhere within the package.
startActivity(new Intent(getApplicationContext(),
MyDrawActivity.class));
This line of code might be sufficient for some applications, which simply transition
fromone Activity to the next. However, you can use the Intent mechanism in a much
morerobust manner. For example, you can use the Intent structure to pass data
betweenActivities.
Creating Intents with Action and Data: You’ve seen the simplest case to use
Intent to launch a class by name. Intents need notspecify the component or class
they want to launch explicitly. Instead, you can create anIntent Filter and register it
within the Android Manifest file.The Android operating systemattempts to resolve the
Intent requirements and launch the appropriate Activitybased on the filter criteria.
The guts of the Intent object are composed of two main parts: the action to be
performedand the data to be acted upon.You can also specify action/data pairs using
IntentAction types and Uri objects. An Uri object represents a string that gives the
location and name of an object.Therefore, an Intent is basically saying “do this” (the
action) to “that” (the Uri describingwhat resource to do the action to).The most
common action types are defined in the Intent class, includingACTION_MAIN
(describes the main entry point of an Activity) and ACTION_EDIT (used
inconjunction with a Uri to the data edited).You also find Action types that generate
integrationpoints with Activities in other applications, such as the Browser or Phone
Dialer.
However, with the appropriate permissions, applications might also launch external
Activitieswithin other applications. For example, a Customer Relationship
Management(CRM) application might launch the Contacts application to browse the
Contact database,choose a specific contact, and return that Contact’s unique
identifier to the CRMapplication for use.
95
Here is an example of how to create a simple Intent with a predefined
Action(ACTION_DIAL) to launch the Phone Dialer with a specific phone number to
dial in theform of a simple Uri object:
b) You can use the ___________to access settings and resources shared across
multiple Activity instances.
96
In this unit you have learn all about android activity, important terminology. You have
understand the life cycle of an activity through practical example and you have also
lean about how to onfigure activity in AndroidManifest.xml file at the end of unit we
have discuss activity transition.
1.11 Assignment
• What is activity? Explain activity life cycle
• Explain activity transition
• Write short note on activity state and activity events
1.12 Activity
• Write android activity using logging feature to demonstrate activity life cycle
97
Unit-2: Services 2
Unit Structure
2.1 Introduction
2.10 Assignment
2.11 Activities
98
2.0 Learning Objectives
2.1 Introduction
You can use services for different purposes. Generally, you use a service when no
input is required from the user. Here are some circumstances in which you might
want to implement or use an Android service:
99
• A photo or media app that keeps its data in sync online might implement a
service to package and upload new content in the background when the device is
idle.
• A video-editing app might offload heavy processing to a queue on its service in
order to avoid affecting overall system performance for non-essential tasks.
• A news application might implement a service to “pre-load” content by
downloading news stories in advance of when the user launches the application,
to improve performance.
To create service you must defined a class that extends the Service base class.
Inside your service class, you have to implement four methods discussed below:
Method Description
onStartCommand() • The system calls this method when another component,
such as an activity, requests that the service be started, by
calling startService().
• Once this method executes, the service is started and can
run in the background indefinitely.
• It is your responsibility to stop the service when its work is
done, by calling stopSelf() or stopService().
• If you only want to provide binding, you don't need to
implement this method.
onBind() • The system calls this method when another component
wants to bind with the service by calling bindService().
• In your implementation of this method, you must provide
an interface that clients use to communicate with the
service, by returning an IBinder.
• If you don't want to allow binding, then you should return
null.
onCreate() • The system calls this method when the service is first
created, to perform one-time setup procedures before it
100
Method Description
calls either onStartCommand() or onBind().
• If the service is already running, this method is not called.
onDestroy() • The system calls this method when the service is no longer
used and is being destroyed.
• This method should be implemented to clean up any
resources such as threads, registered listeners, receivers,
etc.
• This is the last call the service receives.
Table-14
You can use Intents and Activities to launch services using the startService() and
bindService() methods. A service can essentially take two forms. The difference
between two is as follows:
startService() bindService()
A service is "started" when an application A service is "bound" when an application
component starts it by calling component binds to it by calling
startService() bindService()
Once started, a service can run in the A bound service runs only as long as
background indefinitely, even if the another application component is bound
component that started it is destroyed to it. Multiple components can bind to the
service.
Usually, a started service performs a A bound service offers a client-server
single operation and does not return a interface that allows components to
result to the caller. For example, it might interact with the service, send requests,
download or upload a file over the get results, and even do so across
network. When the operation is done, the processes with inter process
service should stop itself communication (IPC)
Table-15
101
2.5 Service Life Cycle
Like an activity, a service has lifecycle callback methods that you can implement to
monitor changes in the service's state and perform work at the appropriate times as
discussed above. Below Figure illustrates the typical callback methods for a service
for that are created by startService() and from those created by bindService.
Figure-52
We will create service to logs counter which starts from 1 and incremented by one at
interval of one second. To do so perform following steps:
1. Create a New Android Studio Project with project name ServiceDemo and Main
Activity name as ServiceActivity
2. Add new service by right click on package and select New Service Service
and click.
102
Figure-53
3. In dialog box, Enter class name as TimerService as shown in figure and press
finish Button.
Figure-54
package in.edu.baou.servicesdemo;
import android.util.Log;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
103
public class TimerService extends Service {
int counter = 0;
Timer timer = new Timer();
public TimerService() {
}
@Override
public IBinderonBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started!", Toast.LENGTH_LONG).show();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.d("MyService", String.valueOf(++counter));
}
}, 0, 1000);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (timer != null){
timer.cancel();
}
Toast.makeText(this, "Service Destroyed!", Toast.LENGTH_LONG).show();
}
}
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".ServiceActivity">
<TextViewandroid:text="Service Demonstration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView" />
<Button
android:layout_width="match_parent"
104
android:layout_height="wrap_content"
android:text="Start Timer Service"
android:id="@+id/btnStartTimer"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/textView" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Timer Service"
android:id="@+id/btnStopTimer"
android:layout_below="@+id/btnStartTimer"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
package in.edu.baou.servicesdemo;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class ServiceActivity extends ActionBarActivity {
Button startTimer,stopTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
startTimer = (Button)findViewById(R.id.btnStartTimer);
stopTimer = (Button)findViewById(R.id.btnStopTimer);
startTimer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), TimerService.class));
}
});
stopTimer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), TimerService.class));
}
105
});
}
7. Press Shift+F10 or ‘Run App’ button in taskbar. It will launch following dialog box.
Press OK.
Figure-55
8. It will open activity in emulator as shown below. Clicking the START TIMER
SERVICE button will start the service as shown below. To stop the service, click
the STOP TIMER SERVICE.
Figure-56
106
9. Once service is started, you can see counter value incremented by in LogCat
window
Figure-57
Explanation
Inside project layout file we created two buttons to start and stop service with ID
btnStartTimer and btnStopTimer..
Inside ServiceActivity we define two button objects that represents button in
layout file.
The findViewByID() method is used to take reference of button.
Button clicked event is handled by onClick() method of OnClickListener
associated to button using setOnClickListener().
Inside TimerService class we define counter variable which initialized to zero at
the start of service and increment by one every one second using Timer class
scheduledAtFixedRate() Method.
The value of counter is logs inside LogCat window using Log.d() Method with tag
“MyService”.
Toast is temporary message displayed on screen such as “Service Started” in
step-8 and is displayed using makeText method of Toast class.
107
e) Generally, you use a service when to interact with the user.
f) Any Services exposed by an Android application must be registered in the
Android Manifest file.
2.10 Assignment
2.11 Activity
108
Unit-3: Intent 3
Unit Structure
4.1 Introduction
4.13 Assignment
4.14 Activity
109
3.0 Learning Objective
3.1 Introduction
Intent provides a facility for performing late runtime binding between the codes in
different applications. Its most significant use is in the launching of activities, where it
can be thought of as the glue between activities. It is basically a passive data
structure holding an abstract description of an action to be performed.
Primary Attributes
expressed as an Uri.
110
Some examples of action/data pairs are:
filled in.
• ACTION_VIEW tel:123 : Display the phone dialer with the given number filled in. Note
how the VIEW action does what is considered the most reasonable thing for a
particular URI.
• ACTION_DIAL tel:123 : Display the phone dialer with the given number filled in.
identifier is "9".
• ACTION_VIEW content://contacts/people/ : Display a list of people, which the user
can browse through. This example is a typical top-level entry into the Contacts
application, showing you the list of people. Selecting a particular person to view
would result in a new intent {ACTION_VIEWcontent://contacts/people/N } being used
to start an activity to display that person.
Secondary Attributes
111
component is used exactly as is. By specifying this attribute, all of the other Intent
attributes become optional.
• Extras: This is a Bundle of any additional information. This can be used to provide
extended information to the component. For example, if we have a action to send an
e-mail message, we could also include extra pieces of data here to supply a subject,
body, etc.
Here are some examples of other operations you can specify as intents using these
additional parameters:
• ACTION_MAIN with category CATEGORY_HOME: Launch the home screen.
• ACTION_GET_CONTENT with MIME type vnd.android.cursor.item/phone:
Display the list of people's phone numbers, allowing the user to browse through
them and pick one and return it to the parent activity.
• ACTION_GET_CONTENT with MIME type */* and category
CATEGORY_OPENABLE: Display all pickers for data that can be opened and
allowing the user to pick one of them and then some data inside of it and
returning the resulting URI to the caller. This can be used, for example, in an e-
mail application to allow the user to pick some data to include as an attachment.
There are a variety of standard Intent action and category constants defined in the
Intent class, but applications can also define their own, for example, the standard
ACTION_VIEW is called "android.intent.action.VIEW".
• Explicit Intents have specified a component which provides the exact class to be
run. Often these will not include any other information, simply being a way for an
application to launch various internal activities it has as the user interacts with the
application.
112
• Implicit Intents have not specified a component; instead, they must include enough
information for the system to determine which of the available components is best to
run for that intent.
When using implicit intents, given such an arbitrary intent we need to know what to
do with it. This is handled by the process of Intent resolution, which maps an Intent
to an Activity, BroadcastReceiver, or Service that can handle it.
The intent resolution mechanism basically revolves around matching Intent against
all of the <intent-filter> descriptions in the installed application packages.
There are three pieces of information in the Intent that are used for resolution: the
action, type, and category. Using this information, a query is done on the
PackageManager for a component that can handle the intent. The appropriate
component is determined based on the intent information supplied in the
AndroidManifest.xml file as follows:
113
3.6 Example of Intent
For example, consider the Note Pad sample application that allows a user to browse
through a list of notes data and view details about individual items.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.edu.baou.notepad">
<application android:icon="@drawable/app_notes"android:label="@string/app_name">
<provider class=".NotePadProvider"android:authorities="in.edu.baou.provider.NotePad" />
114
</intent-filter>
</activity>
<activity class=".TitleEditor" android:label="@string/title_edit_title"
android:theme="@android:style/Theme.Dialog">
<intent-filter android:label="@string/resolve_title">
<action android:name="com.android.notepad.action.EDIT_TITLE" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.ALTERNATIVE" />
<category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
<data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
</intent-filter>
</activity>
</application>
</manifest>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
This provides a top-level entry into the NotePad application: the standard MAIN
action is a main entry point (not requiring any other information in the Intent), and the
LAUNCHER category says that this entry point should be listed in the application
launcher.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.EDIT" />
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
</intent-filter>
115
This declares the things that the activity can do on a directory of notes. The type
being supported is given with the <type> tag,
where vnd.android.cursor.dir/vnd.google.note is a URI from which a Cursor of zero
or more items (vnd.android.cursor.dir) can be retrieved which holds our note pad
data (vnd.google.note). The activity allows the user to view or edit the directory of
data (via the VIEW and EDIT actions), or to pick a particular note and return it to the
caller (via the PICK action). Note also the DEFAULT category supplied here: this
is required for the startActivity method to resolve your activity when its component
name is not explicitly specified.
<intent-filter>
<action android:name="android.intent.action.GET_CONTENT" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
</intent-filter>
This filter describes the ability to return to the caller a note selected by the user
without needing to know where it came from. The data
type vnd.android.cursor.item/vnd.google.note is a URI from which a Cursor of exactly
one (vnd.android.cursor.item) item can be retrieved which contains our note pad
data (vnd.google.note). The GET_CONTENT action is similar to the PICK action,
where the activity will return to its caller a piece of data selected by the user. Here,
however, the caller specifies the type of data they desire instead of the type of data
the user will be picking from.
Given these capabilities, the following intents will resolve to the NotesList activity:
116
• { action=android.app.action.PICK
data=content://com.google.provider.NotePad/notes } provides a list of the notes
under "content://com.google.provider.NotePad/notes", from which the user can pick
a note whose data URL is returned back to the caller.
• { action=android.app.action.GET_CONTENT
type=vnd.android.cursor.item/vnd.google.note } is similar to the pick action, but
allows the caller to specify the kind of data they want back so that the system can
find the appropriate activity to pick something of that data type.
• The second activity, in.edu.baou.notepad.NoteEditor, shows the user a single note
entry and allows them to edit it. It can do two things as described by its two intent
templates:
<intent-filter android:label="@string/resolve_edit">
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.EDIT" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
</intent-filter>
The first, primary, purpose of this activity is to let the user interact with a single note,
as described by the MIME type vnd.android.cursor.item/vnd.google.note. The activity
can either VIEW a note or allow the user to EDIT it. Again we support the DEFAULT
category to allow the activity to be launched without explicitly specifying its
component.
<intent-filter>
<action android:name="android.intent.action.INSERT" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
</intent-filter>
The secondary use of this activity is to insert a new note entry into an existing
directory of notes. This is used when the user creates a new note: the INSERT
action is executed on the directory of notes, causing this activity to run and have the
user create the new note data which it then adds to the content provider.
Given these capabilities, the following intents will resolve to the NoteEditor activity:
117
• {action=android.intent.action.VIEW
data=content://in.edu.baou.provider.NotePad/notes/{ID}} shows the user the
content of note {ID}.
• { action=android.app.action.EDIT
data=content://in.edu.baou.provider.NotePad/notes/{ID} } allows the user to edit
the content of note {ID}.
• { action=android.app.action.INSERT
data=content://in.edu.baou.provider.NotePad/notes } creates a new, empty note
in the notes list at "content://com.google.provider.NotePad/notes" and allows the
user to edit it. If they keep their changes, the URI of the newly created note is
returned to the caller.
• The last activity, com.android.notepad.TitleEditor, allows the user to edit the title of a
note. This could be implemented as a class that the application directly invokes (by
explicitly setting its component in the Intent), but here we show a way you can
publish alternative operations on existing data:
<intent-filter android:label="@string/resolve_title">
<action android:name="com.android.notepad.action.EDIT_TITLE" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.ALTERNATIVE" />
<category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
<data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
</intent-filter>
• In the single intent template here, we have created our own private action
calledcom.android.notepad.action.EDIT_TITLE which means to edit the title of a
note. It must be invoked on a specific note like the previous view and edit actions,
but here displays and edits the title contained in the note data.
• In addition to supporting the default category as usual, our title editor also supports
two other standard categories: ALTERNATIVE and SELECTED_ALTERNATIVE.
Implementing these categories allows others to find the special action it provides
without directly knowing about it, through the
PackageManager.queryIntentActivityOptions(ComponentName, Intent[], Intent,
int) method, or more often to build dynamic menu items
with Menu.addIntentOptions(int, int, int, ComponentName, Intent[], Intent, int,
118
MenuItem[]). Note that in the intent template here was also supply an explicit name
for the template (via android:label="@string/resolve_title") to better control what the
user sees when presented with this activity as an alternative action to the data they
are viewing.
• Given these capabilities, the following intent will resolve to the TitleEditor activity:
• {action=com.android.notepad.action.EDIT_TITLE
data=content://com.google.provider.NotePad/notes/{ID}} displays and allows the
user to edit the title associated with note {ID}.
These are the current standard actions that Intent defines for launching activities
(usually through Context#startActivity. The most important, and by far most
frequently used, are ACTION_MAIN and ACTION_EDIT.
These are the current standard actions that Intent defines for receiving broadcasts
(usually through registerReceiver or a <receiver> tag in a manifest).
ACTION_TIME_TICK ACTION_PACKAGE_DATA_CLEARED
ACTION_TIME_CHANGED ACTION_PACKAGES_SUSPENDED
ACTION_TIMEZONE_CHANGED ACTION_PACKAGES_UNSUSPENDED
ACTION_BOOT_COMPLETED ACTION_UID_REMOVED
ACTION_PACKAGE_ADDED ACTION_BATTERY_CHANGED
ACTION_PACKAGE_CHANGED ACTION_POWER_CONNECTED
ACTION_PACKAGE_REMOVED ACTION_POWER_DISCONNECTED
ACTION_PACKAGE_RESTARTED ACTION_SHUTDOWN
119
Check your progress-1
• Intent provides a facility for performing late runtime binding between the codes
in similar applications. (True/False)
• Which of the following is a type of intent
(A) Primary (B) Secondary (C) Both (A) and (B) (D) Neither (A) nor (B)
• Which of the following pieces of information is used for intent resolution?
(A) Action (B) Type (C) Category (D) All of these
• The intent has secondary attributes which are optional
• Which of the following is standard activity action?
(A) ACTION_MAIN (B) ACTION_VIEW (C) ACTION_EDIT (D) All of these
• Intent is an abstract description of an operation to be performed
In this unit we have learned about the structure of Intent, what type of operation can
be performed on Intent, types of Intent, Intent Resolution, take example of Intent,
discussed standard Activity actions and standard broadcast actions.
1-a) False1-b) (C) Both (A) and (B)1-c) (D) All of these
• https://developer.android.com/reference/android/content/Intent
3.13 Assignment
120
Unit-4: Permissions 4
Unit Structure
4.1 Introduction
4.11 Assignment
4.12 Activity
121
4.0 Learning Objectives
After studying this unit, students will be able to:
• Define permission
4.1 Introduction
The purpose of a permission is to protect the privacy of an Android user. Android
apps must request permission to access sensitive user data (such as contacts and
SMS), as well as certain system features (such as camera and internet). Depending
on the feature, the system might grant the permission automatically or might prompt
the user to approve the request.
A central design point of the Android security architecture is that no app, by default,
has permission to perform any operations that would adversely impact other apps,
the operating system, or the user. This includes reading or writing the user's private
data (such as contacts or emails), reading or writing another app's files, performing
network access, keeping the device awake, and so on.
This unit provides an overview of how Android permissions work, including: how
permissions are presented to the user, the difference between install-time and
runtime permission requests, how permissions are enforced, and the types of
permissions and their groups.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">
<uses-permission android:name="android.permission.SEND_SMS"/>
122
<application ...>
...
</application>
</manifest>
If your app lists normal permissions in its manifest (that is, permissions that don't
pose much risk to the user's privacy or the device's operation), the system
automatically grants those permissions to your app.
If your app lists dangerous permissions in its manifest (that is, permissions that could
potentially affect the user's privacy or the device's normal operation), such as the
SEND_SMS permission above, the user must explicitly agree to grant those
permissions.
If the device is running Android 6.0 (API level 23) or higher, and the app's
targetSdkVersion is 23 or higher, the user isn't notified of any app permissions at
install time. Your app must ask the user to grant the dangerous permissions at
runtime. When your app requests permission, the user sees a system dialog as
shown in figure 1 telling the user which permission group your app is trying to
access. The dialog includes a Deny and Allow button.
If the user denies the permission request, the next time your app requests the
permission, the dialog contains a checkbox that, when checked, indicates the user
doesn't want to be prompted for the permission again as shown in figure 2.
123
Figure-58
If the user checks the Never ask again box and taps Deny, the system no longer
prompts the user if you later attempt to requests the same permission.
Even if the user grants your app the permission it requested you cannot always rely
on having it. Users also have the option to enable and disable permissions one-by-
one in system settings. You should always check for and request permissions at
runtime to guard against runtime errors (SecurityException).
If the device is running Android 5.1.1 (API level 22) or lower, or the app's
targetSdkVersion is 22 or lower while running on any version of Android, the system
automatically asks the user to grant all dangerous permissions for your app at install-
time as shown in figure 2.
124
Figure-59
If the user clicks Accept, all permissions the app requests are granted. If the user
denies the permissions request, the system cancels the installation of the app.
If an app update includes the need for additional permissions the user is prompted to
accept those new permissions before updating the app.
If you declare android:required="false" for the feature, then Google Play allows your
app to be installed on devices that don't have the feature. You then must check if the
current device has the feature at runtime by calling
125
PackageManager.hasSystemFeature(), and gracefully disable that feature if it's not
available.
If you don't provide the <uses-feature> tag, then when Google Play sees that your
app requests the corresponding permission, it assumes your app requires this
feature. So it filters your app from devices without the feature, as if you declared
android:required="true" in the <uses-feature> tag.
Permissions applied using the android:permission attribute to the <activity> tag in the
manifest restrict who can start that Activity. The permission is checked during
Context.startActivity() and Activity.startActivityForResult(). If the caller doesn't have
the required permission then SecurityException is thrown from the call.
126
In the same way, a permission can be supplied to Context.registerReceiver() to
control who can broadcast to a programmatically registered receiver. Going the other
way, a permission can be supplied when calling Context.sendBroadcast() to restrict
which broadcast receivers are allowed to receive the broadcast.
Note that both a receiver and a broadcaster can require permission. When this
happens, both permission checks must pass for the intent to be delivered to the
associated target.
The permissions are checked when you first retrieve a provider and as you perform
operations on the provider.
URI permissions
The standard permission system described so far is often not sufficient when used
with content providers. A content provider may want to protect itself with read and
write permissions, while its direct clients also need to hand specific URIs to other
apps for them to operate on.
127
A typical example is attachments in a email app. Access to the emails should be
protected by permissions, since this is sensitive user data. However, if a URI to an
image attachment is given to an image viewer, that image viewer no longer has
permission to open the attachment since it has no reason to hold a permission to
access all email.
To build the most secure implementation that makes other apps accountable for their
actions within yor app, you should use fine-grained permissions in this manner and
declare your app's support for it with the android:grantUriPermissions attribute or
<grant-uri-permissions> tag.
Arbitrarily fine-grained permissions can be enforced at any call into a service. This is
accomplished with the Context.checkCallingPermission() method. Call with a desired
permission string and it returns an integer indicating whether that permission has
been granted to the current calling process. Note that this can only be used when
you are executing a call coming in from another process, usually through an IDL
interface published from a service or in some other way given to another process.
There are a number of other useful ways to check permissions. If you have the
process ID (PID) of another process, you can use the Context.checkPermission()
method to check a permission against that PID. If you have the package name of
128
another app, you can use the PackageManager.checkPermission() method to find
out whether that particular package has been granted a specific permission.
d) In mobile with Android 6.0 and higher, the request for permission is requested to
user at __________
(A) Runtime (B) Install-time (C) Either (A) or (B) (D) Neither (A) nor (B)
e) Services provided by apps can enforce custom permissions to restrict who can
use them.
There are three protection levels that affect third-party apps: normal, signature, and
dangerous permissions.
Normal permissions
Normal permissions cover areas where your app needs to access data or resources
outside the app's sandbox, but where there's very little risk to the user's privacy or
the operation of other apps. For example, permission to set the time zone is a
normal permission.
129
If an app declares in its manifest that it needs a normal permission, the system
automatically grants the app that permission at install time. The system doesn't
prompt the user to grant normal permissions, and users cannot revoke these
permissions.
ACCESS_LOCATION_EXTRA_COMMANDS MANAGE_OWN_CALLS
ACCESS_NETWORK_STATE MODIFY_AUDIO_SETTINGS
ACCESS_NOTIFICATION_POLICY NFC
ACCESS_WIFI_STATE READ_SYNC_SETTINGS
BLUETOOTH READ_SYNC_STATS
BLUETOOTH_ADMIN RECEIVE_BOOT_COMPLETED
BROADCAST_STICKY REORDER_TASKS
CHANGE_NETWORK_STATE REQUEST_DELETE_PACKAGES
CHANGE_WIFI_MULTICAST_STATE SET_ALARM
CHANGE_WIFI_STATE SET_WALLPAPER
DISABLE_KEYGUARD SET_WALLPAPER_HINTS
EXPAND_STATUS_BAR TRANSMIT_IR
FOREGROUND_SERVICE USE_FINGERPRINT
GET_PACKAGE_SIZE VIBRATE
INSTALL_SHORTCUT WAKE_LOCK
INTERNET WRITE_SYNC_SETTINGS
KILL_BACKGROUND_PROCESSES
Signature permissions
The system grants these app permissions at install time, but only when the app that
attempts to use permission is signed by the same certificate as the app that defines
the permission.
As of Android 8.1 (API level 27), the following permissions that third-party apps can
use are classified as PROTECTION_SIGNATURE:
130
BIND_ACCESSIBILITY_SERVICE
BIND_AUTOFILL_SERVICE
BIND_CARRIER_SERVICES
BIND_CHOOSER_TARGET_SERVICE
BIND_CONDITION_PROVIDER_SERVICE
BIND_DEVICE_ADMIN
BIND_DREAM_SERVICE
BIND_INCALL_SERVICE
BIND_INPUT_METHOD
BIND_MIDI_DEVICE_SERVICE
BIND_NFC_SERVICE
BIND_NOTIFICATION_LISTENER_SERVICE
BIND_PRINT_SERVICE
BIND_SCREENING_SERVICE
BIND_TELECOM_CONNECTION_SERVICE
BIND_TEXT_SERVICE
BIND_TV_INPUT
BIND_VISUAL_VOICEMAIL_SERVICE
BIND_VOICE_INTERACTION
BIND_VPN_SERVICE
BIND_VR_LISTENER_SERVICE
BIND_WALLPAPER
CLEAR_APP_CACHE
MANAGE_DOCUMENTS
READ_VOICEMAIL
REQUEST_INSTALL_PACKAGES
SYSTEM_ALERT_WINDOW
WRITE_SETTINGS
WRITE_VOICEM
Dangerous permissions
Dangerous permissions cover areas where the app wants data or resources that
involve the user's private information, or could potentially affect the user's stored
data or the operation of other apps. For example, the ability to read the user's
contacts is a dangerous permission. If an app declares that it needs a dangerous
permission, the user has to explicitly grant the permission to the app. Until the user
131
approves the permission, your app cannot provide functionality that depends on that
permission.
To use a dangerous permission, your app must prompt the user to grant permission
at runtime. For a list of dangerous permissions, see table 16 below.
Special permissions
There are a couple of permissions that don't behave like normal and dangerous
permissions. SYSTEM_ALERT_WINDOW and WRITE_SETTINGS are particularly
sensitive, so most apps should not use them. If an app needs one of these
permissions, it must declare the permission in the manifest, and send an intent
requesting the user's authorization. The system responds to the intent by showing a
detailed management screen to the user.
132
4.7 How to View app's permissions
You can view all the permissions currently defined in the system using the Settings
app and the shell command adb shell pm list permissions. To use the Settings app,
go to Settings > Apps. Pick an app and scroll down to see the permissions that the
app uses. For developers, the adb '-s' option displays the permissions in a form
similar to how the user sees them:
All Permissions:
Your location: access extra location provider commands, fine (GPS) location,mock
location sources for testing, coarse (network-based) location
Services that cost you money: send SMS messages, directly call phone numbers
...
You can also use the adb -g option to grant all permissions automatically when
installing an app on an emulator or test device:
133
(A) Normal (B) Signature (C) Dangerous (D) All of these
1-b) False
1-c) <uses-permission>
1-e) True
134
4.11 Assignment
4.12 Activity
• Check the permissions used by different Apps installed in your Android Mobile
and remove any unnecessary permission granted.
135
Unit-5: Application Resources 5
Unit Structure
5.1 Introduction
5.11 Assignment
5.12 Activity
136
5.0 Learning Objectives
5.1 Introduction
Resources are the additional files and static content that your code uses, such as
bitmaps, layout definitions, user interface strings, animation instructions, and more.
You should always externalize app resources such as images and strings from your
code, so that you can maintain them independently. You should also provide
alternative resources for specific device configurations, by grouping them in
specially-named resource directories. At runtime, Android uses the appropriate
resource based on the current configuration. For example, you might want to provide
a different UI layout depending on the screen size or different strings depending on
the language setting.
Once you externalize your app resources, you can access them using resource IDs
that are generated in your project's R class. This document shows you how to group
your resources in your Android project and provide alternative resources for specific
device configurations, and then access them from your app code or other XML files.
The well-written application accesses its resources programmatically instead of hard
coding them into the source code.This is done for a variety of reasons. Storing
applicationresources in a single place is a more organized approach to development
and makesthe code more readable and maintainable. Externalizing resources such
as strings makes iteasier to localize applications for different languages and
geographic regions.
137
5.2 What are resources?
All Android applications are composed of two things: functionality (code instructions)
anddata (resources).The functionality is the code that determines how your
application behaves.This includes any algorithms that make the application run.
Resources include textstrings, images and icons, audio files, videos, and other data
used by the application.Android resource files are stored separately from the java
class files in the Android project.Most common resource types are stored in
XML.You can also store raw data files
Resources are organized in a strict directory hierarchy within the Android project. All
resourcesmust be stored under the /res project directory in specially named
subdirectoriesthat must be lowercase.Different resource types are stored in different
directories.The resource sub-directoriesgenerated when you create an Android
project are shown in below.
138
Each resource type corresponds to a specific resource subdirectory name. For
example, all graphics are stored under the /res/drawable directory structure.
Resources can be furtherorganized in a variety of ways using even more specially
named directory qualifiers.
These resources are stored in the /res directory of your Android project in a strict
(butreasonably flexible) set of directories and files.All resources filenames must be
lowercaseand simple (letters, numbers, and underscores only).
The resource types supported by the Android SDK and how they are stored within
theproject are shown in table below
139
Resource Type Directory Filename XML Tag
Arrays ofIntegers /res/values/ integers.xml <integer-array>,<item>
Mixed-TypeArrays /res/values/ Arrays.xml <array>, <item>
SimpleDrawables /res/values/ drawables.xml <drawable>
Graphics /res/drawable/ Examples include Supported graphics
icon.png logo.jpg files
or drawable definition
XML files such
asshapes.
TweenedAnimations /res/anim/ Examples include <set>, <alpha>,
fadesequence.xml <scale>, <translate>,
spinsequence.xml <rotate>
Frame-by-Frame /res/drawable/ Examples include <animation-list>,
Animations sequence1.xml <item>
sequence2.xml
Menus /res/menu/ Examples include <menu>
mainmenu.xml
helpmenu.xml
XML Files /res/xml/ Examples include Defined by the
data.xml developer
data2.xml
Raw Files /res/raw/ Examples include Defined by the
jingle.mp3 developer
somevideo.mp4
helptext.txt
Layouts /res/layout/ Examples include Varies. Must be a
main.xml layoutcontrol.
help.xml
Styles andThemes /res/values/ styles.xml <style>
themes.xml
Table-17
140
5.5 Storing Different Resource Value Types
Simple resource value types, such as strings, colors, dimensions, and other
primitives, arestored under the /res/values project directory in XML files. Each
resource file underthe /res/values directory should begin with the following XML
header:
Next comes the root node <resources> followed by the specific resource element
typessuch as <string> or <color>. Each resource is defined using a different element
name.Although the XML file names are arbitrary, the best practice is to store your
resourcesin separate files to reflect their types, such as strings.xml, colors.xml, and
so on. However,there’s nothing stopping the developers from creating multiple
resource files for agiven type, such as two separate xml files called bright_colors.xml
andmuted_colors.xml, if they so choose.
In addition to simple resource types stored in the /res/values directory, you can
alsostore numerous other types of resources, such as animation sequences,
graphics, arbitraryXML files, and raw files.These types of resources are not stored in
the /res/values directory,but instead stored in specially named directories according
to their type. For example,you can include animation sequence definitions in the
/res/anim directory. Makesure you name resource files appropriately because the
resource name is derived from thefilename of the specific resource. For example, a
file called flag.png in the/res/drawable directory is given the name R.drawable.flag.
141
class to access that resource using sub-directory and resource name or directly
resource ID.
During your application development you will need to access defined resources
either in your code, or in your layout XML files. Following section explains how to
access your resources in both the scenarios.
Here first line of the code make use of R.id.myimageview to get ImageView defined
with id myimageview in a Layout file. Second line of code makes use of
R.drawable.myimage to get an image with name myimage available in drawable sub-
directory under /res.
Now you can set the text on a TextView object with ID msg using a resource ID as
follows:
TextViewmsgTextView = (TextView) findViewById(R.id.msg);
msgTextView.setText(R.string.hello);
<TextViewandroid:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
This application code will load this layout for an Activity, in the onCreate() method as
follows:
Consider the following resource XML res/values/strings.xml file that includes a color
resource and a string resource:
You can access system resources in addition to your own resources.The android
packagecontains all kinds of resources, which you can browse by looking in the
android.R subclasses.Here you find system resources for
You can reference system resources the same way you use your own; set the
package nameto android. For example, to set the background to the system color for
darker gray, youset the appropriate background color attribute to
@android:color/darker_gray.
You can access system resources much like you access your application’s
resources. Insteadof using your application resources, use the Android package’s
resources under theandroid.R class.
144
Check your progress-1
(A) Functionality (B) Data (C) Both A and B (D) Neither A nor B
b) You should always externalize app resources from your code, so that you can
maintain them independently (True/False)
c) You can use R class to access that resource using sub-directory and resource
name or directly resource ID. (True/False)
d) You cannot store resources, such as animation sequences, graphics, arbitrary
XML files, and raw files. (True/False)
e) All resources filenames must be in uppercase and simple (True/False)
f) Different resource types are stored in different directories (True/False)
g) You can access system resources much like you access your application’s
resources. (True/False)
Resources are compiled and accessed using the R.java class file, which is
automaticallygenerated when the application resources are compiled. Developers
access applicationand system resources programmatically using this special class.
145
5.9 Check your Progress: Possible Answers
1-g) True
5.10Further Reading
• https://developer.android.com/reference/android/content/res/Resources
• https://developer.android.com/guide/topics/resources/providing-resources
5.11 Assignment
5.12 Activity
• Create String Resource for Title and Welcome message for Main Activity and use
it at design time and programmatically to set at runtime.
146
Block-4
Android User
Interface Design
147
Unit-1: Basic User Interface
Screen elements 1
Unit Structure
1.0. Learning Objectives
1.1. Introduction
1.3. TextView
1.4. EditText
1.5. AutoCompleteTextView
1.6. Spinner
1.7. Buttons
1.10. Pickers
1.14. Activities
148
1.0 Learning Objective
1.1 Introduction
Most Android applications inevitably need some form of user interface. In this unit,we
will discuss the user interface elements available within the Android Software
DevelopmentKit (SDK). Some of these elements display information to the user,
whereas othersgather information from the user.
You learn how to use a variety of different components and controls to build a
screenand how your application can listen for various actions performed by the user.
Finally, youlearn how to style controls and apply themes to entire screens.
Before we go any further, we need to define a few terms.This gives you a better
understandingof certain capabilities provided by the Android SDK before they are
fully introduced.First, let’s talk about the View class.
This class represents the basic building block for user interface components. A View
occupies a rectangular area on the screen and is responsible for drawing and event
handling. View is the base class for widgets, which are used to create interactive UI
components (buttons, text fields, etc.). The ViewGroup subclass is the base class for
149
layouts, which are invisible containers that hold other Views (or other ViewGroups)
and define their layout properties.
All of the views in a window are arranged in a single tree. You can add views either
from code or by specifying a tree of views in one or more XML layout files. There are
many specialized subclasses of views that act as controls or are capable of
displaying text, images, or other content.
Once you have created a tree of views, there are typically a few types of common
operations you may wish to perform:
Set properties: for example setting the text of a TextView. The available properties
and the methods that set them will vary among the different subclasses of views.
Note that properties that are known at build time can be set in the XML layout files.
Set focus: The framework will handle moving focus in response to user input. To
force focus to a specific view, call requestFocus().
Set up listeners: Views allow clients to set listeners that will be notified when
something interesting happens to the view. For example, all views will let you set a
listener to be notified when the view gains or loses focus. You can register such a
listener using setOnFocusChangeListener(android.view.View.OnFocusChangeListener).
Other view subclasses offer more specialized listeners. For example, a Button
exposes a listener to notify clients when the button is clicked.
150
Introduction to Android Layout
One special type of control found within the android.widget package is called a
layout.A layout control is still a View object, but it doesn’t actually draw anything
specific on thescreen. Instead, it is a parent container for organizing other controls
(children). Layoutcontrols determine how and where on the screen child controls are
drawn. Each type oflayout control draws its children using particular rules. For
instance, the LinearLayoutcontrol draws its child controls in a single horizontal row or
a single vertical column. Similarly,a TableLayout control displays each child control
in tabular format (in cells withinspecific rows and columns).
By necessity, we use some of the layout View objectswithin this unit to illustrate how
to use the controls previously mentioned.However, we don’t go into the details of the
various layout types available as part of theAndroid SDK until the next unit. We will
lean in more details about layout in next unit.
1.3 TextView
TextView is a user interface element that displays text to the user. Following table
shows important XML Attributes of TextView control.
Attribute Description
id id is an attribute used to uniquely identify a text view
gravity The gravity attribute is an optional attribute which is used to control the
alignment of the text like left, right, center, top, bottom, center_vertical,
center_horizontal etc.
text text attribute is used to set the text in a text view.
textColor textColor attribute is used to set the text color of a text view. Color
value is in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
textSize textSize attribute is used to set the size of text of a text view. We can
set the text size in sp(scale independent pixel) or dp(density pixel).
textStyle textStyle attribute is used to set the text style of a text view. The
possible text styles are bold, italic and normal.
151
background background attribute is used to set the background of a text view. We
can set a color or a drawable in the background of a text view
padding padding attribute is used to set the padding from left, right, top or
bottom.
Table-18
The following code sample shows a typical use, with an XML layout and code to
modify the contents of the text view:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is TextView"
android:layout_centerInParent="true"
android:textSize="35sp"
android:padding="15dp"
android:textColor="#aaa"
android:background="#fff"/>
</LinearLayout>
This code sample demonstrates how to modify the contents of the text view defined
in the previous XML layout:
152
helloTextView.setText(R.string.user_greeting);
}
}
To display this TextView on the screen, all your Activity needs to do is call
thesetContentView() method with the layout resource identifier in which you defined
in thepreceding XML shown.
You can change the text displayed programmatically by callingthe setText() method
on the TextView object. Retrieving the text is done with thegetText() method.To
customize the appearance of TextView we can use Styles and Themes.
1.4 EditText
EditText is a user interface element for entering and modifying text.Following table
shows important XML Attributes of EditText control.
Attribute Description
id This is an attribute used to uniquely identify an edit text
gravity The gravity attribute is an optional attribute which is used to control
the alignment of the text like left, right, center, top, bottom,
center_vertical, center_horizontal etc.
text This attribute is used to set the text in a text view.
hint It is an attribute used to set the hint i.e. what you want user to enter in
this edit text. Whenever user start to type in edit text the hint will
automatically disappear.
lines Defineshow many lines tall the input box is. If this isnot set, the entry
field grows as the user enters text.
textColorHint It is an attribute used to set the color of displayed hint.
textColor This attribute is used to set the text color of aedit text. Color value is
in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
textSize This attribute is used to set the size of text of aedit text. We can set
the text size in sp(scale independent pixel) or dp(density pixel).
153
textStyle This attribute is used to set the text style of aedit text. The possible
text styles are bold, italic and normal.
background This attribute is used to set the background of aedit text. We can set
a color or a drawable in the background of a edit text
padding Paddingattribute is used to set the padding from left, right, top or
bottom.
Table-19
Following layout code shows a basic EditText element.
<EditText
android:id=”@+id/txtName”
android:layout_height=”wrap_content”
android:hint=”Full Name”
android:lines=”4”
android:layout_width=”fill_parent” />
The EditText object is essentially an editable TextView. You can readtext from it in
by using the getText() method.You can also set initial text to draw in the text entry
area using the setText() method.You can also highlight a portion of the text fromcode
bycall to setSelection() method and a call to selectAll() method highlights theentire
text entry field.
By default, the user can perform a long press to bring up a context menu.This
providesto the user some basic copy, cut, and paste operations as well as the ability
tochange the input method and add a word to the user’s dictionary of frequently
usedwords. You can set theeditable attribute to false, so the user cannot edit the text
in the field but can still copytext out of it using a long press.
1.5 AutoCompleteTextView
154
of suggestions is displayed in drop down menu from which user can choose an item
which actually replace the content of EditBox with that.
It is a subclass of EditText class so we can inherit all the properties of EditText in a
AutoCompleteTextView.
<AutoCompleteTextView
android:id="@+id/ac"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Auto Suggestions EditText"/>
String v = ac.getText().toString();
155
(A) Label (B) EditText (C) TextBox (D) TextView
e) ___________is a user interface element for entering and modifying text.
(A) Label (B) EditText (C) TextBox (D) TextView
f) AutoCompleteTextView is a view i.e. similar to ________except that it displays a
list of completion suggestions automatically while the user is typing.
1.6 Spinner
In Android, Spinner provides a quick way to select one value from a set of values. It
is similar to dropdown list in other programming language. In a default state, a
spinner shows its currently selected value. It provides an easy way to select a value
from a known set.Following table shows important XML Attributes of spinner control.
Attribute Description
dropDownHorizontalOffset Amount of pixels by which the drop down should be
offset horizontally.
dropDownSelector List selector to use for spinnerMode="dropdown"
display.
156
dropdown 1 Spinner options will be presented to
the user as an inline dropdown
anchored to the spinner widget itself.
Table-20
As with the auto-complete method, the possible choices for a spinner can come from
an Adapter.You can also set the available choices in the layout definition by usingthe
entries attribute with an array resource. Following is an XML layout for showing
spinner
<Spinner
android:id=”@+id/Spinner01”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:entries=”@array/colors”
android:prompt=”@string/spin_prompt” />
This places a Spinner control on the screen.When the user selects it, apop-up shows
the prompt text followed by a list of the possible choices.This list allowsonly a single
item to be selected at a time, and when one is selected, the pop-up goes away.
First, the entries attribute is set to thevalues that shows by assigning it to an array
resource, referred to here as @array/colors.
The choices you provide for the spinner can come from any source, but must be
provided through a SpinnerAdapter, such as an ArrayAdapter if the choices are
available in an array or a CursorAdapter if the choices are available from a database
query.
For instance, if the available choices for your spinner are pre-determined, you can
provide them with a string array defined in a string resource file:
157
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
With an array such as this one, you can use the following code in
your Activity or Fragment to supply the spinner with the array using an instance
of ArrayAdapter:
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array,android.R.layout.simple_spinner_item);
158
Call setAdapter() to apply the adapter to your Spinner.
When the user selects an item from the drop-down, the Spinner object receives an
on-item-selected event.
159
If you implement the AdapterView.OnItemSelectedListener interface with your
Activity or Fragment (such as in the example above), you can pass this as the
interface instance.
1.7 Button
A user interface element the user can tap or click to perform an action.To display a
button in an activity, add a button to the activity's layout XML file:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:drawableLeft="@drawable/button_icon"
... />
To specify an action when the button is pressed, set a click listener on the button
object in the corresponding activity code:
Figure-61
public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_layout_id);
160
The above snippet creates an instance of View.OnClickListener and wires the
listener to the button using setOnClickListener(View.OnClickListener). As a result,
the system executes the code you write in onClick(View) after the user presses the
button.
Every button is styled using the system's default button background, which is often
different from one version of the platform to another. If you are not satisfied with the
default button style, you can customize it.
1.8 Checkbox
Figure-62
To create each checkbox option, create a CheckBox in your layout. Because a set of
checkbox options allows the user to select multiple items, each checkbox is
managed separately and you must register a click listener for each one.
When the user selects a checkbox, the CheckBox object receives an on-click event.
To define the click event handler for a checkbox, add the android:onClick attribute to
the <CheckBox> element in your XML layout. The value for this attribute must be the
name of the method you want to call in response to a click event. The Activity
hosting the layout must then implement the corresponding method.
Within the Activity that hosts this layout, the following method handles the click event
for both checkboxes:
Radio buttons allow the user to select one option from a set. You should use radio
buttons for optional sets that are mutually exclusive if you think that the user needs
to see all available options side-by-side. If it's not necessary to show all options side-
by-side, use a spinner instead.
Figure-63
To create each radio button option, create a RadioButton in your layout. However,
because radio buttons are mutually exclusive, you must group them together inside a
RadioGroup. By grouping them together, the system ensures that only one radio
button can be selected at a time.
When the user selects one of the radio buttons, the corresponding RadioButton
object receives an on-click event.
To define the click event handler for a button, add the android:onClick attribute to the
<RadioButton> element in your XML layout. The value for this attribute must be the
name of the method you want to call in response to a click event. The Activity
hosting the layout must then implement the corresponding method.
163
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButtonandroid:id="@+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pirates"
android:onClick="onRadioButtonClicked"/>
<RadioButtonandroid:id="@+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ninjas"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Within the Activity that hosts this layout, the following method handles the click event
for both radio buttons:
Android provides controls for the user to pick a time or pick a date as ready-to-use
dialogs. Each picker provides controls for selecting each part of the time (hour,
minute, AM/PM) or date (month, day, year). Using these pickers helps ensure that
your users can pick a time or date that is valid, formatted correctly, and adjusted to
the user's locale.
Figure-64
It is recommended that you use DialogFragment to host each time or date picker.
The DialogFragment manages the dialog lifecycle for you and allows you to display
the pickers in different layout configurations, such as in a basic dialog on handsets or
as an embedded part of the layout on large screens.
165
Here's an example:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
Once you've defined a DialogFragment like the one shown above, you can display
the time picker by creating an instance of the DialogFragment and calling show().
For example, here's a button that, when clicked, calls a method to show the dialog:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
166
android:text="@string/pick_time"
android:onClick="showTimePickerDialog" />
When the user clicks this button, the system calls the following method:
This method calls show() on a new instance of the DialogFragment defined above.
The show() method requires an instance of FragmentManager and a unique tag
name for the fragment.
Here's an example:
167
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
For example, here's a button that, when clicked, calls a method to show the dialog:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pick_date"
android:onClick="showDatePickerDialog" />
When the user clicks this button, the system calls the following method:
168
public void showDatePickerDialog(View v) {
DialogFragmentnewFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
This method calls show() on a new instance of the DialogFragment defined above.
The show() method requires an instance of Fragment Manager and a unique tag
name for the fragment.
169
1.12 Check your Progress: Possible Answers
1-a) (A) View 1-b) (B) View Group 1-c) (C) Either (A) or (B)
1-d) (D) TextView 1-e) (B) EditText 1-f) (B) EditText
2-a) (D) Spinner 2-b) on-item-selected 2-c) True
2-d) (C) Date or Time 2-e) False 2-f) True
• https://developer.android.com/reference/android/widget/TextView
• https://developer.android.com/reference/android/widget/EditText
• https://developer.android.com/reference/android/widget/Button
• https://developer.android.com/reference/android/widget/CheckBox
• https://developer.android.com/reference/android/widget/Spinner
1.14 Assignment
1.15 Activity
170
Unit-2: Designing User
Interfaces with Layouts 2
Unit Structure
2.0. Learning Objectives
2.1. Introduction
2.13. Assignment
2.14. Activity
171
2.0 Learning Objectives
2.1 Introduction
One special type of control found within the android.widget package is called a
layout.A layout control is still a View object, but it doesn’t actually draw anything
specific on thescreen. Instead, it is a parent container for organizing other controls
(children). Layoutcontrols determine how and where on the screen child controls are
drawn. Each type oflayout control draws its children using particular rules. For
instance, the LinearLayoutcontrol draws its child controls in a single horizontal row or
a single vertical column. Similarly,a TableLayout control displays each child control
in tabular format (in cells withinspecific rows and columns).
Android provides a simple way to create layout files inXML as resources provided in
the /res/layout project directory.This is the most commonand convenient way to build
Android user interfaces and is especially useful fordefining static screen elements
and control properties that you know in advance, and toset default attributes that you
can modify programmatically at runtime.
172
You can configure almost any ViewGroup or View (or View subclass) attribute using
theXML layout resource files.This method greatly simplifies the user interface design
process,moving much of the static creation and layout of user interface controls, and
basic definitionof control attributes, to the XML, instead of littering the code.
Developers reserve theability to alter these layouts programmatically as necessary,
but they can set all the defaultsin the XML template.You will recognize the following
as a simple layout file with a LinearLayout and a singleTextView control.
This block of XML shows a basic layout with a single TextView.The first line, which
youmight recognize from most XML files, is required.
Creating only an XML file, though, won’t actually draw anything on the screen.A
particularlayout is usually associated with a particular Activity. In your default
Androidproject, there is only one activity, which sets the main.xml layout by
default.To associatethe main.xml layout with the activity, use the method call
setContentView() with theidentifier of the main.xml layout.The ID of the layout
matches the XML filename withoutthe extension. In this case, the preceding example
came from main.xml, so the identifierof this layout is simply main:
setContentView(R.layout.main);
173
2.3. Creating Layouts Programmatically
The onCreate() method is called when the Activity is created.The first thing
thismethod does is some normal Activity housekeeping by calling the constructor for
the
base class.Next, two TextView controls are instantiated.The Text property of each
TextView isset using the setText() method.AllTextView attributes, such as TextSize,
are set by making method calls on the TextView object.These actions perform the
same functionthat you have in the past by setting the properties Text and
174
TextSizeusing the layout resource designer, except these properties are set at
runtime instead of defined inthe layout files compiled into your application package.
We talked a lot about the LinearLayout layout, but there are several other types of
layouts.Each layout has a different purpose and order in which it displays its child
View controlson the screen. Layouts are derived from android.view.ViewGroup.
• FrameLayout
• LinearLayout
• RelativeLayout
• TableLayout
All layouts, regardless of their type, have basic layout attributes. Layout attributes
apply toany child View within that layout.You can set layout attributes at runtime
programmatically,but ideally you set them in the XML layout files using the following
syntax:android:layout_attribute_name=”value”
There are several layout attributes that all ViewGroup objects share.These include
sizeattributes and margin attributes.You can find basic layout attributes in
theViewGroup.LayoutParamsclass.The margin attributes enable each child View
within alayout to have padding on each side. Find these attributes in
theViewGroup.MarginLayoutParams classes.There are also a number of ViewGroup
attributesfor handling child View drawing bounds and animation settings.
FrameLayout is designed to block out an area on the screen to display a single item.
Generally, FrameLayout should be used to hold a single child view, because it can
be difficult to organize child views in a way that's scalable to different screen sizes
175
without the children overlapping each other. You can, however, add multiple children
to a FrameLayout and control their position within the FrameLayout by assigning
gravity to each child, using the android:layout_gravity attribute.
Child views are drawn in a stack, with the most recently added child on top. The size
of the FrameLayout is the size of its largest child (plus padding), visible or not (if the
FrameLayout's parent permits). Views that are View.GONE are used for sizing only if
setConsiderGoneChildrenWhenMeasuring() is set to true.
176
Figure-65
2.6. LinearLayout
A LinearLayout view organizes its child View objects in a single row, shown in Figure
below, or column, depending on whether its orientation attribute is set to horizontal
or vertical.This is a very handy layout method for creating forms.
You can find the layout attributes available for LinearLayout child View objects
inandroid.control.LinearLayout.LayoutParams. Following table describes some of the
importantattributes specific to LinearLayout views.
177
Attribute Applies Description Value
Name To
android: Parent Layout is a single Horizontal or Vertical
view row(horizontal) or
orientation
singlecolumn
(vertical).
android: Parent Gravity of child One or more constants
view viewswithin layout. separated by“|”. The constants
gravity
available are top,bottom, left,
right, center_vertical, fill_vertical,
center_horizontal, fill_horizontal,
center, and fill.
android: Child The gravity for a One or more constants
View specificchild view. separated by“|”. The constants
layout_
Used available are top,bottom, left,
gravity forpositioning of right, center_vertical, fill_vertical,
views. center_horizontal, fill_horizontal,
center, and fill.
android: Child The weight for a The sum of values across all
view specificchild view.childviews in a parent view must
layout_
Used toprovide
equal 1.For example, one child
weight ratio of screen control mighthave a value of .3
space used within and anotherhave a value of .7.
theparent control.
Table-22
Figure-66
178
2.7. RelativeLayout
The RelativeLayout view enables you to specify where the child view controls are
inrelation to each other. For instance, you can set a child View to be positioned
“above” or“below” or “to the left of ” or “to the right of ” another View, referred to by its
uniqueidentifier.You can also align child View objects relative to one another or the
parent layoutedges. Combining RelativeLayout attributes can simplify creating
interesting user interfaceswithout resorting to multiple layout groups to achieve a
desired effect. You can find the layout attributes available for RelativeLayout child
View objects inandroid.control.RelativeLayout.LayoutParams. Following Table
describes some of the importantattributes specific to RelativeLayout views.
Following figure shows how each of the button controls is relative to each other.
180
Figure-67
Here’s an example of an XML layout resource with a RelativeLayout and two child
View objects, a Button object aligned relative to its parent, and an ImageView
aligned andpositioned relative to the Button (and the parent):
2.8. TableLayout
181
A TableLayout view organizes children into rows, as shown in following Figure-68.
You add individualView objects within each row of the table using a TableRow layout
View (which isbasically a horizontally oriented LinearLayout) for each row of the
table. Each column ofthe TableRow can contain one View (or layout with child View
objects).You place Viewitems added to a TableRow in columns in the order they are
added.You can specify thecolumn number (zero-based) to skip columns as
necessary (the bottom row shown in above figure demonstrates this); otherwise, the
View object is put in the next column to theright. Columns scale to the size of the
largest View of that column.You can also includenormal View objects instead of
TableRow elements, if you want the View to take up an entirerow.
Figure-68
You can find the layout attributes available for TableLayout child View objects
inandroid.control.TableLayout.LayoutParams.You can find the layout attributes
availableforTableRow child View objects in android.control.TableRow.LayoutParams.
Following Table describes some of the important attributes specific to TableLayout
View objects.
182
Attribute Name Applies To Description Value
android:collapseC TableLayout A comma-delimitedlist String or string
olumns of column indices resource.For
to collapse (0-based) example, “0,1,3,5”
android: TableLayout A comma-delimited String or string
shrinkColumns list of column indices resource.Use “*” for
to shrink (0-based) all columns.
For example,
“0,1,3,5”
andriod: TableLayout A comma-delimited String or string
stretchColumns list of column indices resource.Use “*” for
to stretch (0-based) all columns.
For example,
“0,1,3,5”
android: TableRow Index of column this Integer or integer
layout_column child view child view should be resource.For
displayed in (0-based) example, 1
android: TableRow Number of columns Integer or integer
layout_span child view this child view should resourcegreater
span across than orequal to
1.For example, 3
Table-24
Here’s an example of an XML layout resource with a TableLayout with two rows (two
TableRow child objects).The TableLayout is set to stretch the columns to the size of
thescreen width.The first TableRow has three columns; each cell has a Button
object.Thesecond TableRow puts only one Button view into the second column
explicitly:
<TableLayoutxmlns:android=“http://schemas.android.com/apk/res/android”
android:id=”@+id/TableLayout01”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:stretchColumns=”*”>
<TableRowandroid:id=”@+id/TableRow01”>
183
<Buttonandroid:id=”@+id/ButtonLeft”
android:text=”Left Door” />
<Buttonandroid:id=”@+id/ButtonMiddle”
android:text=”Middle Door” />
<Buttonandroid:id=”@+id/ButtonRight”
android:text=”Right Door” />
</TableRow>
<TableRowandroid:id=”@+id/TableRow02”>
<Buttonandroid:id=”@+id/ButtonBack”
android:text=”Go Back”
android:layout_column=”1” />
</TableRow>
</TableLayout>
Some of the View container controls are designed for displaying repetitive View
objects ina particular way. Examples of this type of View container control include
ListView,GridView, and GalleryView:
184
In this section, you learn how to bind data to View objects using Adapter objects.
Inthe Android SDK, an Adapter reads data from some data source and provides a
View objectbased on some rules, depending on the type of Adapter used.This View
is used topopulate the child View objects of a particular AdapterView.
The most common Adapter classes are the CursorAdapter and the
ArrayAdapter.TheCursorAdapter gathers data from a Cursor, whereas the
ArrayAdapter gathers data froman array.A CursorAdapter is a good choice to use
when using data from a database.TheArrayAdapter is a good choice to use when
there is only a single column of data orwhen the data comes from a resource array.
There are some common elements to know about Adapter objects.When creating
anAdapter, you provide a layout identifier.This layout is the template for filling in each
rowof data.The template you create contains identifiers for particular controls that
theAdapter assigns data to.A simple layout can contain as little as a single TextView
control.
When making an Adapter, refer to both the layout resource and the identifier of the
TextView control.The Android SDK provides some common layout resources for use
inyour application.
An ArrayAdapter binds each element of the array to a single View object within the
layoutresource. Here is an example of creating an ArrayAdapter:
In this example, we have a String array called items.This is the array used by
theArrayAdapter as the source data.We also use a layout resource, which is the
View that isrepeated for each item in the array.This is defined as follows:
185
<TextViewxmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textSize=”20px” />
This layout resource contains only a single TextView. However, you can use a more
complexlayout with the constructors that also take the resource identifier of a
TextViewwithin the layout. Each child View within the AdapterView that uses this
Adapter getsone TextView instance with one of the strings from the String array.
If you have an array resource defined, you can also directly set the entries attribute
foran AdapterView to the resource identifier of the array to automatically provide the
ArrayAdapter.
startManagingCursor(names);
ListAdapter adapter = new SimpleCursorAdapter(
this, R.layout.two_text,
names, new String[] {
Contacts.Phones.NAME,
Contacts.Phones.NUMBER
}, new int[] {
R.id.scratch_text1,
R.id.scratch_text2
});
186
In this example, we present a couple of new concepts. First, you need to know that
theCursor must contain a field named _id. In this case, we know that the Contacts
contentprovider does have this field.This field is used later when you handle the user
selecting aparticular item.
Now that you have an Adapter object, you can apply this to one of the AdapterView
controls.Any of them works.Although the Gallery technically takes a
SpinnerAdapter,the instantiation of SimpleCursorAdapter also returns a
SpinnerAdapter. Here is an exampleof this with a ListView, continuing on from the
previous sample code:
((ListView)findViewById(R.id.list)).setAdapter(adapter);
187
Figure-69
Handling Selection Events
You often use AdapterView controls to present data from which the user should
select.All three of the discussed controls—ListView, GridView, and Gallery—enable
your applicationto monitor for click events in the same way.You need to
callsetOnItemClickListener() on your AdapterView and pass in an implementation
ofthe AdapterView.OnItemClickListener class.
av.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(
AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(Scratch.this, “Clicked _id=”+id,
Toast.LENGTH_SHORT).show();
}
});
Finally, the id parameter is the value of the _id column for the particular item thatthe
user selects.This is useful for querying for further information about that particularrow
of data that the item represents.
188
parameters are the same, yourapplication receives a call as the highlighted item
changes.This can be in response to theuser scrolling with the arrow keys and not
selecting an item for action.
189
2.12 Further Reading
• https://developer.android.com/reference/android/widget/FrameLayout
• https://developer.android.com/reference/android/widget/TableLayout
• https://developer.android.com/reference/android/widget/RelativeLayout
• https://developer.android.com/reference/android/widget/GridLayout
• https://developer.android.com/reference/android/widget/ListView
• https://developer.android.com/reference/android/widget/GridView
• https://developer.android.com/reference/android/widget/Gallery
2.13 Assignment
2.14 Activity
• Design Interface using different Layouts for collecting personal information such
as Id, Name, Date of Birth, Gender, Address etc.
190
Unit-3: Drawing and Working
with Animation 3
Unit Structure
3.0. Learning Objectives
3.1. Introduction
3.3. Bitmaps
3.4. Shapes
3.10. Assignment
3.11. Activity
191
3.0 Learning Objectives
3.1. Introduction
With Android, we can displayimages such as PNG and JPG graphics, as well as text
and primitive shapes to the screen.We can paint these items with various colors,
styles, or gradients and modify them usingstandard image transforms.We can even
animate objects to give the illusion of motion.
The Canvas class holds the "draw" calls. To draw something, you need 4 basic
components:
1. A Bitmap to hold the pixels,
2. A Canvas to host the draw calls (writing into the bitmap),
3. A drawing primitive (e.g. Rect, Path, text, Bitmap), and
4. A paint (to describe the colors and styles for the drawing).
For instance, Canvas provides a method to draw a line, while Paint provides
methods to define that line's color. Canvas has a method to draw a rectangle, while
Paint defines whether to fill that rectangle with a color or leave it empty. Simply put,
Canvas defines shapes that you can draw on the screen, while Paint defines the
color, style, font, and so forth of each shape you draw.
192
So, before you draw anything, you need to create one or more Paint objects. The
PieChart example does this in a method called init, which is called from the
constructor from Java.
Creating objects ahead of time is an important optimization. Views are redrawn very
frequently, and many drawing objects require expensive initialization. Creating
drawing objects within your onDraw() method significantly reduces performance and
can make your UI appear sluggish.
Once you have your object creation and measuring code defined, you can implement
onDraw(). Every view implements onDraw() differently, but there are some common
operations that most views share:
• Draw text using drawText(). Specify the typeface by calling setTypeface(), and
the text color by calling setColor().
• Draw primitive shapes using drawRect(), drawOval(), and drawArc(). Change
whether the shapes are filled, outlined, or both by calling setStyle().
• Draw more complex shapes using the Path class. Define a shape by adding lines
and curves to a Path object, then draw the shape using drawPath(). Just as with
primitive shapes, paths can be outlined, filled, or both, depending on the
setStyle().
193
• Define gradient fills by creating LinearGradient objects. Call setShader() to use
your LinearGradient on filled shapes.
• Draw bitmaps using drawBitmap().
For example, here's the code that draws PieChart. It uses a mix of text, lines, and
shapes.
3.3 Bitmaps
You can find lots of goodies for working with graphics such as bitmaps in the
android.graphics package.The core class for bitmaps isandroid.graphics.Bitmap.
194
Drawing Bitmap Graphics on a Canvas
You can draw bitmaps onto a valid Canvas, such as within the onDraw() method of a
View, using one of the drawBitmap() methods. For example, the following code loads
a Bitmap resource and draws it on a canvas:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
...
Bitmap pic = BitmapFactory.decodeResource(getResources(),
R.drawable.bluejay);
canvas.drawBitmap(pic, 0, 0, null);
Perhaps you want to scale your graphic to a smaller size. In this case, you can use
thecreateScaledBitmap() method, like this:
You can preserve the aspect ratio of the Bitmap by checking the getWidth() and
getHeight() methods and scaling appropriately.
3.4 Shapes
You can define and draw primitive shapes such as rectangles and ovals using
theShapeDrawable class in conjunction with a variety of specialized Shape
classes.You candefine Paintable drawables as XML resource files, but more often,
especially with morecomplex shapes, this is done programmatically.
195
In Unit-5,“Application Resources” of block-3, we show you how to define
primitiveshapes such as rectangles using specially formatted XML files within the
/res/drawable/resource directory.
The following resource file called /res/drawable/green_rect.xml describes a simple,
green rectangle shape drawable:
You can then load the shape resource and set it as the Drawable as follows:
You should note that many Paint properties can be set via XML as part of the
Shapedefinition. For example, the following Oval shape is defined with a linear
gradient (red towhite) and stroke style information:
196
You can also define this ShapeDrawable instances programmatically. The different
shapesare available as classes within the android.graphics.drawable.shapes
package. For example,you can programmatically define the aforementioned green
rectangle as follows:
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
...
You can then set the Drawable for the ImageView directly:
You can create and use these shapes as Drawable resources directly within
ImageViewviews, or you can find corresponding methods for creating these primitive
shapes withina Canvas.
197
Drawing rectangles and squares (rectangles with equal height/width values) is simply
amatter of creating a ShapeDrawable from a RectShape object.The RectShape
object hasno dimensions but is bound by the container object—in this case, the
ShapeDrawable.
You can set some basic properties of the ShapeDrawable, such as the Paint color
and thedefault size.
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
…
198
Frame-by-frame animation is best used for complicated graphics transformations
thatare not easily implemented programmatically.
With tweened animation, you can provide a single Drawable resource - it is a Bitmap
graphic, a ShapeDrawable, a TextView, orany other type of View object—and the
intermediate frames of the animation are renderedby the system.Android provides
tweening support for several common image transformations,including alpha, rotate,
scale, and translate animations.You can apply tweenedanimation transformations to
any View, whether it is an ImageView with a Bitmap orshape Drawable, or a layout
such as a TableLayout.
import android.view.animation.RotateAnimation;
...
RotateAnimation rotate = new RotateAnimation(0, 360,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(5000);
Loading Animations
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
...
ImageView iView = (ImageView)findViewById(R.id.ImageView1);
iView.setImageResource(R.drawable.green_rect);
Animation an =AnimationUtils.loadAnimation(this, R.anim.grow);
iView.startAnimation(an);
We can listen for Animation events, including the animation start, end, and repeat
events,by implementing an AnimationListener class, such as the MyListener class
shown here:
202
class MyListener implements Animation.AnimationListener {
public void onAnimationEnd(Animation animation) {
// Do at end of animation
}
public void onAnimationRepeat(Animation animation) {
// Do each time the animation loops
}
public void onAnimationStart(Animation animation) {
// Do at start of animation
}
}
Alpha values range from 0.0 (fully transparent or invisible) to 1.0 (fully opaque or
visible).Alpha animations involve a starting transparency (fromAlpha) and an ending
transparency(toAlpha).
203
<alphaandroid:fromAlpha=”0.0”
android:toAlpha=”1.0”
android:duration=”5000”>
</alpha>
Programmatically, you can create this same animation using the AlphaAnimation
classwithin the android.view.animation package.
Working with Rotating Transformations
Rotations are defined in terms of degrees. For example, you might want an object to
make one complete clockwise rotation.To do this, you set the fromDegrees property
to 0and the toDegrees property to 360.To rotate the object counterclockwise instead,
youset the toDegrees property to -360.
By default, the object pivots around the (0,0) coordinate, or the top-left corner of
theobject.This is great for rotations such as those of a clock’s hands, but much of the
time,you want to pivot from the center of the object; you can do this easily by setting
the pivotpoint, which can be a fixed coordinate or a percentage.
The following XML resource file excerpt defines a rotation animation, taking five
secondsto make one full clockwise rotation, pivoting from the center of the object:
<rotateandroid:fromDegrees=”0”
android:toDegrees=”360”
android:pivotX=”50%”
android:pivotY=”50%”
android:duration=”5000” />
Programmatically, you can create this same animation using the RotateAnimation
classwithin the android.view.animation package.
The following XML resource file excerpt defines a scaling animation, taking five
secondsto double an object’s size, pivoting from the center of the object:
<scaleandroid:pivotX=”50%”
android:pivotY=”50%”
android:fromXScale=”1.0”
android:fromYScale=”1.0”
android:toXScale=”2.0”
android:toYScale=”2.0”
android:duration=”5000” />
Programmatically, you can create this same animation using the ScaleAnimation
classwithin the android.view.animation package.
You can move objects around using translate operations.Translate operations move
an objectfrom one position on the (x,y) coordinate to another coordinate.
To perform a translate operation, you must specify the change, or delta, in the
object’scoordinates.You can set four values for translations: starting position
(fromXDelta,fromYDelta) and relative target location (toXDelta, toYDelta).
205
The following XML resource file excerpt defines a translate animation, taking 5
secondsto move an object up (negative) by 100 on the y-axis.We also set the
fillAfterproperty to be true, so the object doesn’t “jump” back to its starting position
when theanimation finishes:
<translate android:toYDelta=”-100”
android:fillAfter=”true”
android:duration=”2500” />
The Android SDK comes with the android.graphics package, which includes powerful
classes for drawing graphics and text to the screen in a variety of different ways.
Somefeatures of the graphics library include Bitmap graphics utilities, Typeface and
font stylesupport, Paint colors and styles, different types of gradients, and a variety
of primitiveand not-so-primitive shapes that can be drawn to the screen and even
animated usingtweening and frame-by-frame animation mechanisms.
207
Website : www.baou.edu.in | Email : offi[email protected]