0% found this document useful (0 votes)
396 views99 pages

Android Notes Gondwana University Gadchiroli

The document discusses the structure of an Android project. It describes the key folders in an Android project like src, gen, res, assets, and libs. It explains that the src folder contains Java source files, gen contains generated Java libraries, and res stores resource files like images, XML files etc. It provides details on the subfolders within res like drawable for images, layout for XML layout files, values for storing string values. It also describes important files like AndroidManifest.xml, MainLayout.xml and the Activity class. Finally, it briefly explains the need for the Dalvik Virtual Machine in Android to optimize the JVM for mobile devices.

Uploaded by

Pranay nandanwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
396 views99 pages

Android Notes Gondwana University Gadchiroli

The document discusses the structure of an Android project. It describes the key folders in an Android project like src, gen, res, assets, and libs. It explains that the src folder contains Java source files, gen contains generated Java libraries, and res stores resource files like images, XML files etc. It provides details on the subfolders within res like drawable for images, layout for XML layout files, values for storing string values. It also describes important files like AndroidManifest.xml, MainLayout.xml and the Activity class. Finally, it briefly explains the need for the Dalvik Virtual Machine in Android to optimize the JVM for mobile devices.

Uploaded by

Pranay nandanwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 99

1 | Pranay Nandanwar

Unit 1
a) Draw and explain Android studio project structure. S18

c) Write a detail note on Android project structure. S19

a) Draw and explain Android studio project structure. W18 OLD

Developing an Android project, you have to install the Android plug-ins for Eclipse and
at least have some knowledge of Java programming.

After installing all the plug-ins for an Android file, you can begin to develop an Android
application.

Android uses packages not only to arrange the code in an application but to manage the
application themselves.

The above diagram shows the basic building blocks of an Android application. Android
application in Eclipse or in any development tool have a pre-defined structure with code
and resource organized into a number of folders.
2 | Pranay Nandanwar

Every Android project contains several folders, like:

Folder Name Description

src The 'src' stands for Source Code. It contains the Java Source files.

gen The 'gen' stands for Generated Java Library. This library is for Android
internal use only.

Android 2.2 The Android Framework Library is stored here.

assets It is used to store raw asset files.

libs It contains private libraries.

res The 'res' stands for Resource file. It can store resource files such as pictures,
XML files, etc. It contains some additional folders such as Drawable, Layout
and Values.

anim: It is used for XML files that are compiled into animation objects.
color: It is used for XML files that describe colors.
drawable: It is used to store various graphics files. In Android project
structure,

there are three types of drawable folders,


1. drawable-mdpi
2. drawable-hdpi
3. drawable-ldpi

The above drawable folders are required in order to adapt to different screen
resolutions.

layout: It is used for placing the XML layout files, which defines how various
Android objects such as textbox, buttons, etc. are organized on the screen.

menu: It is used for defining the XML files in the application menu.

raw: The 'raw' stands for Raw Asset Files. These files are referenced from
the application using a resource identifier in the R class.
For example, good place for media is MP3 or Ogg files.

values: It is used for XML files which stores various string values, such as
titles, labels, etc.

xml: It is used for configuring the application components.

AndroidManifest.xml This file indicates the Android definition file. This file contains the information
about the Android application such as minimum Android version, permission to
access Android device capabilities such as Internet access permission, phone
permission etc.

default.properties This file contains the project settings, such as build the target. Do not edit this
file manually. It should be maintained in a Source Revision Control System.
3 | Pranay Nandanwar

Proguard.cfg This file defines how ProGuard optimizes and makes your code unclear.

MainLayout.xml This file describes the layout of the page. So all the components such as
textboxes, labels, radio buttons, etc. are displaying on the application screen.

Activity class The application occupies the entire device screen which needs at least one
class inherits from the Activity class. OnCreate() method initiates the
application and loads the layout page.

After you have installed all the plug-ins necessary for the development of an Android file, you
can now begin to develop an Android application. From the top menu, choose File -> Project,
and from the "New Project window", choose "Android Project". Follow the project setup wizard
and after finishing the wizard, you will have a basic Android application. Every Android project
contains several folders:

 src: This folder contains the Java source files.


 gen: Generated Java library, this library is for Android internal use only.
 Res: Here we can store resource files such as pictures, XML files for defining layouts, and so
forth. Within this folder there are additional folders such as Drawable, Layout, and Values.
 Drawable: Here we store the various graphic files. We can see three types of drawable folders.
This is because there are many Android devices with different screen resolutions. By default,
there are several versions of this folder such as: Drawable-mdpi, drawable-hdpi, and so forth.
This is required in order to adapt to different screen resolutions.
 Layout: This is the place for XML layout files. Layout files are XML files which define how various
Android objects (such as textboxes, buttons, etc.) are organized on the screen.
 Values: XML files which store various string values (titles, labels, etc.).

Major files in the Android project:

 AndroidManifest.xml: This is the Android definition file. It contains information about the
Android application such as minimum Android version, permission to access Android device
capabilities such as internet access permission, ability to use phone permission, etc.
 MainLayout.xml: This file describes the layout of the page. This means the placement of every
component (such as textboxes, labels, radio buttons, user defined components, etc.) on the app
screen.
 Activity class: Every application that occupies the entire device screen needs at least one class
which inherits from the Activity class. One major method is called OnCreate. This method
initiates the app and loads the layout page.

b) Write and android project to demonstrate Intent. S18


Step 1: Create a new Android Studio project with an empty activity.

Step 2: In the activity layout file (activity_main.xml), add a button with the text "Open Second Activity".

xml
<Button

android:id="@+id/button_open_second_activity"
4 | Pranay Nandanwar

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Open Second Activity" />

Step 3: In the activity class (MainActivity.java), add the following code to handle the button click and start the
second activity:

java
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button buttonOpenSecondActivity = findViewById(R.id.button_open_second_activity);


buttonOpenSecondActivity.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
}
Step 4: Create a new activity class (SecondActivity.java) with a simple layout (second_activity.xml) that displays
some text:

java

public class SecondActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.second_activity);

}
5 | Pranay Nandanwar

xml

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="This is the second activity." />

That's it! Now when the user clicks the "Open Second Activity" button in the main activity, the second activity will
be opened and display the text "This is the second activity."

c) What is DVM? Explain the need of DVM in brief. S18

As we know the modern JVM is high performance and provides excellent memory management.
But it needs to be optimized for low-powered handheld devices as well.

The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices.
It optimizes the virtual machine for memory, battery life and performance.

Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.

The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple
class files are converted into one dex file.

The javac tool compiles the java source file into the class file.

The dx tool takes all the class files of your application and generates a single .dex file. It is a
platform-specific tool.

The Android Assets Packaging Tool (aapt) handles the packaging process.

Working of DVM
The Java Compiler(javac) converts the Java Source Code into Java Byte-Code(.class).
Then DEX Compiler converts this (.class) file into in Dalvik Byte Code i.e. “.dex” file.
6 | Pranay Nandanwar

Application
For Android, a new Virtual machine was developed by Google as stated above. It uses
registers of the CPU to store the operands. So no requirement of any pushing and
popping of instructions. Hence making execution faster. The instructions operate on
virtual registers, being those virtual registers memory positions in the host device.
Register-based models are good at optimizing and running on low memory. They can
store common sub-expression results which can be used again in the future. This is
not possible in a Stack-based model at all. Dalvik Virtual Machine uses its own byte-
code and runs “.dex”(Dalvik Executable File) file.
Advantages
 DVM supports the Android operating system only.
 In DVM executable is APK.
 Execution is faster.
 From Android 2.2 SDK Dalvik has it’s own JIT (Just In Time) compiler.

 DVM has been designed so that a device can run multiple instances of the Virtual
Machine effectively.
 Applications are given their own instances.
Disadvantages
 DVM supports only Android Operating System.
 For DVM very few Re-Tools are available.
 Requires more instructions than register machines to implement the same high-
level code.
 App Installation takes more time due to dex.
 More internal storage is required.

Role of Dalvik Virtual Machine (DVM)

The role of Dalvik Virtual Machine(DVM) is that In java we write and compile java programs using java compiler
and run that bytecode on the java virtual machine. On the other side, In android, we still write and compile java
source file(bytecode) on java compiler, but at that point, we recompile it once again using Dalvik compiler to
Dalvik bytecode (dx tool converts java .class file into .dex format) and this Dalvik bytecode is then executed on
the Dalvik virtual machine.

a) What is Android? Explain its platform in detail. W18

a) Discuss Android platform with diagram. W19

c) What is Android? Explain its features in detail. W18 OLD

Android is an open source and Linux-based Operating System for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance, led
by Google, and other companies.
Android offers a unified approach to application development for mobile devices which means
developers need only develop for Android, and their applications should be able to run on different
devices powered by Android.
The first beta version of the Android Software Development Kit (SDK) was released by Google in
2007 where as the first commercial version, Android 1.0, was released in September 2008.
On June 27, 2012, at the Google I/O conference, Google announced the next Android version,
4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user
interface, both in terms of functionality and performance.
7 | Pranay Nandanwar

The source code for Android is available under free and open source software licenses. Google
publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel
changes, under the GNU General Public License version 2.

Why Android ?

Features of Android
After learning what is android, let's see the features of android. The important features of android
are given below:

1) It is open-source.

2) Anyone can customize the Android Platform.

3) There are a lot of mobile applications that can be chosen by the consumer.

4) It provides many interesting features like weather details, opening screen, live RSS (Really
Simple Syndication) feeds etc.

Android is a powerful operating system competing with Apple 4GS and supports great features.
Few of them are listed below −

Sr.No. Feature & Description

1 Beautiful UI
Android OS basic screen provides a beautiful and intuitive user interface.
8 | Pranay Nandanwar

2 Connectivity
GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX.

3 Storage
SQLite, a lightweight relational database, is used for data storage purposes.

4 Media support
H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV,
JPEG, PNG, GIF, and BMP.

5 Messaging
SMS and MMS

6 Web browser
Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine
supporting HTML5 and CSS3.

7 Multi-touch
Android has native support for multi-touch which was initially made available in handsets such as
the HTC Hero.

8 Multi-tasking
User can jump from one task to another and same time various application can run
simultaneously.

9 Resizable widgets
Widgets are resizable, so users can expand them to show more content or shrink them to save
space.

10 Multi-Language
Supports single direction and bi-directional text.

11 GCM
Google Cloud Messaging (GCM) is a service that lets developers send short message data to their
users on Android devices, without needing a proprietary sync solution.

12 Wi-Fi Direct
A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer
connection.

13 Android Beam
A popular NFC-based technology that lets users instantly share, just by touching two NFC-enabled
phones together.

Categories of Android applications


There are many android applications in the market. The top categories are:

o Entertainment
o Tools
o Communication
9 | Pranay Nandanwar

o Productivity
o Personalization
o Music and Audio
o Social
o Media and Video
o Travel and Local etc.

Android Applications

Android applications are usually developed in the Java language using the Android Software
Development Kit.
Once developed, Android applications can be packaged easily and sold out either through a store
such as Google Play, SlideME, Opera Mobile Store, Mobango, F-droid and the Amazon
Appstore.
Android powers hundreds of millions of mobile devices in more than 190 countries around the
world. It's the largest installed base of any mobile platform and growing fast. Every day more than
1 million new Android devices are activated worldwide.
This tutorial has been written with an aim to teach you how to develop and package Android
application. We will start from environment setup for Android application programming and then
drill down to look into various aspects of Android applications.

Categories of Android applications


There are many android applications in the market. The top categories are −

History of Android
The code names of android ranges from A to N currently, such as Aestro, Blender, Cupcake,
Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat,
Lollipop and Marshmallow. Let's understand the android history in a sequence.
10 | Pranay Nandanwar

Android Platform
Android is an open source, Linux-based software stack created for a wide array of devices
and form factors. This is being used in mobile, tablet as well as in TV. Android platform is
divided into 6 sections and five main layers.
11 | Pranay Nandanwar

Android Platform Architecture Division


The 6 main sections are as below –

1. Linux Kernel
2. Hardware Abstraction Layer
3. Native C/C++ Libraries
4. Android RuntimeJava API Framework
5. System Apps
1. Linux Kernel
Linux kernel is the foundation of the android platform. Layers such as Android
Runtime depends on linux kernel for basic functionalities such as threading,
memory managements etc. it also allows manufacturer to develop driver for a well
known kernel. Linux kernel also provide key security features including
a. A user-based permission model. For example, you can not read some other
user’s profile.
b. Process isolation.
c. Extensible mechanism for secure Inter -process communication.
d. Ability to remove un-necessary and insecure parts of the kernel.

This layer also provides a level of abstraction between the device hardware. It
contains all the hardware drivers. For example, Display driver, Camera driver,
Bluetooth driver, Flash Memory driver, Binder driver, USB driver , Keypad driver,
Wifi driver, Audio driver, Power management etc.

This layer is the foundation of the Android Platform.

 Contains all low level drivers for various hardware components support.

 Android Runtime relies on Linux Kernel for core system services like,

o Memory, process management, threading etc.

o Network stack

o Driver model

o Security and more.

2. Hardware Abstraction layer


It contains multiple library modules. Each module implements interface for a
specific type of hardware component. For example, Camera module, Bluetooth
module, Audio module, Sensors module etc. Whenever a request to access device
hardware is made, the Android System loads the library module for that hardware
component.

3. Native C/C++ libraries


On the top of linux kernel, their are Native libraries such as WebKit, OpenGL, FreeType, SQLite,
Media, C runtime library (libc) etc.
12 | Pranay Nandanwar

Android components and services are made up of native codes that finally needs
some native libraries. These native libraries are written in c and c++. Android
platform provides java api frameworks to make developers enable to use
functionality of such libraries. For example, For drawing and manipulating 2D and
3D graphics in android application, we use Java OpenGL api. This Java OpenGL api
access OpenGL ES.
This section consists of such java based libraries. Such libraries helps developer in
user-interface building, graphics drawing and database access. Some of the popular
libraries are as below –

1. android.app – It enables to access the application model.


2. android.content – enables to access content, communicate between different
applications etc.
3. android.database – Enables to access database.
4. android.opengl – Enables to access OpenGL ES 3D graphics rendering api.
5. android.os – Enables to access operating system services, messaging, inter -
process communications etc.
6. android.text – Enable to manage and render text display.
7. android.view – It is fundamental building block of application UI
8. android.widget – This contains several views such as butt on, textview etc. These
are used to develop application.
9. android.webkit – Enables to implement web bro wsing into android application.

4. Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile devices. It
consumes less memory and provides fast performance.

This layer was designed to run the application in low memory as well. In device that
has Android version 5.0 or highe r, each app runs in it’s own process. Also, it has
it’s own instance of Android Runtime. ART is written to run multiple virtual machine
on low memory devices by executing DEX files. DEX files is a bytecode format
designed for Android. Some of the major fea tures of ART is as below –
a. Optimised Garbage collector.
b. Ahead-of-time(AOT) and Just-in-Time(JIT) compilation.
c. Improved debugging support.

Before Android 5.0, Dalvik was the Android Runtime. If any application runs
properly in Android Runtime, then , it will work properly in Dalvik as well. But, the
vice-versa may not be true.
This layer also contains some core libraries that provides most of the functionality
of the Java programming language that Java api framework uses. Thus, it enables
android application developers to create project u sing Java programming language.

5. Java API Framework


This layer provides many higher level services as java class. You can use this class
into your application to use such services. Services are
1. Resource Manager: It helps to access values from strings file, layout files etc.
2. Notification Manager: It enables to display notification in status bar.
3. Activity Manager: This manages app life cycle and navigation back stack.
4. Content Providers: Used to access data from other apps. For example, Access
13 | Pranay Nandanwar

contacts from contact app etc.


5. View System: Used to build application UI. You can make structures like list,
grid, textview etc.

6. System Apps
This is top layer and contains all the android applications. The androi d applications
may be core apps or built by the user. Some core apps may be for Email,
Messaging, calendars etc. This app does not have a special priority from the app
that user choose to install. User can choose any app to s end email of his/her own
choice

a) Explain the Android Stack in detail. S19

android architecture or Android software stack is categorized into five parts:

1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications

The Android software stack generally consists of a Linux kernel and a collection of
C/C++ libraries that are exposed through an application framework that provides
services, and management of the applications and run time.
Linux Kernel
Android was created on the open-source kernel of Linux. One main reason for choosing
this kernel was that it provided proven core features on which to develop the Android
operating system. The features of the Linux kernel are:
1. Security: The Linux kernel handles the security between the application and the
system.
2. Memory Management: It efficiently handles memory management thereby providing
the freedom to develop our apps.
3. Process Management: It manages the process well and allocates resources to
processes whenever they need them.
4. Network Stack: It effectively handles network communication.
5. Driver Model: It ensures that the application works. Hardware manufacturers can
build their drivers into the Linux build.
Libraries:
Running on top of the kernel, the Android framework was developed with various
features. It consists of various C/C++ core libraries with numerous open-source tools.
Some of these are:
1. The Android Runtime: The Android runtime consists of core libraries of Java and
ART(the Android RunTime). Older versions of Android (4.x and earlier) had Dalvik
runtime.
2. Open GL(graphics library): This cross-language, cross-platform application
program interface (API) is used to produce 2D and 3D computer graphics.
14 | Pranay Nandanwar

3. WebKit: This open-source web browser engine provides all the functionality to display
web content and simplify page loading.
4. Media frameworks: These libraries allow you to play and record audio and video.
5. Secure Socket Layer (SSL): These libraries are there for Internet security.
Android Runtime
It is the third section of the architecture. It provides one of the key components which is
called Dalvik Virtual Machine. It acts like Java Virtual Machine which is designed
especially for Android. Android uses its own custom VM designed to ensure that multiple
instances run efficiently on a single device.
The Dalvik VM uses the device’s underlying Linux kernel to handle low-level
functionality, including security, threading, and memory management.
Application Framework
The Android team has built on a known set of proven libraries, built in the background,
and all of it is exposed through Android interfaces. These interfaces wrap up all the
various libraries and make them useful for the Developer. They don’t have to build any
of the functionality provided by the android. Some of these interfaces include:
1. Activity Manager: It manages the activity lifecycle and the activity stack.
2. Telephony Manager: It provides access to telephony services as related subscriber
information, such as phone numbers.
3. View System: It builds the user interface by handling the views and layouts.
4. Location manager: It finds the device’s geographic location.
Applications:
Android applications can be found at the topmost layer. At the application layer, we write
our application to be installed on this layer only. Examples of applications are Games,
Messages, Contacts, etc.

b) Enlist and explain the layers of Android in brief. W18


c) Explain the layers of Android with suitable diagram. W19
The Android stack includes an impressive array of features for mobile applications. In fact, looking at the
architecture alone, without the context of Android being a platform designed for mobile environments, it
would be easy to confuse Android with a general computing environment. All the major components of a
computing platform are there. Here’s a quick rundown of prominent components of the Android stack:

as
15 | Pranay Nandanwar

core services such as process, memory, and filesystem management. The


kernel
is where hardware-specific drivers are implemented—capabilities such as Wi-
Fi
and Bluetooth are here. The Android stack is designed to be flexible, with
many optional components that largely rely on the availability of specific
hardware on a given device. These components include features such as touch
screens, cameras, GPS receivers, and accelerometers.

– Browser technology from WebKit, the same open source engine powering
Mac’s Safari and the iPhone’s Mobile Safari browser. WebKit has become the
de facto standard for most mobile platforms.
– Database support via SQLite, an easy-to-use SQL database.
– Advanced graphics support, including 2D, 3D, animation from Scalable
Games Language (SGL), and OpenGL ES.
– Audio and video media support from PacketVideo’s OpenCORE, and
Google’s own Stagefright media framework.
– Secure Sockets Layer (SSL) capabilities from the Apache project.

– Activities and views – Telephony


– Windows – Resources
– Location-based services

– Core Java packages for a nearly full featured Java programming environment. Note that
this isn’t a Java ME environment.
– The Dalvik VM employs services of the
Linux-based kernel to provide an environment to host Android applications

1 Building on the Linux kernel

Android is built on a Linux kernel and on an advanced, optimized VM for its Java
applications. Both technologies are crucial to Android. The Linux kernel component of
the Android stack promises agility and portability to take advantage of numerous
hardware options for future Android-equipped phones. Android’s Java environment is
key: It makes Android accessible to programmers because of both the number of Java
software developers and the rich environment that Java programming has to offer. Why
use Linux for a phone? Using a

2 Running in the Dalvik VM


The Dalvik VM is an example of the need for efficiency, the desire for a rich programming environment,
and even some intellectual property constraints, colliding, with innovation as the result. Android’s Java
environment provides a rich application platform and is accessible because of the popularity of Java
itself. Also, application performance, particularly in a low-memory setting such as you find in a mob
16 | Pranay Nandanwar

a) What are the types of Android components? Explain. 4 marks W18

App components are the essential building blocks of an Android app. Each component is an
entry point through which the system or a user can enter your app. Some components depend
on others.

There are four types of app components:

 Activities

 Services

 Broadcast receivers

 Content providers

1. Activities
An activity is a class that is considered as an entry point for users that represents a
single screen. A messenger application might have an activity that shows a new
notification, another activity which reads messages and another which composes a
new message.

Each activity is independent of one another. For example – camera application can be
started in an email application to compose an email that shares an image. The picture
below depicts how each new activity adds an item to back stack and how the current
activity is destroyed and previous activity is resumed. We will study the life cycle of
activity in detail in our Android Activity article.
To implement an activity, extend the Activity class in your subclass:

public class MainActivity extends Activity {

//code

2. Services
A service is a component that runs in the background, it acts as an invisible worker of
our application. It keeps updating data sources and activities. It also broadcasts
intents and performs tasks when applications are not active. An example of service is
we can surf the internet or use any other application while listening to music.
To execute services, extend the Services class in your sub-class:

public class MyService extends Services {

//code

3. Content Providers
Content Provider is a component that allows applications to share data among
multiple applications. It hides the details of the database and can be used to read and
17 | Pranay Nandanwar

write private data of the application which is not shared. It would be a mess to access
data from other applications without content providers.
For example – you can consider looking for contact details in contact list. Or You
might want photos from the gallery which are also provided by Content Provider.
To implement this, extend ContentProvider in your subclass:

public class Provider_Name extendsContentProvider {

//code

4. Broadcast Receiver
Broadcast Receiver is a component that responds to broadcast messages from
another application or the same system. It can also deliver broadcasts to applications
that are not running. For example – notify the user that the battery is low. Android
developers can use broadcast messages in the application or outside the normal flow.
To implement this, extend BroadcastReceiver to your receiver:

public class Broadcast_Name extendsBroadcastReceiver {

//code

Additional Components of Android Application

1. Intents
It is an inter-application message passing framework for communication between
android components. It is also used for transferring data between different Activities
as well as to start a new service and display a list of contacts in ListView. Example –
the camera application sends an intent to the operating system when the user decides
to share a picture.

2. Widgets
Widgets are variations of Broadcast Receivers and essential aspects of home screen
customization. They display data and allow users to perform actions on them. There
are various types of widgets:
 Information widget: These widgets display crucial information and track how the
information changes over time. Example – Clock widgets and widgets that
display weather and time information.
 Collection widget: As the name depicts, collection widgets are a collection of
information of the same type. Its use is for browsing information and opening
any one of the elements to view details. Example – music widgets, as we can skip
pause and play music outside the music application.
 Control widget: These widgets display functionalities and by using them, the user
can trigger from home screen without opening the application. Example – pause
and play the video outside the application.
18 | Pranay Nandanwar

 Hybrid widget: These widgets combine features of all the other three widgets.
Example – music player widget is a control widget but it also informs the user
about which track is playing currently, which means it is a combination of control
and information thus it is termed as hybrid widget.
3. Views
 View is responsible for drawing and event handling. They are rectangular
elements on the screen. Some of the views are EditText, ImageView Button,
CheckBox and ImageButton.
 4. Notifications It alerts users when the application is not visible
or is inactive. This alert flashes on the screen and then disappears. Example –
Notification of the new incoming message popped on the screen.
5. Fragments 6. Layout XML Files 7. App APK files 8. Resources

b) What is the purpose of Android Manifest file? Explain the structure of manifest file in brief. S19

b) What is Android Manifest file? Explain essential attributes of Android Manifest file. S18 OLD

The AndroidManifest.xml file contains information of your package, including components of the
application such as activities, services, broadcast receivers, content providers etc.

Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located in the root
directory of its project hierarchy.

The manifest file is an important part of our app because it defines the structure and metadata of our
application, its components, and its requirements.
This file includes nodes for each of the Activities, Services, Content Providers, and Broadcast
Receivers that make the application, and using Intent Filters and Permissions determines how they
coordinate with each other and other applications.
The manifest file also specifies the application metadata, which includes its icon, version number, themes,
etc., and additional top-level nodes can specify any required permissions, and unit tests, and define
hardware, screen, or platform requirements. The manifest comprises a root manifest tag with a package
attribute set to the project’s package. It should also include an xmls:android attribute that will supply
several system attributes used within the file. We use the versionCode attribute is used to define the
current application version in the form of an integer that increments itself with the iteration of the version
due to update. Also, the versionName attribute is used to specify a public version that will be displayed to
the users.

1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2. package="com.javatpoint.hello"
3. android:versionCode="1"
4. android:versionName="1.0" >
5.
6. <uses-sdk
7. android:minSdkVersion="8"
8. android:targetSdkVersion="15" />
9.
10. <application
19 | Pranay Nandanwar

11. android:icon="@drawable/ic_launcher"
12. android:label="@string/app_name"
13. android:theme="@style/AppTheme" >
14. <activity
15. android:name=".MainActivity"
16. android:label="@string/title_activity_main" >
17. <intent-filter>
18. <action android:name="android.intent.action.MAIN" />
19.
20. <category android:name="android.intent.category.LAUNCHER" />
21. </intent-filter>
22. </activity>
23. </application>
24.
25. </manifest>

Elements of the AndroidManifest.xml file


The elements used in the above xml file are described below.

<manifest>

manifest is the root element of the AndroidManifest.xml file. It has package attribute that
describes the package name of the activity class.

<application>

application is the subelement of the manifest. It includes the namespace declaration. This
element contains several subelements that declares the application component such as activity
etc.

The commonly used attributes are of this element are icon, label, theme etc.

android:icon represents the icon for all the android application components.

android:label works as the default label for all the application components.

android:theme represents a common theme for all the android activities.

<activity>

activity is the subelement of application and represents an activity that must be defined in the
AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc.

android:label represents a label i.e. displayed on the screen.


20 | Pranay Nandanwar

android:name represents a name for the activity class. It is required attribute.

<intent-filter>

intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.

<action>

It adds an action for the intent-filter. The intent-filter must have at least one action element.

<category>

It adds a category name to an intent-filter.

Structure of the manifest file

The structure of the file usually takes the form of a code-like instruction and looks usually like
this:

<manifest>

<application>

<activity

android:name="com.example.applicationname.MainActivity">

</activity>

</application>

</manifest>

The following data is contained in the Manifest file:

 The name of the application's package, often known as the namespace of the code. As the
project is being built, this information is utilized to locate the code.
 The component that consists of all the actions, services, recipients, and content providers is
another.
 The permissions that the application needs in order to access the system's and other apps'
protected areas.
 Which devices can download the app from Google Play depends on the functionality that the
app needs. Both hardware and software features are included in these features.
 Additionally, it contains information about the program metadata, such as the icon, version,
themes, etc.

Furthermore, here are some other things it does:

 It selects the processes that will host the various application components.
 It specifies which rights are necessary for the application to communicate with other programs
and access restricted areas of the API.
21 | Pranay Nandanwar

 It includes a list of the instrumentation classes, which offer profiling and other data while the
program is operating. These declarations are deleted from the manifest before the application is
released and are only present there while the application is being built and tested.
 It specifies the Android API level that the application must have at a minimum.
 It also specifies which libraries that the program must be linked against

d) What do you mean by Android emulator? Write and explain the procedure to create Android
emulator S19
d) Write a brief note on Android Emulator and user Interfaces.W18
c) Write a brief note on Android Emulator with suitable example. W17 OLD

The Android emulator is an Android Virtual Device (AVD), which represents a specific
Android device. We can use the Android emulator as a target device to execute and test our
Android application on our PC. The Android emulator provides almost all the functionality of a
real device. We can get the incoming phone calls and text messages. It also gives the location of
the device and simulates different network speeds. Android emulator simulates rotation and
other hardware sensors. It accesses the Google Play store, and much more
The Android SDK provides a virtual mobile device emulator that runs on a computer.
An android emulator is used for executing, debugging, and testing android
applications. The emulator helps the developer to run a trial product virtually without an
actual hardware device. An emulator is similar to a physical hardware mobile device
including all the features that an actual mobile contains except that it cannot place an
actual phone call. The emulator comes with predefined configurations for various
Android phones, tablets, Wear OS, and Android TV devices. Emulator represents a
specific Android device that can be used as a target platform to run and test your
android application on your PC.
It provides navigation control keys along with touchscreen accessibility. On a virtual
device, the cursor can be used as a finger and perform all the functions such as typing,
opening applications, swiping, etc. The Android Emulator runs on a full Android system
stack, down to the kernel level including a set of preinstalled applications that we can
access from our applications.
Android emulator enables us to choose api level and android version of your choice by
configuring AVDs. While launching the emulator at runtime, we can use a variety of
commands and options to control its behavior. The android emulator offers dynamic
binary translation of device machine code to the OS and processor architecture of our
development machine.
The emulator supports various hardware features like:
 ARMv5 CPU AMD corresponding MMU
 A 16-bit LCD Display
 Dialpad\keyboard
 Sound chip
 Flash memory
 GSM modem
 Camera
 Sensors like accelerometers
22 | Pranay Nandanwar

Advantages of Android Emulator

 Transfer of files is faster in virtual devices, as here a file can be transferred through
drag and drop.
 Emulator enables the programmer to work with physical sensors such as
accelerometers, gyroscopes, proximity, etc.
 One can play games, browse the internet, change settings, etc.
 Android emulator enables you to choose any version of your choice and
accordingly, a developer can build an app.
 Developer can check all possible test cases through android emulators.

Disadvantages of Android Emulator

 Android emulator works with slow speed as compared to actual physical devices.
 Emulators cannot recognize the speed and performance of the battery, location,
and hardware-related activities.
 Testing on an emulator is not accurate as you are using a virtual device not an
actual device.
 One cannot identify issues related to networks or notifications on an emulator.
 The emulator crashes at launch if it does not receive enough disk space.
Below is a sample image of how an Android Emulator looks like.

Install the emulator


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

Creating an Android Emulator


An Android emulator is an Android Virtual Device (AVD) that represents a specific
Android device. You can use an Android emulator as a target platform to run and test
your Android applications on your PC.

 Using Android emulators is optional.


 An Android emulator is installed by default during the RAD Studio installation.
 We recommend that you install this emulator during product installation.
 This emulator is used as the default target for an Android application, so you
can easily create and run an Android application on your development system.
 If you create your own Android emulator, consider creating an emulator for each
Android device you want to support.
 RAD Studio supports the following targets:
 Android emulators that are version 4.0 or newer
 Android devices that are ARM version 7 or newer
 You cannot use an Android emulator on a Virtual Machine (VM). Although an
emulator might run on a VM, the emulator will not run an application.
23 | Pranay Nandanwar

 It is a well-known performance issue that Android emulators are extremely slow.


The installed Android emulator is named rsxe5_android, which uses the WVGA800
skin and Android 4.2.2.

a) Explain the different views available in Android development 4 mark S19

A View is a fundamental element for any user interface (or design) in android. View
provides you with a rectangular space that can be used to display, interact or handle
events. The view is a superclass for any graphical components in android. Usually,
each view is rectangular and can hold textual and visual contents. Attached to a view,
there are several attributes that define the property and functionality of that view.

Types of Android Views


Android provides a bunch of views that can be used depending upon the needs of
your application. Some of them are as follows:

 TextView
24 | Pranay Nandanwar

 ImageView
 EditText
 Button
 ImageButton
 ToggleButton
 RadioButton
 RadioGroup
 CheckBox
View

The view is a fundamental UI component that responds to user interactions(touches, clicks, scrolls, etc.).

The view is a superclass for many view elements like TextView, ImageView, Button, etc.

The view belongs to the android.view.View class

A View object is usually a widget, for example, Button, TextView, ImageView, etc.

View, in general, is known as a child view.

Text View:

This class is used to display text on the android application screen. It also allows user to
optionally edit it. Although it contains text editing operations, the basic class does not allow
editing, So Edit Text class is included to do so.

Edit Text:

This class makes text to be editable in Android application. It helps in building the data
interface taken from any user, also contains certain features through which we can hide the
data which are confidential.

Image view:

Image view helps to display images in an android application. Any image can be selected, we
just have to paste our image in a drawable folder from where we can access it. For example:
In below Code “@drawable/ic_laucher” has been taken.
a) Write about app package. S18 (4 marks)
a) Explain app package. 4 W18 OLD

Let us first know the basic meaning of what an Android Application Package actually
is. It is a package that is basically a file format that is used by Android Operating
System. Android OS uses this file format for the distribution and installation of
Android Applications that can be mobile apps or mobile games.
25 | Pranay Nandanwar

Let us begin the tutorial towards the deeper knowledge of Android Application
Packages.

Android Application Package (APK) can be understood as a package file format of


Android Applications. These files are analogous to the many other software packages.
These packages include APPX in MicroSoft Windows or you can consider Deb packages in
Debian based OS like Ubuntu. As we know that any Android Application is built using the
four very important components. The two of those components that are Activities and
Services. Let us recall what Activities and Services are-

An Activity is that application component which provides a visible screen that helps the
users interact with it to perform some operations. For example whatever you see as soon
as you open an app, like upon opening the Call logs you see the recent calls. You can know
more about Activities.

On the other hand, Services are those part of an application that helps the app to
perform long run operations. These are generally performed in the background and do not
need the user interference. For example the songs playing in the background. Or some
updation going on in the background. Learn more about Android Services.

d) Develop an Android Application to display context menu for list view item. S18
d) Develop an Android app to display context menu for List view item W19
c) Develop android application to display context menu for List view item. S18 OLD
Step 1: Create a new Android Studio project with an empty activity.
Step 2: In the activity layout file (activity_main.xml), add a ListView:

xml
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Step 3: In the activity class (MainActivity.java), set up the ListView with some data and register a context
menu for the items:

public class MainActivity extends AppCompatActivity


{
private ListView listView;
26 | Pranay Nandanwar

private String[] data = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);

ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,


data);
listView.setAdapter(adapter);

registerForContextMenu(listView);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo
menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);

getMenuInflater().inflate(R.menu.context_menu, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)
item.getMenuInfo();
String selectedItem = data[info.position];

switch (item.getItemId())
{
27 | Pranay Nandanwar

case R.id.menu_item_delete:
// Delete the selected item
// ...
return true;
case R.id.menu_item_edit:
// Edit the selected item
// ...
return true;
default:
return super.onContextItemSelected(item);
}
}
}
Step 4: Create a new menu file (context_menu.xml) in the "menu" folder and define the context menu
items:
xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_item_delete"
android:title="Delete" />
<item
android:id="@+id/menu_item_edit"
android:title="Edit" />
</menu>
That's it! Now when the user long-presses an item in the ListView, a context menu will be displayed with
the "Delete" and "Edit" options. You can handle these options in the onContextItemSelected method of
the activity class.
a) Differentiate between Assets folder and Drawable folder. 4marks W19
a) What is the difference between Asset and Resource folder? 4 W19 OLD
1. Assets folder:
The Assets folder is used to store arbitrary files, such as text files, fonts, and sound files, that your app
needs to access at runtime. These files can be accessed using the `AssetManager` class, which provides
methods for reading files from the Assets folder. Assets are typically read-only and cannot be changed
at runtime.
28 | Pranay Nandanwar

2. Drawable folder:
The Drawable folder is used to store graphical resources such as images, icons, and XML files that define
drawables. These files can be referenced using the `R.drawable` class, which generates unique IDs for
each drawable in your app. Drawables can be used in layouts, menus, and other UI components.
Here are some key differences between the Assets and Drawable folders:
- Accessing files: The Assets folder provides direct access to files using the `AssetManager` class, while
the Drawable folder provides access to graphical resources using the `R.drawable` class.

- File types: The Assets folder can store any type of file, while the Drawable folder is intended for
graphical resources such as images and icons.

- Naming conventions: The Assets folder does not enforce any naming conventions for files, while the
Drawable folder has specific naming conventions based on the type of drawable (e.g. "ic_launcher.png"
for an app icon).

- Modifying files: Assets are typically read-only and cannot be modified at runtime, while drawables can
be modified dynamically at runtime, for example, by changing the image source of an ImageView.

- Resource management: Drawables are automatically managed by the Android system, which
optimizes them for different screen densities and other configuration changes. Assets, on the other
hand, must be managed manually by your app.

In summary, the Assets folder is used for storing arbitrary files that your app needs to access at runtime,
while the Drawable folder is used for storing graphical resources that can be referenced in layouts and
other UI components.

c) How to map Applications to process? Explain. Also write the steps to create and execute Android
Application. W18

In Android, each application runs in its own process by default, with its own instance of the Android
runtime environment. This is known as the Application Sandbox, which provides a layer of security and
isolation between different apps running on the same device. Mapping an application to a process
involves assigning a unique process ID (PID) to the application and setting up the necessary memory and
resource allocations for the application to run.
When an application is launched, the Android system creates a new process for the application if one
doesn't already exist. The system assigns a unique PID to the process and sets up the necessary memory
and resource allocations for the application to run. The application process runs independently of other
processes on the device and has its own virtual machine (VM) instance, which allows it to run Java code.
To create and execute an Android application, follow these steps:
29 | Pranay Nandanwar

1. Install Android Studio: Android Studio is the official IDE for developing Android applications. You
can download it from the Android Studio website.
2. Create a new project: Open Android Studio and click on "Create New Project". Follow the
prompts to set up a new project with a name, package name, and other project settings.
3. Create a layout: In the "res/layout" directory, create a new XML file for the layout of your app.
This file defines the user interface of your app.
4. Create an activity: In the "java" directory, create a new Java class for your app's main activity.
This class extends the Activity class and contains the logic for your app's behavior.
5. Build and run your app: Use the "Run" button in Android Studio to build and run your app on a
connected device or emulator. Android Studio will automatically compile your code and deploy
the app to the device or emulator.
6. Test and debug your app: Use Android Studio's built-in debugging tools to test and debug your
app. You can set breakpoints, inspect variables, and step through code to find and fix errors in
your app.
7. Publish your app: Once your app is ready, you can publish it to the Google Play Store or other
app stores. Follow the guidelines for app publishing and distribution to ensure that your app
meets the necessary requirements and standards.
In summary, mapping an Android application to a process involves assigning a unique PID to the
application and setting up the necessary memory and resource allocations. To create and execute an
Android application, you need to use Android Studio to create a project, write the code for your app's
user interface and behavior, build and run the app, test and debug it, and publish it to the app store.
b) Write an Android program to demonstrate resources. W19

d) Write an android program to demonstrate resources. W18 OLD

Here is an Android program that demonstrates the use of resources:


1. Create a new Android project in Android Studio.
2. In the res/values folder, create a new XML file named strings.xml.
3. In strings.xml, define some string resources using the <string> element, like this:
php
Copy code
<resources>
<string name="app_name">My App</string>
<string name="welcome_message">Welcome to my app!</string>
</resources>
4. In your app's code, access the string resources using the R.string class, like this:

java
String appName = getResources().getString(R.string.app_name);
30 | Pranay Nandanwar

String welcomeMessage = getResources().getString(R.string.welcome_message);


5. In the res/drawable folder, add an image file (e.g. my_image.png).
6. In your app's layout XML file, use the <ImageView> element to display the image, like this:
xml
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_image" />
7. Run your app and verify that the string resources and image are displayed correctly.
Here's the complete code for an activity that demonstrates the use of resources
public class MainActivity extends AppCompatActivity {

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

String appName = getResources().getString(R.string.app_name);


String welcomeMessage = getResources().getString(R.string.welcome_message);

TextView textView = findViewById(R.id.text_view);


textView.setText(welcomeMessage + " " + appName);
}
}
In this example, we access the app_name and welcome_message string resources using
getResources().getString(). We then display the welcome message and app name in a TextView. The
image resource is displayed using an ImageView element with the android:src attribute set to
@drawable/my_image. When the app runs, the string resources and image should be displayed
correctly in the UI.
31 | Pranay Nandanwar

UNIT 2
c) Explain the following. i) Action Bad ii) Alarm Manager iii) Alert Dialog iv) Fragment S18
. i) Action Bad

The ActionBar, now known as the App Bar, is a consistent navigation element that is standard
throughout modern Android applications. The ActionBar can consist of:

 An application icon
 An "upward" navigation to logical parent
 An application or activity-specific title
 Primary action icons for an activity
 Consistent navigation (including navigation drawer)

In Android applications, ActionBar is the element present at the top of the activity screen. It is a salient feature of
a mobile application that has a consistent presence over all its activities. It provides a visual structure to the app
and contains some of the frequently used elements for the users. Android ActionBar was launched by Google in
2013 with the release of Android 3.0(API 11). Before that, the name of this top most visual element was AppBar.
AppBar contains only the name of the application or current activity. It was not very much useful for the users
and developers also have negligible option to customize it.
Google announced a support library along with the introduction of ActionBar. This library is a part
of AppCompat and its purpose is to provide backward compatibility for older versions of Android and to support
tabbed interfaces. All applications that use the default theme provided by the
Android(Theme.AppCompat.Light.DarkActionBar), contains an ActionBar by default. However, developers can
customize it in several ways depending upon their needs. Components included in the ActionBar are:
 App Icon: Display the branding logo/icon of the application.
 View Controls: Section that displays the name of the application or current activity. Developers can also
include spinner or tabbed navigation for switching between views.
 Action Button: Contains some important actions/elements of the app that may be required to the users
frequently.
 Action Overflow: Include other actions that will be displayed as a menu.

Android AlarmManager
Android AlarmManager allows you to access system alarm.

By the help of Android AlarmManager in android, you can schedule your application to run at a
specific time in the future. It works whether your phone is running or not.

The Android AlarmManager holds a CPU wake lock that provides guarantee not to sleep the
phone until broadcast is handled.

Android AlarmManager is a class that provides access to alarm services of the


system. Through this, it lets us schedule the application to run at a particular time. As
soon as the alarm goes off, the system broadcasts the intent registered for it. The
wake lock of the CPU is held by the AlarmManager till the alarm
receiver’s onReceive() method is in execution. This thing ensures that the device does
not sleep until the broadcast is handled.
Alarms basically give us the way to perform time-based operations. Basically, an alarm
has characteristics which are given below:
32 | Pranay Nandanwar

 They fire intents at particular time intervals or at a particular time.


 They have the ability to run outside the application as well, this enables the alarm
to trigger the event even if the application is not running, or the device is asleep.
 They can be used along with the broadcast receivers, to perform a particular
action or to start services.
 They help in minimizing the resource requirements.
 They will execute until and unless they are force stopped or the device restarts.
Ways to invoke Alarm Manager in Android
1. setInExactAndRepeating: This type of AlarmManager does not trigger the alarm at
the exact time.
2. setExact: This type of AlarmManager ensures that the system triggers the alarm at
an exact time.
3. setExactAndAllowWhileIdle: This type of AlarmManager is allowed to be executed,
even in low power modes of devices.
We will move on to implement it in our application without any delay.

Android AlertDialog
In android, AlertDialog is used to prompt a dialog to the user with messages and buttons to perform an
action to proceed further.

The AlertDialog in an android application will contain three regions like as shown below.

In android Alert Dialogs, we can show a title, up to three buttons, a list of selectable items or a custom
layout based on our requirements.

Region Description

Title It’s optional and it can be used to show the detailed messages based on our
requirements.

Content It is used to display a message, list or other custom layouts based on our
Area requirements.
33 | Pranay Nandanwar

Region Description

Action It is used to display action buttons to interact with users. We can use upto 3
Buttons different action buttons in alert dialogs, such as positive, negative and neutral.

Generally, in android we can build AlertDialog in our activity file using different dialog methods.

Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It
can be used to interrupt and ask the user about his/her choice to continue or discontinue.

Android AlertDialog is composed of three regions: title, content area and action buttons.

Android AlertDialog is the subclass of Dialog class.

Methods of AlertDialog class

Method Description

public AlertDialog.Builder This method is used to set the title of


setTitle(CharSequence) AlertDialog.

public AlertDialog.Builder This method is used to set the message


setMessage(CharSequence) for AlertDialog.

public AlertDialog.Builder setIcon(int) This method is used to set the icon over
AlertDialog.
b) Write about fragment Instantiate exception. 4 W19

b) Write and explain fragment Instantiate Exception. 4 S18 old

Android Fragment is the part of activity, it is also known as sub-activity. There can be more than
one fragment in an activity. Fragments represent multiple screen inside one activity.

Android fragment lifecycle is affected by activity lifecycle because fragments are included in
activity.

Each fragment has its own life cycle methods that is affected by activity life cycle because
fragments are embedded in activity.

The FragmentManager class is responsible to make interaction between fragment objects.

A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong
if we say, a fragment is a kind of sub-activity.
Following are important points about fragment −
 A fragment has its own layout and its own behaviour with its own life cycle callbacks.
 You can add or remove fragments in an activity while the activity is running.
34 | Pranay Nandanwar

 You can combine multiple fragments in a single activity to build a multi-pane UI.
 A fragment can be used in multiple activities.
 Fragment life cycle is closely related to the life cycle of its host activity which means when
the activity is paused, all the fragments available in the activity will also be stopped.
 A fragment can implement a behaviour that has no user interface component.
 Fragments were added to the Android API in Honeycomb version of Android which API
version 11.
You create fragments by extending Fragment class and You can insert a fragment into your
activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.
Prior to fragment introduction, we had a limitation because we can show only a single activity on
the screen at one given point in time. So we were not able to divide device screen and control
different parts separately. But with the introduction of fragment we got more flexibility and
removed the limitation of having a single activity on the screen at a time. Now we can have a
single activity but each activity can comprise of multiple fragments which will have their own
layout, events and complete life cycle.
Following is a typical example of how two UI modules defined by fragments can be combined into
one activity for a tablet design, but separated for a handset design.

Fragment Life Cycle


Android fragments have their own life cycle very similar to an android activity. This section briefs
different stages of its life cycle.

Fragment lifecycle
Here is the list of methods which you can to override in your fragment class −
 onAttach()The fragment instance is associated with an activity instance.The fragment and
the activity is not fully initialized. Typically you get in this method a reference to the activity
which uses the fragment for further initialization work.
 onCreate() The system calls this method when creating the fragment. You should initialize
essential components of the fragment that you want to retain when the fragment is paused
or stopped, then resumed.
 onCreateView() The system calls this callback when it's time for the fragment to draw its
user interface for the first time. To draw a UI for your fragment, you must return
a View component from this method that is the root of your fragment's layout. You can
return null if the fragment does not provide a UI.
 onActivityCreated()The onActivityCreated() is called after the onCreateView() method
when the host activity is created. Activity and fragment instance have been created as well
as the view hierarchy of the activity. At this point, view can be accessed with the
findViewById() method. example. In this method you can instantiate objects which require
a Context object
35 | Pranay Nandanwar

 onStart()The onStart() method is called once the fragment gets visible.


 onResume()Fragment becomes active.
 onPause() The system calls this method as the first indication that the user is leaving the
fragment. This is usually where you should commit any changes that should be persisted
beyond the current user session.
 onStop()Fragment going to be stopped by calling onStop()
 onDestroyView()Fragment view will destroy after call this method
 onDestroy()onDestroy() called to do final clean up of the fragment's state but Not
guaranteed to be called by the Android platform.
Types of Fragments
Basically fragments are divided as three stages as shown below.
 Single frame fragments − Single frame fragments are using for hand hold devices like
mobiles, here we can show only one fragment as a view.
 List fragments − fragments having special list view is called as list fragment
 Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment.
 Content Providers are an important component of Android. They handle the
access to the central repository and supply data from one application to
another on request. This task of handling is done by methods
of ContentResolver class. So, content providers can store data in various ways
such as files, database or over the internet.
 Many a time we need to share our data with applications and that’s where it
becomes useful. The following diagram depicts how the content
provider helps in sharing data with applications from data stores.


 c) Write a note on content provider classes in Android. S19
 b) Write a brief note on Android's content provider classes. W18
 a) Discuss content provider class and its methods. W19
 b) Explain the content provider classes in detail. W17 OLD
 a) Define Intent. Explain content provider classes in detail. W18 OL

As can be seen, the content provider lets us collect the data centrally and provide
them to applications as shown in the above diagram. Content providers act the same
as database and also we can query it to add, delete, insert or update the data.

It can be understood that a content provider hides the database details and also, it
lets an application share data among other applications. Content providers are not
limited to texts, but also contains images and videos as well.

CRUD Operations
Content providers provide the following four basic operations. These are also known
as CRUD operations, where
36 | Pranay Nandanwar

C – Create
R – Read
U – Update
D – Delete
The above are the four operations of content providers :

 Create: It is used for the creation of data in content providers.


 Read: It reads the data stored in the content provider.
 Update: It lets the editing in existing data in content providers.
 Delete: It deletes the existing data stored in its Storage.
Examples of Android Content Providers

To understand content providers with examples, consider the following examples :

 The Gallery that contains images.


 Contact lists that contain Contact details.
 A dictionary that has collections of all the words that are used.
 The music playlist has a list of songs.
 Call logs contain the call details.
Methods of Content Provider in Android

Let’s see the following methods of content provider:

 onCreate() – This method in Android initializes the provider as soon as the


receiver is created.
 query() – It receives a request in the form of a query from the user and responds
with a cursor in Android.
 insert() – This method is used to insert the data into our content provider.
 update() – This method is used to update existing data in a row and return the
updated row data.
 delete() – This method deletes existing data from the content provider.
 getType() – It returns the Multipurpose Internet Mail Extension type of data to
the given Content URI.
Content URIs
Content URIs are the uniform resource identifiers that identify the data in the
content providers. A content URI includes two things: Authority that is the symbolic
name of the Provider and a Path that is a name that points towards the data. Every
content provider methods have an argument which is URI.
Let’s understand the Content Provider URI:

content://<authority>/<path>/<optional_id>

 content:// – It’s always present, and is the scheme portion of the URI.
37 | Pranay Nandanwar

 authority – It is the unique name of the content provider, like photos, contacts.
It’s a string that can identify the whole content provider.
 path – It is often used to identify some or the other data of the provider. The path
is mostly used to identify individual tables.
 optional_id – id is used to access a single particular record of a file. We use this
only in cases where we need to access only a particular record and not the
complete file. It’s a numeric identifier to access a particular row of the data table.
Content provider also has two wildcards which are:

1. * – Asterisk (*) is used to match valid characters irrespective of their length.


2. # – Hash (#) is used to match valid numerals irrespective of their length.
Working of the Content Provider
UI components of android applications like Activity and Fragments use an
object CursorLoader to send query requests to ContentResolver. The
ContentResolver object sends requests (like create, read, update, and delete) to
the ContentProvider as a client. After receiving a request, ContentProvider process it
and returns the desired result. Below is a diagram to represent these processes in
pictorial form.

d) Explain the following Terms: i) Notification in Android. ii) Alarms in Android. S19

Notification is a kind of message, alert, or status of an application (probably running


in the background) that is visible or available in the Android’s UI elements. This
application could be running in the background but not in use by the user. The purpose
of a notification is to notify the user about a process that was initiated in the application
either by the user or the system. This article could help someone who’s trying hard to
create a notification for developmental purposes.
Notifications could be of various formats and designs depending upon the developer.
In General, one must have witnessed these four types of notifications:
1. Status Bar Notification (appears in the same layout as the current time, battery
percentage)
2. Notification drawer Notification (appears in the drop-down menu)
3. Heads-Up Notification (appears on the overlay screen, ex: Whatsapp notification,
OTP messages)
4. Lock-Screen Notification (I guess you know it)
38 | Pranay Nandanwar

Set Android Notification Properties


The properties of Android notification are set using NotificationCompat.Builder object. Some
of the notification properties are mention below:

o setSmallIcon(): It sets the icon of notification.


o setContentTitle(): It is used to set the title of notification.
o setContentText(): It is used to set the text message.
o setAutoCancel(): It sets the cancelable property of notification.
o setPriority(): It sets the priority of notification.

How notifications may be noticed

 Showing a status bar icon


 Appearing on the lock screen
 Playing a sound or vibrating
 Peeking onto the current screen
 Blinking the device's LED

a) Explain Broadcast Receivers in brief with suitable example. W18


a) List and explain the method for broadcasting intents. Write an activity file which demonstrate any one method
of broadcast intent. 8 S18

Broadcast in android is the system-wide events that can occur when the device starts,
when a message is received on the device or when incoming calls are received, or when
a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these
system-wide events. Broadcast Receivers allow us to register for the system and
application events, and when that event happens, then the register receivers get notified.
There are mainly two types of Broadcast Receivers:
 Static Broadcast Receivers: These types of Receivers are declared in the manifest
file and works even if the app is closed.
39 | Pranay Nandanwar

 Dynamic Broadcast Receivers: These types of receivers work only if the app is
active or minimized.
Since from API Level 26, most of the broadcast can only be caught by the dynamic
receiver, so we have implemented dynamic receivers in our sample project given below.
There are some static fields defined in the Intent class which can be used to broadcast
different events. We have taken a change of airplane mode as a broadcast event, but
there are many events for which broadcast register can be used. Following are some of
the important system-wide generated intents:-
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system itself. These messages are sometime called events or intents. For example,
applications can also initiate broadcasts to let other applications know that some data has been
downloaded to the device and is available for them to use, so this is broadcast receiver who will
intercept this communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
 Creating the Broadcast Receiver.
 Registering Broadcast Receiver
 There is one additional steps in case you are going to implement your custom intents then
you will have to create and broadcast those intents.

 Creating the Broadcast Receiver


 A broadcast receiver is implemented as a subclass of BroadcastReceiver class and
overriding the onReceive() method where each message is received as a Intent object
parameter.
 public class MyReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
 Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
 }
 }
 Registering Broadcast Receiver
 An application listens for specific broadcast intents by registering a broadcast receiver
in AndroidManifest.xml file. Consider we are going to register MyReceiver for system
generated event ACTION_BOOT_COMPLETED which is fired by the system once the
Android system has completed the boot process.


40 | Pranay Nandanwar

 Broadcast-Receiver
 <application
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <receiver android:name="MyReceiver">

 <intent-filter>
 <action android:name="android.intent.action.BOOT_COMPLETED">
 </action>
 </intent-filter>

 </receiver>
 </application>
 Now whenever your Android device gets booted, it will be intercepted by
BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be
executed.
 There are several system generated events defined as final static fields in the Intent class.
The following table lists a few important system events.
 Creating the Broadcast Receiver:
 class AirplaneModeChangeReceiver:BroadcastReceiver() {
 override fun onReceive(context: Context?, intent: Intent?) {
 // logic of the code needs to be written here
 }
 }

 Registering a BroadcastReceiver:
 IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
 // receiver is the broadcast receiver that we have registered
 // and it is the intent filter that we have created
 registerReceiver(receiver,it)
 }
41 | Pranay Nandanwar

c) What is server socket? Explain communicating with a server socket. W19


c) What is server socket? Explain communicating with a server socket. W17 OLD

Communicating with a server socket


A server socket is a stream that you can read or write raw bytes to, at a specified IP address
and port. This lets you deal with data and not worry about media types, packet sizes, and so on.
This is yet another network abstraction intended to make the job of the programmer a bit easier.
The philosophy that sockets take on, that everything should look like file I/O to the developer,
comes from the POSIX family of standards and has been adopted by most major operating
systems in use today.

We will move on to higher levels of network communication in a bit, but first we will start with a
raw socket. For that we need a server listening on a particular port. The EchoServer code
shown in listing 6.2 fits the bill. This isn't an Android-specific class; rather it's just an
oversimplified server that can run on any host machine with Java. We'll later connect to it from
an Android client.

EchoServer code shown in the next listing fits the bill. This example isn’t an Androidspecific class; rather, it’s an
oversimplified server that can run on any host machine with Java. We’ll connect to it later from an Android client.

b) What is BROADCAST_STICKY permission. 4 S18

Android apps and the Android system can use broadcasts as a messaging system to notify other apps of
events that they might be interested in. Sticky broadcasts are a special type of broadcast for which the
sent intent object(s) remains in the cache after the broadcast is complete. The system may re-broadcast
sticky intents to later registrations of receivers. Unfortunately, the sticky broadcasts API suffers from a
number of security-related shortcomings, which is why it was deprecated in Android 5.0 (API level 21).

Anyone can access sticky broadcasts

Sticky broadcasts cannot be restricted to receivers that hold certain permissions. Therefore, they
aren’t suitable for broadcasting sensitive information. It might be tempting to think that
specifying the application package name on the broadcast Intent limits the set
of BroadcastReceivers:
42 | Pranay Nandanwar

KotlinJava

Intent intent = new Intent("com.example.NOTIFY");


intent.setPackage("com.example.myapp");
getApplicationContext().sendBroadcast(intent);

In the example, only receivers in the com.example.myapp package receive the intent when the
broadcast is sent. However, the package name filter isn’t applied when the Intent is re-
broadcast from the sticky cache. When registering a receiver using the registerReceiver() method,
all intents in the sticky cache that match the specified filter are re-broadcast to the receiver
regardless of the package name in which the receiver resides.

Anyone can send sticky broadcasts

To send sticky broadcasts, an app only requires


the android.permission.BROADCAST_STICKY permission, which is granted automatically when the
app is installed. Therefore, attackers can send any intent to any receiver, potentially gaining
unauthorized access to another app. Broadcast receivers can restrict the senders to those
holding a certain permission. However, by doing so, the receiver can’t receive broadcasts from
the sticky cache because those are not sent in the context of any app’s identity and aren’t
broadcast with any permissions.

Anyone can modify sticky broadcasts

When an intent is part of a sticky broadcast, that intent replaces any previous instance that has
the same action, data, type, identifier, class, and categories in the sticky cache. Therefore, an
attacker can trivially overwrite the extra data in a sticky intent from a legitimate app, which
might then get re-broadcast to other receivers.

Broadcasts sent using the sendStickyOrderedBroadcast() method are delivered to one receiver at a
time to allow receivers with higher priority to consume the broadcast before it’s delivered to
receivers with lower priority. As each receiver executes in turn, it can propagate a result to the
next receiver, such as by calling setResultData(), or it can abort the broadcast, preventing
subsequent receivers from receiving the broadcast. An attacker that can receive sticky ordered
broadcasts from a legitimate app can create a high-priority receiver to tamper with the
broadcast result data or drop broadcasts completely.

Impact

Impact varies depending on how sticky broadcasts are used and what data is passed to the
broadcast receivers.

Mitigations

Sticky broadcasts shouldn’t be used. The recommended pattern is to use non-sticky broadcasts
with another mechanism, such as a local database, to retrieve the current value whenever
desired.
43 | Pranay Nandanwar

A toast provides simple feedback about an operation in a small popup. It only fills the amount
of space required for the message and the current activity remains visible and interactive. Toasts
automatically disappear after a timeout.

For example, clicking Send on an email triggers a "Sending message..." toast, as shown in the
following screen capture:

If your app targets Android 12 (API level 31) or higher, its toast is limited to two lines of text and
shows the application icon next to the text. Be aware that the line length of this text varies by
screen size, so it's good to make the text as short as possible.

A Toast is a feedback message. It takes a very little space for displaying while the
overall activity is interactive and visible to the user. It disappears after a few seconds.
It disappears automatically. If the user wants a permanently visible message,
a Notification can be used. Another type of Toast is custom Toast, in which images
can be used instead of a simple message.

Constants of Toast class

There are only 2 constants of Toast class which are given below.

Constant Description

public static final int LENGTH_LONG displays view for the long duration of time.

public static final int displays view for the short duration of
LENGTH_SHORT time.

Instantiate a Toast object

Methods of Toast class

The widely used methods of Toast class are given below.

Method Description

public static Toast makeText(Context context, makes the toast containing text and
CharSequence text, int duration) duration.
44 | Pranay Nandanwar

public void show() displays toast.

public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.

d) Explain in brief the working with HTTP and web services of Android. W18
d) What are web services? Explain how HTTP and web services works. S18 old
b) What is web services? 4 W19 OLD
c) What is web services? Write any three packages of web services. S19 OLD
b) Write a note on web services associated with Android in detail. 4 S19

Working with HTTP

HTTP (Hypertext Transfer Protocol) is the foundation of communication on the World Wide Web.

you can use a raw socket to transfer IP data to and from a server with Android. The most common way to do this
is to use a web server and leverage HTTP. Now we’re going to take a look at making HTTP requests from an
Android client and sending them to an HTTP server. We’ll let the HTTP server handle all the socket details, and
we’ll focus on our client Android application.

Here we’re going to use some of the most common methods and concepts to talk to network resources from
Android applications

When the helper class is in place, we’ll use it to make additional HTTP and HTTPS requests, both GET and POST,
and we’ll look at basic authentication.

Our first HTTP request will be an HTTP GET call using an HttpUrlConnection.

Robust HTTP with HttpClient

To get started with HttpClient, we’re going to look at using core classes to perform HTTP GET and POST method
requests. We’re going to concentrate on making network requests in a Thread separate from the UI, using a
combination of the Apache ResponseHandler and Android Handler (for different but related purposes,

Creating an HTTP and HTTPS helper


45 | Pranay Nandanwar

The next Activity in our NetworkExplorer application, which is shown in listing 6.6, is a lot more straightforward
and Android-focused than our other HTTP-related classes up to this point. We’ve used the helper class we
mentioned previously,

Web services
The term web services means many different things, depending on the source and the audience.

Web services are the type of API that typically runs over HTTP/HTTPS

Web services are a means of exposing an API over a technology-neutral network endpoint. They’re a means to
call a remote method or operation that’s not tied to a specific platform or vendor and get a result. By this
definition, POX over the network is included; so are REST and SOAP—and so is any other method of exposing
operations and data on the wire in a neutral manner.

POX, REST, and SOAP are by far the most common web services around, so they’re what we’ll focus on in this
section.

The two main types of APIs used for web service that runs over the Internet and typically use
HTTP/HTTPS are SOAP and REST.

6.5.1 POX—Putting it together with HTTP and XML


SOAP (Simple Object Access Protocol)
SOAP stands for “Simple Object Access Protocol.” It is a transport-independent
messaging protocol. SOAP is built on sending XML data in the form of SOAP
Messages. A document known as an XML document is attached to each message.
Only the structure of the XML document, not the content, follows a pattern. The best
thing about Web services and SOAP is that everything is sent through HTTP, the
standard web protocol.
A root element known as the element is required in every SOAP document. In an XML
document, the root element is the first element. The “envelope” is separated into two
halves. The header comes first, followed by the body. The routing data, or information
that directs the XML document to which client it should be sent to, is contained in the
header. The real message will be in the body.
46 | Pranay Nandanwar

REST(Representational State Transfer Protocol)

Any Web Service that is defined on the Principle of REST uses HTTP verbs of getting, POST,
PUT, and DELETE.

REST allocates resources on URL and acts. it allows multiple web service-based systems to
interact and communicate with them.

SOAP REST
1. This is a function-based protocol. 1. This is Database based Protocol.
2. It only uses XML. 2. This Permit HTTP,plain
3. It can't be cached. text,XML,JSON
4. It has a strict communication 3. It can be Cached.
5. Build-in ACID compliance. 4. It has an easy communication
6. used in banking applications where security 5. Lack of ACID compliance
is prior. 6. It is advance and simple
 Functions of Web Services
 It’s possible to access it via the internet or intranet networks.
 XML messaging protocol that is standardized.
 Operating system or programming language independent.
 Using the XML standard, it is self-describing.
 A simple location approach can be used to locate it.

b) How to persist Data to a Database? Explain. 4 W18

Persisting data to a database

Android conveniently includes a built-in relational database.1 SQLite doesn’t have all the features of
larger client/server database products, but it includes everything you need for local data storage. At the
same time, it’s quick and relatively easy to work with.

SQLite database system, from creating and querying a database to upgrading and working with the
sqlite3 tool available in the adb shell.

Building and accessing a database

To use SQLite, you have to know a bit about SQL in general. If you need to brush up on the background
of the basic commands, such as CREATE, INSERT, UPDATE, DELETE, and SELECT,

Using the sqlite3 tool

When you create a database for an application in Android, it creates files for that database on the
device in the /data/data/[PACKAGE_NAME]/database/db.name location. These files are SQLite
proprietary, but you can manipulate, dump, restore, and work with your databases through these files
in the adb shell by using the sqlite3 tool.

c) Write a program to build Android Application to demonstrate Intents of Android. (Write . xml and
.Java coadding) W18
47 | Pranay Nandanwar

This app has two activities: MainActivity and SecondActivity. When the user clicks a button in the MainActivity, it
sends an intent to the SecondActivity, passing a message as an extra. The SecondActivity displays the message in
a TextView.

1. Create a new Android Studio project with an empty activity named MainActivity.

2. Open the layout file for the MainActivity (activity_main.xml) and add a button to the layout:

```xml

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Send Intent"

android:onClick="sendMessage" />

```

3. Open the MainActivity class (MainActivity.java) and add the following method to handle the button click:

```java

public void sendMessage(View view)

Intent intent = new Intent(this, SecondActivity.class);

String message = "Hello from MainActivity!";

intent.putExtra("EXTRA_MESSAGE", message);

startActivity(intent);

```

This method creates a new intent with the SecondActivity class and adds a message as an extra to the intent.
Then, it starts the SecondActivity.

4. Create a new activity named SecondActivity and add a TextView to the layout file (activity_second.xml):

```xml

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="TextView" />

```

5. Open the SecondActivity class (SecondActivity.java) and add the following code to retrieve the message from
the intent and display it in the TextView:
48 | Pranay Nandanwar

```java

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_second);

Intent intent = getIntent();

String message = intent.getStringExtra("EXTRA_MESSAGE");

TextView textView = findViewById(R.id.textView);

textView.setText(message);

```

This code retrieves the intent that started the activity and retrieves the message extra. Then, it sets the text of
the TextView to the message.

6. Run the application on an emulator or physical device and click the "Send Intent" button in the MainActivity.
The SecondActivity should open and display the message.

b) Write an android application for implementing the context menu (Floating list of Menu Items) S18
1. Create a new Android Studio project with an empty activity named MainActivity.

2. Open the layout file for the MainActivity (activity_main.xml) and add a TextView to the layout:

```xml

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Long press this text to show context menu" />

3. Open the MainActivity class (MainActivity.java) and add the following code to register the TextView for the
context menu:

```java

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

TextView textView = findViewById(R.id.textView);

registerForContextMenu(textView);
49 | Pranay Nandanwar

This code retrieves the TextView from the layout and registers it for the context menu.

4. Override the onCreateContextMenu() method to create the context menu:

```java

@Override

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

getMenuInflater().inflate(R.menu.context_menu, menu);

This code creates a new menu by inflating a menu resource (context_menu.xml) and adds it to the context menu.

5. Create a new menu resource file (context_menu.xml) and add menu items to it

```xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item

android:id="@+id/menu_item_1"

android:title="Menu Item 1" />

<item

android:id="@+id/menu_item_2"

android:title="Menu Item 2" />

<item

android:id="@+id/menu_item_3"

android:title="Menu Item 3" />

</menu>

This code creates a menu with three items.

6. Override the onContextItemSelected() method to handle the menu item selection:

```java

@Override

public boolean onContextItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.menu_item_1:

// Handle menu item 1

return true;
50 | Pranay Nandanwar

case R.id.menu_item_2:

// Handle menu item 2

return true;

case R.id.menu_item_3:

// Handle menu item 3

return true;

default:

return super.onContextItemSelected(item);

This code switches on the selected menu item and handles each case.

7. Run the application on an emulator or physical device and long press the TextView to show the context menu.
The menu should appear with the three menu items.

d) Write a sample program to create a progress bar for your android application. S18
1. Create a new Android Studio project with an empty activity named MainActivity.

2. Open the layout file for the MainActivity (activity_main.xml) and add a ProgressBar to the layout:

```xml

<ProgressBar

android:id="@+id/progressBar"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true" />

```

This code creates a new ProgressBar and centers it in the layout.

3. Open the MainActivity class (MainActivity.java) and add the following code to retrieve the ProgressBar from
the layout and update its progress:

```java

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ProgressBar progressBar = findViewById(R.id.progressBar);

progressBar.setMax(100);

progressBar.setProgress(50);

}
51 | Pranay Nandanwar

This code retrieves the ProgressBar from the layout, sets its maximum value to 100, and sets its current progress
to 50.

4. Run the application on an emulator or physical device and the ProgressBar should appear in the center of the
layout with the progress set to 50%.

a) Write a program in Android to demonstrate implicit Intent. (note : write .java and .xml code) S19

1. Create a new Android Studio project with an empty activity named MainActivity.

2. Open the layout file for the MainActivity (activity_main.xml) and add a Button to the layout:

```xml

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Open Browser" />

This code creates a new Button with text "Open Browser".

3. Open the MainActivity class (MainActivity.java) and add the following code to handle the Button click and start
the implicit intent:

```java

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String url = "https://www.google.com";

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

startActivity(intent);

});
52 | Pranay Nandanwar

This code retrieves the Button from the layout and adds an OnClickListener to handle its click event. When the
Button is clicked, an implicit intent is created to open the Google homepage in a web browser.

4. Run the application on an emulator or physical device and click the Button to open the browser and navigate
to the Google homepage.

Sure, here's an example Android application that opens a new activity on button click:

b) Create an app to open new activity on Button click. W19(IMPortant 2023)


b) Create an app to open new activity on Button click. W18 OLD
b) Develop an Android application to open new activity on Button click. S18 old
1. Create a new Android Studio project with an empty activity named MainActivity.

2. Open the layout file for the MainActivity (activity_main.xml) and add a Button to the layout:

```xml

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Open Activity 2" />

```

This code creates a new Button with text "Open Activity 2".

3. Create a new activity named SecondActivity by right-clicking on the app folder in the project view, selecting
New -> Activity -> Empty Activity and naming it SecondActivity.

4. Open the layout file for the SecondActivity (activity_second.xml) and add a TextView to the layout:

```xml

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Second Activity" />

This code creates a new TextView with text "Second Activity".

5. Open the MainActivity class (MainActivity.java) and add the following code to handle the Button click and start
the SecondActivity:

```java

@Override

protected void onCreate(Bundle savedInstanceState) {


53 | Pranay Nandanwar

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Intent intent = new Intent(MainActivity.this, SecondActivity.class);

startActivity(intent);

});

This code retrieves the Button from the layout and adds an OnClickListener to handle its click event. When the
Button is clicked, a new explicit intent is created to open the SecondActivity, and then started using the
startActivity() method.

6. Run the application on an emulator or physical device and click the Button to open the SecondActivity, which
should display the text "Second Activity" in the center of the screen.

d) Create and activity file that will trigger the notification.W19

c) Create an activity file that will trigger the notification. S18 old

1. Create a new Android Studio project with an empty activity named MainActivity.

2. Create a new activity named NotificationActivity by right-clicking on the app folder in the project view,
selecting New -> Activity -> Empty Activity and naming it NotificationActivity.

3. Open the layout file for the NotificationActivity (activity_notification.xml) and add a Button to the layout:

```xml

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Trigger Notification" />

This code creates a new Button with text "Trigger Notification".

4. Open the NotificationActivity class (NotificationActivity.java) and add the following code to handle the Button
click and trigger a notification:

```java

@Override
54 | Pranay Nandanwar

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_notification);

Button button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

NotificationCompat.Builder builder = new NotificationCompat.Builder(NotificationActivity.this,


"channel_id")

.setSmallIcon(R.drawable.ic_notification)

.setContentTitle("My Notification")

.setContentText("This is my notification.")

.setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(NotificationActivity.this);

notificationManager.notify(1, builder.build());

});

This code retrieves the Button from the layout and adds an OnClickListener to handle its click event. When the
Button is clicked, a new notification is created using the NotificationCompat.Builder class and then triggered
using the NotificationManagerCompat class.

5. Run the application on an emulator or physical device, navigate to the NotificationActivity, and click the Button
to trigger the notification, which should display the title and content text in the notification bar.
55 | Pranay Nandanwar

UNIT 3
c) Write short note on Open core. 4 S18

c) What is open core? Explain 4 S18 OLD

c) Write a detail note on Multimedia and open core in Android. S19

Since the foundation of Android's multimedia platform is PacketVideo's OpenCORE, in this


section we will review OpenCORE's architecture and services. OpenCORE is a Java open
source multimedia platform supporting the following:

■ Interfaces for third-party and hardware media codecs, input and output devices, and content
policies

■ Media playback, streaming, downloading, and progressive playback, including 3GPP, MPEG-
4, AAC, and MP3 containers

■ Video and image encoders and decoders, including MPEG-4, H.263, and AVC (H.264), and
JPEG

■ Speech codecs, including AMR-NB and AMR-WB

■ Audio codecs, including MP3, AAC, and AAC+

■ Media recording, including 3GPP, MPEG-4, and JPEG

■ Video telephony based on the 324-M standard

■ PV test framework to ensure robustness and stability; profiling tools for memory and CPU
usage

OpenCORE provides all this functionality in a well-laid-out set of services, which are
diagrammed in figure 10.1.

NOTE The current Android SDK does not support video recording via the API. Video recording
is still possible but is specific to the phone vendor.

As you can see from figure 10.1, OpenCORE's architecture has excellent support for
multimedia and numerous codecs. In the next section we are going to dive right in and use the
Android API to play audio files.

10.2 Playing audio

Probably the most basic need for multimedia on a cell phone is the ability to play

audio files, whether new ringtones, MP3s, or quick audio notes. Android’s Media

Player is easy to use. At a high level, all you need to do to play back an MP3 file is follow these steps:
56 | Pranay Nandanwar

1 Put the MP3 in the res/raw directory in a project (note that you can also use aURI to access files on the network
or via the internet).

2 Create a new instance of the MediaPlayer and reference your MP3 by calling

MediaPlayer.create().

3 Call the MediaPlayer methods prepare() and start().

10.3 Playing video

Playing a video is slightly more complicated than playing audio with the MediaPlayer API, in part because you

have to provide a view surface for your video to play on.

Android has a VideoView widget that handles that task

for you; you can use it in any layout manager.

10.3 Playing video

Playing a video is slightly more complicated than playing audio with the MediaPlayer API, in part because you
have to provide a view surface for your video to play on.

Android has a VideoView widget that handles that task for you; you can use it in any layout manager.

10.4 Capturing Audio

10.5 Recording Video

c) Explain the following. i) getAllocationByteCount() ii) hasMipMap() iii) setHasMipMap() S18

d) Explain i) GetAllocationByteCount( ) ii) hasMipMap( ) W18 OLD

. i) getAllocationByteCount()

`getAllocationByteCount()` is a method in the Android SDK's `Bitmap` class that returns the total size in
bytes of the allocated memory used by the bitmap. This method was added in Android API level 19.
Here's an example usage of `getAllocationByteCount()`:
57 | Pranay Nandanwar

```java
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
int byteCount = bitmap.getAllocationByteCount();
Log.d(TAG, "Bitmap size: " + byteCount + " bytes");
In this example, the `BitmapFactory` class is used to decode an image resource into a `Bitmap` object.
The `getAllocationByteCount()` method is then called on the `Bitmap` object to get the total size in
bytes of the allocated memory used by the bitmap. The result is logged to the console using `Log.d()`.

Note that `getAllocationByteCount()` returns the size of the allocated memory used by the bitmap,
which may be larger than the size of the bitmap's pixel data. This is because the `Bitmap` class stores
additional metadata and padding to optimize memory access.
ii) hasMipMap()
`hasMipMap()` is a method in the Android SDK's `Bitmap` class that returns a boolean value indicating
whether the bitmap has a mip-map. A mip-map is a pre-calculated set of scaled-down versions of an
image, which can be used to improve rendering performance and reduce aliasing artifacts.
Here's an example usage of `hasMipMap()`:
```java
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
boolean hasMipMap = bitmap.hasMipMap();
Log.d(TAG, "Bitmap has mip-map: " + hasMipMap);
```

In this example, the `BitmapFactory` class is used to decode an image resource into a `Bitmap` object.
The `hasMipMap()` method is then called on the `Bitmap` object to check if it has a mip-map. The result
is logged to the console using `Log.d()`.

By default, the `Bitmap` class creates mip-maps for images that are larger than a certain size. You can
disable mip-mapping by setting the `inScaled` option to `false` when decoding a bitmap from a
resource:
```java
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image, options);
iii) setHasMipMap()
58 | Pranay Nandanwar

`setHasMipMap()` is a method in the Android SDK's `Bitmap` class that sets a boolean value indicating
whether the bitmap has a mip-map. A mip-map is a pre-calculated set of scaled-down versions of an
image, which can be used to improve rendering performance and reduce aliasing artifacts.
Here's an example usage of `setHasMipMap()`:
```java
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
bitmap.setHasMipMap(true);
```

In this example, the `BitmapFactory` class is used to decode an image resource into a `Bitmap` object.
The `setHasMipMap()` method is then called on the `Bitmap` object to enable mip-mapping for the
bitmap.

b) What do you mean by open GLES? Explain how it can be used in creating Animations
in Android. S19
a) What is openly Embedded system? Explain how to create animations with Android's Graphics API. S18

a) What is openly Embedded system? Explain how to create animations with Android graphics API. S18 OLD

a) How to create Animations with Android's Graphics API? Explain with example. W18

a) How to create animations with Android's Graphics API? Explain in brief W17 OLD

OpenGL ES

One of the most interesting features of the Android platform is its support of OpenGL for Embedded Systems,1 or
OpenGL ES. OpenGL ES is the embedded systems version of the popular OpenGL standard, which defines a cross-
platform and cross-language API for computer graphics.

The OpenGL ES API doesn’t support the full OpenGL API, and much of the OpenGL API has been stripped out to
allow OpenGL ES to run on a variety of mobile phones, PDAs, video game consoles, and other embedded systems.

OpenGL ES is a fantastic API for 2D and 3D graphics, especially for graphically intensive applications such as
games, graphical simulations, visualizations, and all sorts of animations. Because Android also supports 3D
hardware acceleration, developers can make graphically intensive applications that target hardware with 3D
accelerators.

The basics

Android supports OpenGL both through its framework API and the Native Development Kit
(NDK). This topic focuses on the Android framework interfaces. For more information about the
NDK, see the Android NDK.
59 | Pranay Nandanwar

There are two foundational classes in the Android framework that let you create and manipulate
graphics with the OpenGL ES API: GLSurfaceView and GLSurfaceView.Renderer. If your goal is to use
OpenGL in your Android application, understanding how to implement these classes in an
activity should be your first objective.

Android incudes support for high performance 2D and 3D graphics with the Open Graphics
Library (OpenGL®), specifically, the OpenGL ES API. OpenGL is a cross-platform graphics API
that specifies a standard software interface for 3D graphics processing hardware. OpenGL ES is
a flavor of the OpenGL specification intended for embedded devices. Android supports several
versions of the OpenGL ES API:

 OpenGL ES 1.0 and 1.1 - This API specification is supported by Android 1.0 and higher.

 OpenGL ES 2.0 - This API specification is supported by Android 2.2 (API level 8) and higher.

 OpenGL ES 3.0 - This API specification is supported by Android 4.3 (API level 18) and higher.

 OpenGL ES 3.1 - This API specification is supported by Android 5.0 (API level 21) and higher.
Creating animations with Android’s Graphics API

 Android provides a huge set of 2D-drawing APIs that allow you to create graphics.
 Android has got visually appealing graphics and mind blowing animations.
 The Android framework provides a rich set of powerful APIS for applying animation to
UI elements and graphics as well as drawing custom 2D and 3D graphics.

If a picture says a thousand words, then an animation must speak volumes. Android supports multiple
methods of creating animation, including through XML, as you saw in chapter 3, or via Android’s XML
frame-byframe animations using the Android Graphics API, or via Android’s support for OpenGL ES. In
this section, you’re going to create a simple animation of a bouncing ball using Android’s frame-by-
frame animation.
9.2.1 Android’s frame-by-frame animation

Android allows you to create simple animations by showing a set of images one after another to give the Listing
9.8 Shape3.xml Listing 9.9 line.xml Figure 9.2 Various shapes drawn using XML 228 CHAPTER 9 Graphics and
animation illusion of movement, much like stop-motion film. Android sets each frame image as a drawable
resource; the images are then shown one after the other in the background of a View. To use this feature, you
define a set of resources in a XML file and then call AnimationDrawable start(). To demonstrate this method

9.2.2 Programmatically creating an animation


Page No228 Extra

d) Explain Location Manager and Location provider in detail. S19


c) Explain location Manager and Location provider in brief. W19
c) Distinguish between Location Manager and Location provider. Write example of any one. W18
d) Explain Location Manager and Location provider in brief. W17 OLD

Location mnager
60 | Pranay Nandanwar

This class provides access to the system location services. These services allow applications to obtain
periodic updates of the device's geographical location, or to be notified when the device enters the
proximity of a given geographical location.

When building location-aware applications on the Android platform, you’ll most often use several key
classes.

A LocationProvider provides location data using several metrics, and you can access providers through a
LocationManager. LocationManager allows you to attach a LocationListener that receives updates when
the device location changes. LocationManager also can directly fire an Intent based on the proximity to a
specified latitude and longitude. You can always retrieve the last-known Location directly from the
manager. The Location class is a Java bean that represents all the location data available from a
particular snapshot in time.

Depending on the provider used to populate it, a Location may or may not have all the possible data
present; for example, it might not include speed or altitude. To get your Wind and Waves sample
application started and to grasp the related concepts, you first need to master the LocationManager.

LocationProvider is the super class for location providers. A location provider provides the information
of the geographical location of the device. This information is stored in the Location class.

For accessing the location based services Android provide different classes that are available in android.
location.
LocationProvider helps define the capabilities of a given provider implementation. Each implementation
responsible for returning location information may be available on different devices and in different
circumstances. Available provider implementations depend on the hardware capabilities of the device,
such as the presence of a GPS receiver. They also depend on the situation: even if the device has a
GPS receiver, can it currently receive data from satellites, or is the user somewhere inaccessible such
as an elevator or a tunnel?

The different classes are as follows:

EXAMPLE:

Create a new project by File-> New -> Android Project

Give the project name as Location. In the given below example create a separate class name it
LocationService. I have access this class in MainActivity.java class.
61 | Pranay Nandanwar

After creating the classes your Android workspace folder structure will look like as given below.

Code for MainActivity.java class

package com.example.location;

import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button btnLocation;

LocationService appService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appService = new LocationService(this);

btnLocation = (Button) findViewById(R.id.btnGPSLocation);


btnLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {

Location gpsLocation = appService.getLocation(LocationManager.GPS_PROVIDER);

if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Toast.makeText(getApplicationContext(),"Mobile Location (GPS): \nLatitude: " + latitude+ "\nLongitude: " +
longitude,Toast.LENGTH_LONG).show();
} else
{
showAlertDialog("GPS Service");
}

}
});
}

public void showAlertDialog(String title) {

AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

alertDialog.setTitle(title + " SETTINGS");

alertDialog.setMessage(title + " is not enabled! Do you want to go to settings menu?");


62 | Pranay Nandanwar

alertDialog.setPositiveButton("Settings",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});

Code for LocationService.java class

package com.example.location;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

public class LocationService extends Service implements LocationListener{

protected LocationManager locationManager;


Location location;

private static final long MIN_UPDATE_TIME = 1000 * 60 * 3;

public LocationService(Context context)

{
locationManager = (LocationManager)context.getSystemService(LOCATION_SERVICE);
}

public Location getLocation(String provider) {


if (locationManager.isProviderEnabled(provider))
{
locationManager.requestLocationUpdates(provider,MIN_UPDATE_TIME, 10, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
63 | Pranay Nandanwar

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}

Write given below code in AndroidManifest.xml after uses-sdk tag.

< !-- to get location using GPS -->


< uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
< uses-permission android:name="android.permission.INTERNET" />

run

c) Write a note on Simulating Location Within the Emulator. 4 W18


c) Explain simulation of location within the emulator in brief. 4 W19
c) Explain simulation of location within the Emulator in brief. 4 W17 OLD
For any location-aware application, you’ll start by working with the provided SDK and the emulator. Within the
emulator, you’ll set and update your current location. From there you’ll want to progress to supplying a range of
locations and times to simulate movement over a geographic area. You can accomplish these tasks in several
ways, either by using the DDMS tool or by using the command line from the shell. To get started quickly, let’s first
send in direct coordinates through the DDMS tool.

11.1.1 Sending in your coordinates with the DDMS tool

You can access the DDMS tool in two ways, either launched on its own from the SDK tools subdirectory or as the
Emulator Control view within the Eclipse IDE. You need to have Eclipse and the Android Eclipse plug-in to use
DDMS within Eclipse; see chapter 2 and appendix A for more details about getting the SDK and plug-in set up.
With the DDMS tool you can send direct latitude and longitude coordinates manually from the Emulator Control
> Location Controls form. This is shown in figure 11.2. Note that Longitude is the first field, which is the standard
around the world, but backward from how latitude and longitude are generally expressed in the United States.
64 | Pranay Nandanwar

11.1.2 The GPS Exchange Format

The DDMS tool supports two formats for supplying a range of location data in file form to the emulator. The GPS
Exchange Format (GPX) allows a more expressive form when working with Android. GPX is an XML schema that
allows you to store waypoints, tracks, and routes. Many handheld GPS devices support this format. The following
listing shows the basics of the format in a portion of a sample GPX file.
11.1.3 The Google Earth Keyhole Markup Language

The second format that the Android DDMS tool supports for sending a range of mock location information to the
emulator is the Keyhole Markup Language KML). KML was originally a proprietary format created by a company
named Keyhole page no 270

a) Explain three types of animation supported by android. W19


d) Explain Three types of animations supported by android. S18 OLD

Animation is the process of adding a motion effect to any view, image, or text. With the
help of an animation, you can add motion or can change the shape of a specific view.
Animation in Android is generally used to give your UI a rich look and feel. The
animations are basically of three types as follows:
1. Property Animation
2. View Animation
3. Drawable Animation

Property Animation
Property Animation is one of the robust frameworks which allows animating almost
everything. This is one of the powerful and flexible animations which was introduced in
Android 3.0. Property animation can be used to add any animation in
the CheckBox, RadioButtons, and widgets other than any view.
This animation was introduced in Android 3.0 (API level 11). It allows the user to animate
anything.
Property animations are highly customizable, you can specify the duration, the number of
repeats, the type of interpolation, and the frame rate of the animation. The Property Animation
system is always preferred for more complex animations.
Property animations allow us to animate any property of any object from one value to another
over a specified duration. Let us take an example, imagine you wanted to animate the 3d rotation
using the rotationX or rotationY properties that were introduced in API 11. Or maybe you want
to animate a color change or animate the change of a drawable. This is not possible by using View
Animations. For this purpose Property Animation is used .
Common properties commonly animated on views include:
Property Description
alpha Fade in or out
rotation, rotationX, rotationY Spin or flip
scaleX ,scaleY Grow or shrink
x,y,z Position
translationX, translationY, translationZ (API 21+) Offset from Position
View Animation:
65 | Pranay Nandanwar

This is the simplest animation used in Android. It define the properties of our Views that should
be animated using a technique called Tween Animation.It take the following parameters i.e. size,
time duration , rotation angle, start value , end value, and perform the required animation on
that object.You can execute the animation by specifying transformations on your View. This can
be done in XML resource files or programmatically.
Android View animation can make animation on any View objects, such as ImageView, TextView
or Button objects. View animation can only animate simple properties like position, size, rotation,
and the alpha property that allows you animate the transparency of a View.
The drawback of this mechanism is that it can only be applied to Views.
Drawable Animation:
This animation allows the user to load drawable resources and display them one frame after
another. This method of animation is useful when user wants to animate things that are easier to
represent with Drawable resources.
To use Animations in Android , Android has provided us a class called Animation.
To perform animation in android , we will call a static function loadAnimation()(this method is
used to load animation) of the class AnimationUtils. We are going to receive the result in an
instance of Animation Object. Its syntax is as follows −

Animation animation =AnimationUtils.loadAnimation(getApplicationContext(), R.anim.myanimatio


n);

Second parameter refers to our animation.xml file.It is created under res directory(res->anim-
>myanimation.xml)
The Animation class has many methods given below:
1.start(): This method will start the animation.
2.setDuration(long duration): This method sets the duration of an animation.
3.getDuration(): This method gets the duration.
4.end(): This method ends the animation.
5.cancel(): This method cancels the animation.

Setting The Animation Listeners (Optional)

Animation listeners can be set by implementing AnimationListener in our Activity. If you will use
AnimationListener, then you will have to override following methods.
onAnimationStart –

@Override
public void onAnimationStart(Animation animation) {
}
66 | Pranay Nandanwar

onAnimationEnd –

@Override
public void onAnimationEnd(Animation animation) {
}

onAnimationRepeat –

@Override
public void onAnimationRepeat(Animation animation) {
}

Scale Animation
Scale Animation is used to make a smaller or larger view either on x axis or y axis. Pivot point can
also be specified around which we want the animation to take place.
Rotate Animation
Rotate Animation is used to rotate a view around a pivot point by a certain number of degrees.
Translate Animation
Translate Animation is used to move a view along the x or y axis.
Alpha Animation
Transparency of a view can be changed by Alpha Animation

Interpolator:

The dictionary meaning of Interpolate is to alter, intercept or insert in between two things or
events.
It is used to insert or apply an additional animation effects between the start and the end value
of the property of an object.It is also used to define the rate of change of an animation.
Types of Interpolator:
1.Linear Interpolator: It is the default interpolator of all animations. It defines that the rate of the
change of the animation is constant.
2.Accelerate Interpolator: Accelerates the moving of the view, it starts out slowly and then
accelerates until it reaches the final position.
3.Decelerate Interpolator: Does the opposite of the accelerate interpolator. It starts out fast and
the slows down.
4.Accelerate Decelerate Interpolator: Makes the moving go slow at the beginning and the end,
but fast in the middle.
5.Anticipate Interpolator: Moves the animation backwards before it starts
6.Overshoot Interpolator: Does the opposite of the anticipate interpolator. It make the
animation to go further than the defined destintion, and then get back to the defined destination.
67 | Pranay Nandanwar

7.Anticipate Overshoot Interpolator: Combines the anticipate and the overshoot interpoplator.
The change starts backward then flings forward and overshoots the target value and finally goes
back to the final value.
8.Bounce Interpolator: Makes an bounce animation before the desired animation ends.
9.Cycle Interpolator: Repeats the animation for a specified number of cycles.

d) Develop an android app to play frame-by frame animation for static image.
W19(page no 228)
1. Create a new Android project in Android Studio and add your static image file to the project.

2. Open the `activity_main.xml` file and add an `ImageView` to display the animation:

```xml

<ImageView

android:id="@+id/animation_image"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:src="@drawable/your_static_image" />

```

Note that we've assigned an ID to the `ImageView` so that we can reference it in the Java code later.

3. Create a new directory named `anim` in the `res` folder of your project.

4. Add each frame of the animation as a separate image file to the `anim` directory. Name the files in sequential
order (e.g. `frame_1.png`, `frame_2.png`, `frame_3.png`, etc.).

5. Create a new XML file named `animation_list.xml` in the `anim` directory. Add the following code to define the
frame-by-frame animation:

```xml

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

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"

android:oneshot="false">

<item

android:drawable="@drawable/frame_1"

android:duration="100" />
68 | Pranay Nandanwar

<item

android:drawable="@drawable/frame_2"

android:duration="100" />

<item

android:drawable="@drawable/frame_3"

android:duration="100" />

<!-- Add additional frames here as needed -->

</animation-list>

```

Note that we've set the `oneshot` attribute to `false` so that the animation loops continuously. You can adjust the
`duration` attribute to control the speed of the animation.

6. Open the `MainActivity.java` file and add the following code to start the animation when the app starts:

```java

public class MainActivity extends AppCompatActivity {

private ImageView animationImage;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

animationImage = findViewById(R.id.animation_image);

animationImage.setImageResource(R.drawable.animation_list);

AnimationDrawable animationDrawable = (AnimationDrawable) animationImage.getDrawable();

animationDrawable.start();

```

This code initializes the `ImageView` object and sets its image to the `animation_list.xml` file. It then starts the
animation using the `AnimationDrawable` class.

7. Run the app to see the frame-by-frame animation play for the static image.
69 | Pranay Nandanwar

d) How to convert places and Addresses with Decoder? Explain with suitable example.W18

The Android documentation describes geocoding as converting a “street address or other description of
a location” into latitude and longitude coordinates.
Reverse geocoding is the opposite—converting latitude and longitude into an address. To accomplish this,
the Geocoder class makes a network call to a web service.
You won’t use geocoding in Wind and Waves because the ocean doesn’t contain cities, addresses, and so
on.
Geocoding concludes our look at the powerful location- and mapping-related components of the Android platform.
Nevertheless, geocoding provides invaluable tools when working with coordinates and maps.
To demonstrate the concepts surrounding geocoding, this listing includes a new single Activity
application,
GeocoderExample.

. . Class declaration and Instance variables omitted for brevity


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
input = (EditText) findViewById(R.id.input);
output = (TextView) findViewById(R.id.output);
button = (Button) findViewById(R.id.geocode_button);
isAddress = (CheckBox)
findViewById(R.id.checkbox_address);
button.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
output.setText(performGeocode(
input.getText().toString(),
isAddress.isChecked()));
}
});
}
private String performGeocode(String in, boolean isAddr) {
String result = "Unable to Geocode - " + in;
if (input != null) {
Geocoder geocoder = new Geocoder(this);
if (isAddr) {
try {
List<Address> addresses =
geocoder.getFromLocationName(in, 1);
if (addresses != null) {
result = addresses.get(0).toString();
}
} catch (IOException e) {
Log.e("GeocodExample", "Error", e);
}
} else {
try {
String[] coords = in.split(",");
if ((coords != null) && (coords.length == 2)) {
70 | Pranay Nandanwar

List<Address> addresses =
geocoder.getFromLocation(
Double.parseDouble(coords[0]),
Double.parseDouble(coords[1]),
1);
result = addresses.get(0).toString();
}
} catch (IOException e) {
Log.e("GeocodExample", "Error", e);
}
}
}
return result;
}
You create a Geocoder by constructing it with the Context of your application B. You then use a Geocoder to
either convert String instances that represent place names into Address objects with the getFromLocationName
method C or convert latitude and longitude coordinates into Address objects with the getFromLocation method
D. Figure 11.8 shows our GeocoderExample in use. In this case we’ve converted a String describing Wrigley Field
in Chicago into an Address object containing latitude and longitude coordinates. Geocoder provides many useful
features. For instance, if you have data that includes address string portions, or only place descriptions, you can
easily convert them into latitude and longitude numbers for use with GeoPoint and Overlay to place them on the
user’s map.

c) Write a program in Android to play audio in Android. 4 S19

c) Write and explain the steps for playing audio in Android conclude by demonstrating its program. W17 OLD

Probably the most basic need for multimedia on a cell phone is the ability to play audio files, whether new
ringtones, MP3s, or quick audio notes. Android’s Media Player is easy to use. At a high level, all you need to do to
play back an MP3 file is follow these steps:
1 Put the MP3 in the res/raw directory in a project (note that you can also use a
URI to access files on the network or via the internet).
2 Create a new instance of the MediaPlayer and reference your MP3 by calling
MediaPlayer.create().
3 Call the MediaPlayer methods prepare() and start().
Listing 10.1 main.xml for MediaPlayer Example

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Simple Media Player"
/>
<Button android:id="@+id/playsong"
android:layout_width="fill_parent"
71 | Pranay Nandanwar

android:layout_height="wrap_content"
android:text="Halo 3 Theme Song"
/>
</LinearLayout>
We need to fill out our MediaPlayerActivity class, as shown in the following listing.

Listing 10.2 MediaPlayerActivity.java


public class MediaPlayerActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button mybutton = (Button) findViewById(R.id.playsong);
mybutton.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {
MediaPlayer mp =
MediaPlayer.create(MediaPlayerActivity.this,
R.raw.halotheme);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer arg0) {}
} );}});
}}

b) Write a program in Android to demonstrate Video View to run any video. W18
Playing a video is slightly more complicated than playing audio with the MediaPlayer API, in part because you
have to provide a view surface for your video to play on. Android has a VideoView widget that handles that task
for you; you can use it in any layout manager. Android also provides a number of display options, including
scaling and tinting. So let’s get started with playing video by creating a new project called Simple Video Player.
Next, create a layout, as shown in the following listing
Listing 10.3 main.xml—UI for Simple Video Player
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<VideoView android:id="@+id/video"
android:layout_width="320px"
android:layout_height="240px"
/>/
</LinearLayout>
All we’ve done in this listing is add the VideoView widget B. The VideoView provides a UI widget with stop, play,
advance, rewind, and other buttons, making it unnecessary to add your own. Next, we need to write a class to
play the video, which is shown in the following listing.
Listing 10.4 SimpleVideo.java
public class SimpleVideo extends Activity {
private VideoView myVideo;
private MediaController mc;
public void onCreate(Bundle icicle) {
72 | Pranay Nandanwar

super.onCreate(icicle);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.main);
this.myVideo = (VideoView) findViewById(R.id.video);
this.myVideo.setVideoPath("sdcard/test.mp4");
this.mc = new MediaController(this);
this.mc.setMediaPlayer(this.myVideo);
this.myVideo.setMediaController(this.mc);
this.myVideo.requestFocus();
}
}
In this listing, we first created a translucent window, which is necessary for our SurfaceView B. Next, we
reference the VideoView as a container for playing the video, and use its setVideoPath() to have it look at an SD
card for our test MP4. Finally, we set up the MediaController and use the setMediaController() to perform a
callback to the VideoView to notify it when our video is finished playing.

a) How Graphics API works in Android? Write a program in Android to Draw Rectangle on the screen using Java
code only. S19

The Android Graphics API provides a set of classes and methods for rendering 2D and 3D graphics on the screen.
It includes support for drawing shapes, images, and text, as well as handling input events and managing
animations.

To draw a rectangle on the screen using Java code in an Android application, you can use the `Canvas` class and
its associated `Paint` object. Here's an example program:

First, create a new layout file in the `res/layout` directory called `activity_main.xml`:

```xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```

This layout simply creates a `FrameLayout` container for the drawing canvas.

Next, create a new activity class called `MainActivity`:

```java
public class MainActivity extends AppCompatActivity {

private static final int RECT_SIZE = 200;

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

FrameLayout container = findViewById(R.id.container);


73 | Pranay Nandanwar

container.addView(new CustomView(this));
}

private static class CustomView extends View {

private final Paint paint = new Paint();

public CustomView(Context context) {


super(context);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int x = getWidth() / 2 - RECT_SIZE / 2;
int y = getHeight() / 2 - RECT_SIZE / 2;
canvas.drawRect(x, y, x + RECT_SIZE, y + RECT_SIZE, paint);
}
}
}
``In this program, the `MainActivity` class sets the `activity_main.xml` layout as its content view and adds a new
instance of the `CustomView` class to the container.

The `CustomView` class extends the `View` class and overrides its `onDraw()` method to draw the rectangle. The
`paint` object is used to set the stroke color, style, and width. The `onDraw()` method then calculates the
rectangle's position and size based on the view's dimensions and draws it on the canvas using the `drawRect()`
method.

b) Write a program to display Arcshape Ovalshape and Rectshape on Activity. W19

c) Write a program to display Arcshape, ovlashape and Rectshape on Activity. S18 OLD

Example og graphic api


Sure, here's an example code snippet that demonstrates how to display Arcshape, Ovalshape, and Rectshape in
an Android Activity using Java and XML:
1. Create a new Android project in Android Studio and open the `activity_main.xml` file.
2. Add the following code to create an `ImageView` for each shape:
```xml
<ImageView
android:id="@+id/arc_shape"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/arc_shape"
/>

<ImageView
android:id="@+id/oval_shape"
74 | Pranay Nandanwar

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/oval_shape"
/>

<ImageView
android:id="@+id/rect_shape"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/rect_shape"
/>
```
Note that the `src` attribute for each `ImageView` references a drawable resource for the corresponding shape.
You can create these drawable resources in the `res/drawable` folder by right-clicking on it and selecting "New >
Drawable Resource File", then choosing the shape you want to create and customizing its attributes.

3. Open the `MainActivity.java` file and add the following code to initialize the `ImageView` objects:
```java
public class MainActivity extends AppCompatActivity {

private ImageView arcShape;


private ImageView ovalShape;
private ImageView rectShape;

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

arcShape = findViewById(R.id.arc_shape);
ovalShape = findViewById(R.id.oval_shape);
rectShape = findViewById(R.id.rect_shape);
}
}

4. Build and run the app. You should now see the Arcshape, Ovalshape, and Rectshape displayed in the main
activity.

b) Develop an Android app that define a List View and apply custom animation to List view. S18
1. Create a new Android project in Android Studio and open the `activity_main.xml` file.
2. Add the following code to create a `ListView` with some sample data:
```xml
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
75 | Pranay Nandanwar

Note that we've assigned an ID to the `ListView` so that we can reference it in the Java code later.
3. Create a new layout resource file named `list_item.xml` in the `res/layout` folder. Add the following code to
create a custom layout for each item in the `ListView`:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">

<TextView
android:id="@+id/item_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="18sp"
android:textColor="#000000"
android:text="Sample Item" />

</LinearLayout>
This layout resource file defines a simple `LinearLayout` with a `TextView` that displays the text for each list item.
4. Open the `MainActivity.java` file and add the following code to initialize the `ListView` object and populate it
with some sample data:
```java
public class MainActivity extends AppCompatActivity {
private ListView listView;

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

listView = findViewById(R.id.list_view);

// Populate the list view with sample data


String[] data = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item
10"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.list_item, R.id.item_text, data);
listView.setAdapter(adapter);
}
}
```
This code initializes the `ListView` object and sets its adapter to an `ArrayAdapter` that uses the `list_item.xml`
layout resource file to display each item.

5. Finally, add the following code to apply a custom animation to the `ListView`:
```java
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
76 | Pranay Nandanwar

Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_in);


listView.startAnimation(animation);
}
}

This code overrides the `onWindowFocusChanged` method to apply an animation to the `ListView` when the
activity gains focus. In this example, we're using the `slide_in.xml` animation resource file to slide each list item
into view.
6. Create a new animation resource file named `slide_in.xml` in the `res/anim` folder. Add the following code to
define the animation:
```xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="100%" android:toYDelta="0" android:duration="500" />
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
</set>

d) Write a program to implement a custom button and handle the displayed message on button
press. S18
1. Create a new Android project in Android Studio and open the `activity_main.xml` file.
2. Add the following code to create a custom button with some sample text:
```xml
<com.example.myapplication.CustomButton
android:id="@+id/custom_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me!" />
```
Note that we've assigned an ID to the `CustomButton` so that we can reference it in the Java code later.

3. Create a new Java class named `CustomButton` in the project. Add the following code to define the custom
button class:
```java
public class CustomButton extends androidx.appcompat.widget.AppCompatButton {

public CustomButton(Context context) {


super(context);
init();
}

public CustomButton(Context context, AttributeSet attrs) {


super(context, attrs);
init();
}

public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {


super(context, attrs, defStyleAttr);
init();
}
77 | Pranay Nandanwar

private void init() {


// Add custom styling or behavior here
}
}
```
This code defines a custom `Button` class that extends the `AppCompatButton` class and includes an `init`
method that can be used to add custom styling or behavior to the button.

4. Open the `MainActivity.java` file and add the following code to handle the button press event and display a
message:
```java
public class MainActivity extends AppCompatActivity {

private CustomButton customButton;

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

customButton = findViewById(R.id.custom_button);
customButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
}
}
```
This code initializes the `CustomButton` object and sets its `OnClickListener` to display a toast message when the
button is clicked.

5. Run the app and click the custom button to verify that the message is displayed correctly.
78 | Pranay Nandanwar

Unit 4

a) Write about NDK in detail. S18

d) What is NDK? Explain in detail. W18

d) Write about NDK in detail. S18 OLD

c) Write about NDK apl in detail. W18 OLD

d) Explain Android Native Development. 4 S19

a) Explain Android Native Development Kit. W19

b) What is Android Native Development kit? Explain in detail. W17 OLD

What is NDK?

NDK which stands for Native Development Kit is a set of tools or a toolset that will allow us
to use C/C++ in our Android Application. Isn’t that cool? It is called Native because of the use
of native-code languages in it such as C and C++.

Why is NDK Useful?

Now, we will answer this question with the help of an example. Let’s say you want to add a
critical function or a specific processor-dependent code to your own app which will require
high performance, using Java only. It would not succeed so in order to get the following
requirements, you have to use C or C++ which will make it run faster. But even if we know C
or C++, how would we implement it in our app? So this is where we require NDK to integrate
the native-code languages to make it run on the app. Let’s see some more advantages of
using NDK:
1. It provides a way to embed the equivalent native libraries in the apk.
2. It mostly runs without any recompilation.
3. It can be used to access physical device components like sensors.
4. It gives us the ability to reuse the code written in C/C++.

How Does it Work?

This brings us to our next question, How will the java code communicate with the native
code? We would understand the question from the image given below:

First of all, we have to write a C/C++ code then after that, we have a Makefile in which we
specifying the platform this application needs to target. We use ndk-build command to build
the shared object libraries of the .so file. Then Java program uses these shared object
libraries and calls the native functions through JNI. JNI is the Java Native Interface which
defines a way for the bytecode that Android compiles the code written in Java or Kotlin to
interact with the native codes.

b) Write a note on : i) Bluetooth in Android. ii) Sensors in Android. S19

c) Write a brief note on Android Bluetooth and sensors. W18


79 | Pranay Nandanwar

: i) Bluetooth in Android

Among many ways, Bluetooth is a way to send or receive data between two different devices. Android
platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data
with other Bluetooth devices.

Android provides Bluetooth API to perform these different operations.


 Scan for other Bluetooth devices
 Get a list of paired devices
 Connect to other devices through service discovery

Using the Bluetooth APIs, an app can perform the following:

 Scan for other Bluetooth devices.

 Query the local Bluetooth adapter for paired Bluetooth devices.

 Establish RFCOMM channels.

 Connect to other devices through service discovery.

 Transfer data to and from other devices.

 Manage multiple connections.


This topic focuses on Classic Bluetooth. Classic Bluetooth is the right choice for more battery-intensive
operations, which include streaming and communicating between devices. For Bluetooth devices with
low power requirements, consider using Bluetooth Low Energy connections.

This documentation describes different Bluetooth profiles and explains how to use the
Bluetooth APIs to accomplish the four major tasks necessary to communicate using Bluetooth:

 Setting up Bluetooth.

 Finding devices that are either paired or available in the local area.

 Connecting devices.

 Transferring data between devices.

Key classes and interfaces

All of the Bluetooth APIs are available in the android.bluetooth package. The following are the
classes and interfaces you need in order to create Bluetooth connections:

BluetoothAdapter

Represents the local Bluetooth adapter (Bluetooth radio). The BluetoothAdapter is the entry-point
for all Bluetooth interaction. Using this, you can discover other Bluetooth devices, query a list of
bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address, and create
a BluetoothServerSocket to listen for communications from other devices.

BluetoothDevice

Represents a remote Bluetooth device. Use this to request a connection with a remote device
through a BluetoothSocket or query information about the device such as its name, address, class,
and bonding state.
80 | Pranay Nandanwar

BluetoothSocket

Represents the interface for a Bluetooth socket (similar to a TCP Socket). This is the connection
point that allows an app to exchange data with another Bluetooth device
using InputStream and OutputStream.

BluetoothServerSocket

Represents an open server socket that listens for incoming requests (similar to a TCP ServerSocket).
In order to connect two devices, one device must open a server socket with this class. When a
remote Bluetooth device makes a connection request to this device, the device accepts the
connection and then returns a connected BluetoothSocket.

BluetoothClass

Describes the general characteristics and capabilities of a Bluetooth device. This is a read-only set
of properties that defines the device's classes and services. Although this information provides a
useful hint regarding a device's type, the attributes of this class don't necessarily describe all
Bluetooth profiles and services that the device supports.

BluetoothProfile

An interface that represents a Bluetooth profile. A Bluetooth profile is a wireless interface


specification for Bluetooth-based communication between devices. An example is the Hands-
Free profile. For more discussion of profiles, see Bluetooth profiles.

BluetoothHeadset

Provides support for Bluetooth headsets to be used with mobile phones. This includes both the
Bluetooth Headset profile and the Hands-Free (v1.5) profile.

BluetoothA2dp

Defines how high-quality audio can be streamed from one device to another over a Bluetooth
connection using the Advanced Audio Distribution Profile (A2DP).

BluetoothHealth

Represents a Health Device Profile proxy that controls the Bluetooth service.

BluetoothHealthCallback

An abstract class that you use to implement BluetoothHealth callbacks. You must extend this class
and implement the callback methods to receive updates about changes in the app’s registration
state and Bluetooth channel state.

BluetoothHealthAppConfiguration

Represents an app configuration that the Bluetooth Health third-party app registers to
communicate with a remote Bluetooth health device.

BluetoothProfile.ServiceListener
81 | Pranay Nandanwar

An interface that notifies BluetoothProfile interprocess communication (IPC) clients when they have
been connected to or disconnected from the internal service that runs a particular profile.

ii) Sensors in Android


b) Enlist any four Interface of sensor class and explain it. S18

c) Enlist any four Interface of sensor class and explain it. W19

Android exposes the physical hardware sensors via a class known as the SensorManager.

The SensorManager class is similar to the BluetoothAdapter class in that all related activities rely on having
a reference to SensorManager. The SensorManager class is part of the android.hardware package.

Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device.

In our childhood, we all have played many android games like Moto Racing and
Temple run in which by tilting the phone the position of the character changes. So, all
these happen because of the sensors present in your Android device. Most Android-
powered devices have built-in sensors that measure motion, orientation, and various
environmental conditions. Android Sensors can be used to monitor the three-
dimensional device movement or change in the environment of the device such as
light, proximity, rotation, movements, magnetic fields, and much more.

Android provides sensor api to work with different types of sensors.

We can collect raw sensor data by using Android Sensor API. Android sensor API
provides many classes and interfaces. Some of the important classes and interfaces
are:

1. SensorManager Class: Sensor manager is used to accessing various sensors


present in the device.
2. Sensor Class: The sensor class is used to get information about the sensor such
as sensor name, sensor type, sensor resolution, sensor type, etc.
3. SensorEvent class: This class is used to find information about the sensor.
4. SensorEventListener interface: This is used to perform some action when sensor
accuracy changes.
82 | Pranay Nandanwar

Android Sensor API

1) SensorManager class

o The android.hardware.SensorManager class provides methods : to get sensor instance,


o to access and list sensors,
o to register and unregister sensor listeners etc.

he class has several methods, such as getDefaultSensor(), registerListener(),


unregisterListener(), and getSensorList()

You can get the instance of SensorManager by calling the method getSystemService() and
passing the SENSOR_SERVICE constant in it.

SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);

.2) Sensor class

The android.hardware.Sensor class provides methods to get information of the sensor such as
sensor name, sensor type, sensor resolution, sensor type etc.

This class represents a specific sensor on the device, such as the accelerometer, gyroscope, or
proximity sensor. You can use it to get information about the sensor, such as its name, vendor,
and power consumption.

The class has several methods, such as getName(), getType(), getVendor(), and getPower().

3) SensorEvent class

Its instance is created by the system. It provides information about the sensor.

This class represents a single sensor event, containing information about the
sensor's value, accuracy, timestamp, and more. When a sensor detects a change, it
creates a new SensorEvent object and sends it to all registered listeners. The class
has several methods, such as values[], accuracy, and timestamp.

4) SensorEventListener interface

It provides two call back methods to get information when sensor values (x,y and z) change or
sensor accuracy changes.

This interface provides methods for receiving sensor events. When you implement this interface
and register your listener with a sensor, you'll receive callbacks whenever the sensor detects a
change in its value. The interface has two methods: onSensorChanged() and
onAccuracyChanged(). The onSensorChanged() method is called when the sensor value
changes, and the onAccuracyChanged() method is called when the sensor accuracy changes.

Each sensor instance can provide a handful of useful and interesting attributes,
83 | Pranay Nandanwar

including:

The orientation sensor on a Nexus One shows the following characteristics:

gree

Now that you have a feel for how to gain access to a sensor through SensorManager,
let’s explore reading values from a sensor.

Sensor types and availability


Sensor Used for

TYPE_ACCELEROMETER Motion detection (shake, tilt, and so on).

TYPE_AMBIENT_TEMPERATURE Monitoring air temperature.

TYPE_GRAVITY Motion detection (shake, tilt, and so on).

TYPE_GYROSCOPE Rotation detection (spin, turn, and so on).

TYPE_LIGHT Controlling screen brightness.

TYPE_LINEAR_ACCELERATION Monitoring acceleration along a single axis.

TYPE_MAGNETIC_FIELD Creating a compass.

TYPE_ORIENTATION Determining device position.

TYPE_PRESSURE Monitoring air pressure changes.

TYPE_PROXIMITY Phone position during a call.

TYPE_RELATIVE_HUMIDITY Monitoring ambient humidity (relative and absolute), and dew point.

TYPE_ROTATION_VECTOR Motion and rotation detection.

TYPE_TEMPERATURE Monitoring temperatures.


84 | Pranay Nandanwar

Types of Sensors
Android supports three types of sensors:
1. Motion Sensors: These sensors measure acceleration forces and rotational forces
along three axes. This category includes accelerometers, gravity sensors,
gyroscopes, and rotational vector sensors.
2. Position Sensors: These sensors measure the physical position of a device. This
category includes orientation sensors and magnetometers.
3. Environmental Sensors: These sensors measure various environmental
parameters, such as ambient air temperature and pressure, illumination, and
humidity. This category includes barometers, photometers, and thermometers.
Example: Light Sensor App

c) Explain AppWidget in Android with suitable example. S19


d) What is App Widget? Write its purpose. 4 W18
d) What is an Appwidget? Explain in brief. W17 OLD
d) Explain – i) App-widgets ii) Localization. W19

On the home screen, a user interacts with applications, initiates a phone call, searches the device,
launches a browser, and more. By the time the user begins to browse for an application among the sea of
icons in the launcher window, a certain percentage of users will be “lost” and will conclude that the
device just isn’t “user friendly.”

An AppWidget is code that runs on the home screen of an Android device. The visual size of an
AppWidget instance can vary and is designated by the programmer at design time.

The home screen is broken up into 16 usable spaces, each of which is approximately 74 pixels square.

An AppWidget can span a rectangular area ranging from 1x1 spaces to 4 x 4 spaces, provided there’s
room on the current home screen “page.” (A typical phone has around five to nine home screen pages.)

Widgets are an important feature of home screen customization. You can consider
them an “at-a-glance” view of an app’s most important data and functionality that is
available right from the user’s home screen. Widgets can be moved across the home
screen, and can be resized based on the information on the widget.

In android, App widgets are the small application views that can be embedded in other applications such as
the Home screen to quickly access the application data.

These application views are referred as widgets in the user interface and we can publish these views using
an App Widget Provider. An application component that is able to hold other app widgets is called an App
Widget Host.
85 | Pranay Nandanwar

Some of the commonly used android widgets are clock widget, weather widget, music widget, etc. based on
our requirements.

To create an App Widget, the following are the main components that we need to use it in our android
applications.

Supported views
A RemoteViews object (and, consequently, an app widget) can support the following layout
classes:

 FrameLayout
 LinearLayout
 RelativeLayout
 GridLayout

And the following view classes:

 AnalogClock
 Button
 Chronometer
 ImageButton
 ImageView
 ProgressBar
 TextView
 ViewFlipper
 ListView
 GridView
 StackView
 AdapterViewFlipper

Descendants of these classes are not supported. The RemoteViews class also
supports ViewStub, which is an invisible, zero-sized View. You can use ViewStub to lazily
inflate layout resources at runtime.
TYPES OF WIDGETS

There are four types of widgets:


1. Information widgets
2. Collection widgets
3. Control widgets
4. Hybrid widgets

INFORMATION WIDGETS:

These display vital information from an app that is easily visible without actually
accessing the app’s main UI and track information change over time. We can open
the associated app to view more information by touching the information widget.

Examples: Weather widgets, clock widgets, etc.


86 | Pranay Nandanwar

COLLECTION WIDGETS:

Collection widgets specialize in displaying a multitude of elements of the same type.


Collection widgets can scroll vertically. We can browse among the collections and
then open an element to see a detailed view. For example, we can view pictures
from the gallery or we can show news article collection widgets that will show all
news/articles.

CONTROL WIDGETS:

These can be used to turn on/off some system settings like wifi. These widgets allow
us to easily use tools like wifi, Bluetooth, etc.

HYBRID WIDGETS:

As the name suggests these widgets are a hybrid of different widgets which make
them different from widgets which are specific to one type.
87 | Pranay Nandanwar

WIDGET LIMITATIONS

Widgets come with many advantages but there are some limitations. Some of them
are as follows.

Gesture: With widgets we have limited gesture support for navigation as compared to
the app, since widgets have to be present on the home screen which may have
some gesture functions already present. Horizontally shifting widgets is not possible
since that is used in the home screen for navigation. Widgets can only use gestures
like touch and vertical swipe.

Element: We cannot use some UI elements that require specific gesture support
since gesture support is limited.

DESIGN GUIDELINES

Widget content: We need to provide content in widgets that are used frequently.
Widgets are like information snacks or teasers. They should contain information to
attract the user to the application but the full-screen app should always contain more
information than widgets.
Widget navigation: Widgets are for quick, frequently usable features of an app. To
enable more such quick use we can provide navigation links that will extend the
widget functionality and give users more options on the home screen. We can use
these for navigation:

Generative functions: Generative functions allow the user to create new content for
an app, like a new document or a new message.

Open application at the top level: By clicking on the information element we get to
the lower level detail screen which provides access to the top level of the app.

Widget resizing: Resizing allows users to change the height and width of a widget
in the constraints of the home screen placement grid. The advantage is that we can
decide whether we want to make our widget freely resizable or if we want to
constrain it to horizontal or vertical size changes. If our widgets are inherently fixed
size then we don’t need to use resizing.
88 | Pranay Nandanwar

d) What do you mean by Localization? Explain.S19


b) What is Localization? Explain how to build Android applications in C. S18 OLD
An android application can run on many devices in many different regions. In order to make your
application more interactive, your application should handle text,numbers,files e.t.c in ways
appropriate to the locales where your application will be used.
The way of changing string into different languages is called as localization
We will localize the strings used in the application, and in the same way other things can be localized.

In this chapter we cover the topics required for localizing an application. You’ll learn high-level
strategies for localizing an application, and you’ll take a hands-on approach to converting an existing
application to another language. Looking back to chapter 12’s Field Service application, you’ll refactor
that code to be localization ready and then translate it to Spanish. We demonstrate the localized
version of the application through screenshots throughout the chapter
We think it’s only fair to note that the author of this chapter is a native English speaker and his
knowledge of any languages beyond English involves computer programming: Java, C, C#, Objective-C,
and so on. If you’re one of the talented and fortunate among us who can speak numerous languages,
please bear with the rest of us as we broaden our horizons to the global scene.

The applications that we use in Android devices can be specific to a particular


language. That is where Localization comes in the role. Localization is a process that
changes the string into various different languages based on user requirements. In
this tutorial, we will implement it practically in our application.
Localization can be done for Dates and time as well. Localizing the string is good for
the users, but, how about localizing the date and the time? Yes, it can be done too.
Luckily, Android SDK includes the classes that format dates and times according to
the locale.
Apart from these languages, the region code of other languages have been given in the table
below −
Sr.No Language & code

Afrikanns
1
Code: af. Folder name: values-af

Arabic
2
Code: ar. Folder name: values-ar

Bengali
3
Code: bn. Folder name: values-bn

Czech
4
Code: cs. Folder name: values-cs
89 | Pranay Nandanwar

Chinese
5
Code: zh. Folder name: values-zh

German
6
Code: de. Folder name: values-de

French
7
Code: fr. Folder name: values-fr

Japanese
8
Code: ja. Folder name: values-ja

18.2 Exploring locales


A locale is generally referenced as a short character code including both the language and the geographic region.
The origin and meaning of these values stem from political actions and boundaries, both of which change over
time. Our discussion should be considered practical and hopefully useful rather than being a treatise on the
history, meaning, and minutia of the “official” definition of locale, which is elusive

As language and regional barriers are blurred thanks to technology, the concept of a locale

has been employed imperfectly to aid electronic communication. The ISO format for a

locale identifier is a short character code of the following syntax: language_REGION

Consider the formatting of dates, which differs on either side of the Atlantic Ocean. In the United States, it’s
common to format a date with the month preceding the day: MM/DD/YYYY. In the UK, it’s more common to see
the day of the month listed first: DD/MM/YYYY.

As an Android developer, you must keep not only written language in mind, but also the formatting of dates,
times, and numbers that users can customize. These differences are more than trivia; they have a direct impact
on how an application is coded, how it behaves, and importantly, how it’s tested prior to release. The Date &
Time settings are shown in a separate preferences screen, as you can see in figure 18.3.
90 | Pranay Nandanwar

b) How to build Android Application in C? Explain in brief. W18


As you embark on this chapter, you’re temporarily leaving behind the comforts of working strictly in the
Android SDK, Java, and Eclipse. We’ll instead take a close look at the underlying Linux underpinnings of
the Android platform—and more specifically, you’ll learn how to build an application in C, without the
SDK.
This chapter explores the steps required to build applications that run in the Linux foundation layer of
Android. To accomplish this, we’re going to use the C programming language.
the term Android/Linux to refer to the Linux underpinnings of the Android platform. We also use the
term Android/Java to refer to a Java application built using the Android SDK and Eclipse.
C language mastery on this platform is powerful because much of the C language development process
involves porting existing, open source Linux code to the mobile platforms.
Using the NDK, programmers can leverage existing C code and map those routines to applications
written in Java. This chapter doesn’t use the NDK, but rather looks at building standalone C applications
capable of running on the Android platform.
13.1 Building Android apps without the SDK
Applications for Android/Linux are markedly different from applications constructed with the Android SDK.
Applications built with Eclipse and the context-sensitive Java syntax tools make for a comfortable learning
environment.

In line with the spirit of Linux development, from here on out all development takes place with commandline
tools and nothing more sophisticated than a text editor.

Though the Eclipse environment could certainly be leveraged for non-Java development, the focus of this
chapter is on core C language1 coding for Android/Linux.

The first place to start is with the cross-compiling tool chain required to build Android/Linux applications.

13.1.1 The C compiler and linker tools


Building applications for Android/Linux requires the use of a cross-compiler tool chain from CodeSourcery.

The specific version required is the Sourcery G++ Lite Edition for ARM, found at
https://support.codesourcery.com/GNUToolchain/release1479. Once installed, the Sourcery G++ tool chain
contributes a number of useful tools to assist you in creating applications targeting Linux on ARM, which is the
architecture of the Android platform.

(RISC) processor, used in numerous devices, including smartphones, PDAs, and technology appliances such as
low-end routers and disk drive controllers. The ARM platform is a 32-bit reduced instruction set computer

The first and most important tool introduced is gcc. 2 This tool is the compiler responsible for turning C source
files into object files and optionally initiating the link process to build an executable suitable for the
Android/Linux target platform. The full name of the gcc compiler for our cross-compilation environment is arm-
nonelinux-gnueabi-gcc.

13.1.2 Building a Hello World application

The first thing we want you to accomplish with your journey into Android/Linux development is to print
something to the emulator screen to demonstrate that you’re running something on the platform outside the
Android SDK and its Java application environment.

Listing 13.1 Hello.c

#include <stdio.h>
91 | Pranay Nandanwar

int main(int argc,char * argv[])


{
printf("Hello, Android!\n");
return 0;
}
13.1.3 Installing and running the application
In preparation for installing and running the Hello Android application, let’s take a tour of our build and testing
environment. You need to identify four distinct environments and tools and clearly understand them when
building applications for Android/Linux: Android Emulator, command-line CodeSourcery tools, adb or DDMS, and
adb shell.

13.1.4 C application build script


In the previous section, we reviewed each step in building and preparing to test our application. Due to the rather
tedious nature of executing each of these steps, you likely want to utilize command-line tools when building C
applications, as it greatly speeds up the edit, compile, copy, debug cycle.

Android can be used in field service applications in several ways, including:


1. Mobile Workforce Management: Android devices can be used to manage and track mobile
workers in the field. Mobile workforce management apps can be used to dispatch work orders,
track job progress, and communicate with field technicians in real-time.
2. GPS Navigation: Android devices can be used for GPS navigation, which is particularly useful in
field service applications where workers need to travel to different locations. GPS navigation
apps can help workers to find the fastest and most efficient routes to their destination.
3. Service Call Management: Android devices can be used to manage service calls and work orders
in the field. Service call management apps can help technicians to receive and complete service
calls, capture customer signatures, and track work order progress.
4. Asset Management: Android devices can be used to manage and track assets in the field. Asset
management apps can help technicians to locate assets, track asset status and history, and
perform maintenance tasks.
5. Field Data Collection: Android devices can be used for field data collection, which is particularly
useful in industries such as utilities, telecommunications, and construction. Field data collection
apps can be used to collect and record data such as meter readings, site inspections, and
equipment measurements.

a) How Android can be used in field service Applications? Explain. S19


a) How to use Android to work in a field service Application? Explain with example. W18

Overall, Android devices can be used to improve field service operations by providing workers with
access to real-time data, enabling better communication and collaboration, and improving overall
efficiency and productivity.
92 | Pranay Nandanwar

Beyond helping you understand the application, this definition process will get you thinking about the kinds of
impact a mobile application can have on our economy. This chapter’s sample application is called a field service
application.

Designing a real-world Android application


We’ve established that our mobile worker will be carrying two things: a set of hand tools and an Android device.
Fortunately, in this book we’re not concerned with the applicability of the hand tools in his toolbox, leaving us
free to focus on the capabilities and features of a field service application running on the Android platform. In
this section, we define the basic and high-level application requirements.

Core requirements of the application

The mobile worker is dispatched by a home office/dispatching authority,


which takes care of prioritizing and distributing job orders to the appropriate
technician.
—a
device capable of browsing rich web content. The application needs to access
the internet for data transfer as well.

on an Android device; a laptop computer isn’t necessary or even desired.


roof of completion of work, most readily accomplished with the
capture of a customer’s signature. Of course, an electronic signature is preferred.

the invoicing process, which improves cash flow.

he’s paid by the job, not by the hour, so getting access to new job information as
quickly as possible is a benefit to the mobile worker.

much information as possible about the problem he’s being asked to resolve.
The mobile worker may have to place orders for replacement parts while in the
field.
rker will require navigation assistance, as he’s likely covering a
rather large geographic area.
—one that’s simple to use
with a minimum number of requirements.
12.2.1 Mapping out the field service application

examine the application flow to better understand the relation among the application’s functionality, the UI, and
the classes used to deliver this functionality.
93 | Pranay Nandanwar

12.2.2 List of source files

A field service application for Android is a software tool that enables companies to manage and track
their field service operations using Android devices, such as smartphones or tablets. This type of
application is typically designed to help field service technicians perform their work more efficiently by
providing them with real-time access to job schedules, customer information, and other important data.
The application may also include features such as GPS tracking, electronic invoicing, and customer
communication tools.
Some common features of a field service application for Android might include:
1. Scheduling and dispatching: This feature allows field service managers to assign jobs to technicians
based on their location, availability, and skill set.
94 | Pranay Nandanwar

2. Job tracking and monitoring: This feature enables managers to track the progress of jobs in real-time,
and receive alerts when a job is running behind schedule or has been completed.
3. GPS tracking: This feature uses the Android device's GPS to track the location of technicians in real-
time, enabling managers to optimize their schedules and dispatch them to the nearest job site.
4. Customer management: This feature allows managers to store and access customer information,
including contact details, service history, and job notes.
5. Electronic invoicing and payments: This feature enables technicians to generate invoices and collect
payments electronically using their Android device.
6. Communication tools: This feature enables technicians to communicate with customers and
colleagues in real-time using text messaging, email, or video chat.
Overall, a field service application for Android can help companies improve their efficiency, reduce
costs, and enhance customer satisfaction by streamlining their field service operations.

c) Explain the Data handling function with example. S18


Data handling functions in Android are programming constructs that allow you to manage and
manipulate data within an Android application. There are various types of data handling functions
available in Android, including data storage, retrieval, and manipulation functions.
Here are some examples of data handling functions in Android:
1. SharedPreferences: This is a type of data storage function that allows you to store key-value pairs of
data in an Android application. SharedPreferences is typically used to store simple, small amounts of
data that need to be persistent across application sessions. For example, you could use
SharedPreferences to store a user's preference for the app's theme or language.

2. SQLite database: This is a type of data storage function that allows you to store and retrieve
structured data in an Android application. SQLite is a relational database management system that is
included with the Android operating system. You can use SQLite to store large amounts of structured
data, such as user profiles, app settings, or chat messages.

3. ContentProvider: This is a type of data handling function that provides a standardized interface for
accessing and sharing data between different Android applications. A ContentProvider allows you to
securely expose data to other applications, while also controlling access to that data. For example, you
could use a ContentProvider to allow other apps to access your app's data, such as contacts or calendar
events.

4. JSON and XML parsing: These are data manipulation functions that allow you to convert data
between different formats. JSON and XML are two common formats for exchanging data between
applications, and Android provides built-in classes for parsing and manipulating data in these formats.
For example, you could use JSON parsing functions to retrieve data from a remote server and display it
in your app.
95 | Pranay Nandanwar

Overall, data handling functions are an essential part of developing Android applications. By using these
functions effectively, you can manage and manipulate data in your app, allowing you to provide a better
user experience and build more powerful applications.
OR
AppWidgets are a type of Android application component that allow you to display data and provide
interaction from the home screen or lock screen. AppWidgets are typically used to display small
amounts of data or provide quick access to common tasks or actions.
AppWidgets can also use data handling functions in order to update their display with fresh data. Here
are some examples of data handling functions that are commonly used with AppWidgets in Android:
1. RemoteViews: This is a class that allows you to update the layout of an AppWidget from a service or
background thread. RemoteViews are used to create and update the views within an AppWidget, and
can be used to display data retrieved from a database or remote server. For example, you could use a
RemoteViews object to update an AppWidget with the latest weather data or news headlines.
2. ContentProvider: A ContentProvider can be used to provide data to an AppWidget. By defining a
ContentProvider within your app, you can allow other applications to access your app's data. This can
be useful for displaying data such as contacts or calendar events within an AppWidget.
3. BroadcastReceiver: A BroadcastReceiver can be used to receive updates or events that trigger
updates to an AppWidget. For example, you could use a BroadcastReceiver to update an AppWidget
when a new message is received or when the device's battery level changes.
4. SharedPreferences: SharedPreferences can be used to store and retrieve small amounts of data that
are persistent across application sessions. You can use SharedPreferences to store data such as user
preferences or settings that are used within an AppWidget.
Overall, data handling functions are an essential part of developing AppWidgets in Android. By using
these functions effectively, you can update your AppWidget with fresh data, provide users with useful
information, and make your application more engaging and interactive.

b) Create an app to demonstrate Analog clock. W19


Step 1: Create a new project in Android Studio and select "Empty Activity" as the template.
Step 2: Open the activity_main.xml file and add the following code to create the layout for the Analog
clock:

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
96 | Pranay Nandanwar

tools:context=".MainActivity">

<AnalogClock
android:id="@+id/analog_clock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />

</RelativeLayout>
```

In this code, we have used the `AnalogClock` widget to display the analog clock. We have also added
some attributes to center the clock in the middle of the screen.

Step 3: Open the MainActivity.java file and add the following code to initialize the Analog clock:

```java
public class MainActivity extends AppCompatActivity {

AnalogClock analogClock;

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

analogClock = (AnalogClock) findViewById(R.id.analog_clock);


}
}
```

In this code, we have initialized the `AnalogClock` widget in the `onCreate` method.
97 | Pranay Nandanwar

Step 4: Run the app on an emulator or physical device, and you should see the Analog clock displayed in
the center of the screen.

Analog Clock:
Analog clock is a widget used to display a two handed clock in which one for hour indicator and
other one is for minute indicator.

d) Write a program to show how to use Date picker control of ADK in your Android application S18
Step 1: Open Android Studio and create a new project. Select "Empty Activity" as the template.
Step 2: Open the activity_main.xml file and add the following code to create the layout for the
DatePicker:

```xml
<DatePicker
android:id="@+id/datePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
```
Step 3: Open the MainActivity.java file and add the following code to initialize the DatePicker and show
the selected date in a Toast message:

```java
public class MainActivity extends AppCompatActivity {
DatePicker datePicker;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
98 | Pranay Nandanwar

setContentView(R.layout.activity_main);

datePicker = (DatePicker) findViewById(R.id.datePicker);

// set the DatePicker to the current date


Calendar calendar = Calendar.getInstance();
datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// show the selected date in a Toast message
String selectedDate = dayOfMonth + "/" + (monthOfYear + 1) + "/" + year;
Toast.makeText(getApplicationContext(), "Selected Date: " + selectedDate,
Toast.LENGTH_SHORT).show();
}
});
}
}
```

In this code, we have initialized the `DatePicker` widget in the `onCreate` method. We have also set the
`DatePicker` to the current date and added an `OnDateChangedListener` to show the elected date in a
Toast message.
Step 4: Run the app on an emulator or physical device, and you should see the DatePicker displayed on
the screen. Select a date and you should see a Toast message showing the selected date.
d) Write a note on filter class in android. 4 W19

The Filter class in Android is used to perform filtering operations on data in a list or a
grid. It is commonly used with ListView and RecyclerView to filter items based on user
input. The Filter class provides a simple and efficient way to filter data without modifying
the original data source.

The Filter class is an abstract class that needs to be extended to implement custom
filtering logic. It contains two important methods that need to be overridden:
99 | Pranay Nandanwar

performFiltering(CharSequence constraint): This method is called in a background thread


to perform the actual filtering operation. It takes a CharSequence parameter that
represents the user input to filter the data.

publishResults(CharSequence constraint, FilterResults results): This method is called in


the UI thread to publish the filtering results. It takes a CharSequence parameter that
represents the user input and a FilterResults parameter that contains the filtered data.

You might also like