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

Android

The document provides an overview of mobile application development, focusing on the Android operating system, its architecture, and practical exercises related to its setup and programming. It includes comparisons with other operating systems, installation steps for development tools, and the importance of the Java Development Kit (JDK) for Android development. Additionally, it covers the build process in Android and practical tasks such as creating a virtual device and writing a simple application.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Android

The document provides an overview of mobile application development, focusing on the Android operating system, its architecture, and practical exercises related to its setup and programming. It includes comparisons with other operating systems, installation steps for development tools, and the importance of the Java Development Kit (JDK) for Android development. Additionally, it covers the build process in Android and practical tasks such as creating a virtual device and writing a simple application.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 197

Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 1: Compare various operating systems with Android


OS.

I. Theory:

Android is an operating system for mobile devices developed by google, which is


built upon Linux kernel. android competes with apple's iOS (for iPhone/iPad),
rim's blackberry, Microsoft’s windows phone, Symbian OS, and many other
proprietary mobile. the latest android supports phone/tablet, tv, wear (watch and
glass), automobile and internet of things.
operating system basics like definition of operating systems, features of operating
systems. what is the need of operating systems? basic architecture of operating
systems. different types of operating systems. distinguishing points between
different operating systems. 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 to develop only for android, and their applications
should be able to run on different devices powered by android. the first beta
version of the android software development kit (SDK) was released by google in
2007, whereas the first commercial version, android 1.0, was released in
September 2008. on June 27, 2012, at the google i/o conference, google announced
the next android version, 4.1 jelly bean. jelly bean is an incremental update, with
the primary aim of improving the user interface, both in terms of functionality and
performance. the source code for android is available under free and open-source
software licenses. google publishes most of the code under the Apache license
version 2.0 and the rest, Linux kernel changes, under the gnu general public
license version 2.

Maharashtra state Board of Technical Education 1


Mobile Application Development (22617) Harshal Dilip Makode

II. Practical related Questions

1. List different Android O.S. versions.


Ans:
Android 1.0
Android 1.1
Android 1.5 Cupcake
Android 1.6 Donut
Android 2.0/2.1 Eclair
Android 2.2 Froyo
Android 2.3 Gingerbread
Android 3.0/3.1/3.2 Honeycomb (primarily for tablets)
Android 4.0 Ice Cream Sandwich
Android 4.1/4.2/4.3 Jelly Bean
Android 4.4 KitKat
Android 5.0/5.1 Lollipop
Android 6.0 Marshmallow
Android 7.0/7.1 Nougat
Android 8.0/8.1 Oreo
Android 9 Pie
Android 10
Android 11
Android 12

2. State characteristics of android operating system


Ans:
The Android operating system is characterized by its open-source nature, built on the
Linux kernel, allowing for extensive customization of the user interface. With a vast
app ecosystem through the Google Play Store, support for multi-tasking, and a
comprehensive notification system, Android offers a diverse and user-friendly
experience. Integration with Google services, security features, and regular updates
enhance the overall functionality. However, device fragmentation due to various
manufacturers and custom ROM options contribute to the platform's versatility. The
OS supports a range of wireless connectivity options and is known for its adaptability
in the dynamic mobile device market.

Maharashtra state Board of Technical Education 2


Mobile Application Development (22617) Harshal Dilip Makode

III. Exercise

1. Draw the architectural diagram of Android operating system.


Ans:
The main components of android architecture are following:-
• Applications
• Application Framework
• Android Runtime
• Platform Libraries
• Linux Kernel

Maharashtra state Board of Technical Education 3


Mobile Application Development (22617) Harshal Dilip Makode

2. Differentiate between Windows operating system and Android operating


system.
Ans
Feature Windows Android
Device Types PCs, laptops, tablets, Smartphones, tablets,
servers smartwatches, TVs
User Interface Desktop environment, Start Touchscreen-optimized
menu with app icons, widgets
Application Ecosystem Diverse, includes desktop Primarily cantered around
software and Microsoft Google Play Store
Store apps
Source Code Closed source, proprietary Open source, allows
customization (custom
ROMs)
Integration with Microsoft services Google services (Gmail,
Services (OneDrive, Office, Cortana) Google Drive, Maps)
Updates and Release Periodic major updates, Frequent incremental
Cycle managed by Microsoft updates, adoption varies
among manufacturers
Customization Limited customization of Extensive customization
the interface options for manufacturers
and developers
Primary Use Case General-purpose computing Mobile and handheld
devices devices

IV. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 4


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 2: Install and configure java development kit (JDK),


Android studio and android SDK.

I. Theory:

Android is based on Linux with a set of native core C/C++ libraries. Android
applications are written in Java. However, they run on Android's own Java Virtual
Machine, called Dalvik Virtual Machine (DVM) (instead of JDK's JVM) which is
optimized to operate on the small and mobile devices. SDK provides a selection of
tools required to build Android apps or to ensure the process goes as smoothly as
possible. Whether creating an app with Java, Kotlin or C#, SDK should run on an
Android device and access unique features of the OS.
Step 1 - Setup Java Development Kit (JDK) You can download the latest version
of Java JDK from Oracle's Java site: Java SE Downloads. You will find
instructions for installing JDK in downloaded files, follow the given instructions to
install and configure the setup. Finally, set PATH and JAVA_HOME environment
variables to refer to the directory that contains java and javac, typically
java_install_dir/bin and java_install_dir respectively. If you are running Windows
and have installed the JDK in C:\jdk1.6.0_15, you would have to put the following
line in your C:\autoexec.batfile.
set
PATH=C:\jdk1.6.0_15\bin; %PATH% set JAVA_HOME=C:\jdk1.6.0_15
Step 2 - Setup Android SDK You can download the latest version of Android SDK
from Android’s official website: http://developer.android.com/sdk/index.html. If
you are installing SDK on Windows machine, then you will find ainstaller_rXX
windows.exe, so just download and run this exe which will launch Android SDK
Tool Setup wizard to guide you throughout the installation, so just follow the
instructions carefully. Finally, you will have Android SDK Tools installed on your
machine. If you are installing SDK either on Mac OS or Linux, check the
instructions provided along with the downloaded android-sdk_rXX-macosx.zip file
for Mac OS and android sdk_rXX-linux.tgz file for Linux. This tutorial will
consider that you are going to setup your environment on Windows machine
having Windows 7 operating system.
Step 3 - Setup Android Development Tools (ADT) Plugin This step will help you
in setting Android Development Tool plugin for Eclipse. Let's start with launching
Eclipse and then, choose Help > Software Updates > Install New Software. This
will display the following dialogue box.
Step 4 - Create Android Virtual Device to test your Android applications you will
need a virtual Android device. So before we start writing our code, let us create an
Android virtual device. Launch Android AVD Manager using Eclipse menu

Maharashtra state Board of Technical Education 5


Mobile Application Development (22617) Harshal Dilip Makode

options Window > AVD Manager> which will launch Android AVD Manager. Use
New button to create a new Android Virtual Device and enter the following
information, before clicking Create AVD button.

II. Practical related Questions

1. List all the steps to install android operating system.


Ans:
1. Download and install Android Studio on your computer.
2. Open Android Studio.
3. Use the SDK Manager in Android Studio to download necessary SDK components.
4. Create a virtual device (emulator) through the AVD Manager in Android Studio.
5. Configure the virtual device settings, including device type and system image.
6. Start the emulator by selecting your virtual device and clicking the "Play" button in
the AVD Manager.
7. Wait for the emulator to boot, which may take a few minutes.
8. Complete the initial Android setup process on the emulator.
9. Explore and use the Android operating system on the emulator for development and
testing.

2. List various IDEs that can be used to execute android operating system.
Ans:
1. Android Studio
2. Eclipse with ADT (Android Development Tools)
3. IntelliJ IDEA
4. Visual Studio with Xamarin
5. NetBeans
6. Unity with Android Build Support

Maharashtra state Board of Technical Education 6


Mobile Application Development (22617) Harshal Dilip Makode

III. Exercise

1. Differentiate between JVM and DVM.


Ans:
JVM(Java Virtual Machine) DVM(Dalvik Virtual Machine)

Stack-based VM that performs


Register-based VM that uses registers
arithmetic and logic operations through
located in the CPU to perform
push and pop operands. The result of
arithmetic and logic operations.
operations is stored in stack memory.

Source code files are first of all


compiled into Java bytecode format
Java source code is compiled into Java like JVM. Further, the DEX
bytecode format(.class file) that further compiler(dx tool) converts the Java
translates into machine code. bytecode into Dalvik
bytecode(classes.dex) file that will be
used to create the .apk file.

More information is required to the


Instruction size is larger as it needs to
VM for data loading and manipulation
encode the source and destination
as well as method loading in the stack
register of the VM.
data structure.

Compiled bytecode size is compact Compiled bytecode size is larger as


because the location of the operand is each instruction needs all implicit
implicitly on the operand stack. operands.

The executable file for the device The executable file for the device
is .jar file. is .apk file.

A single instance of JVM is configured The device runs multiple DVM


with shared processes and memory instances with a separate process in
space in order to run all deployed shared memory space to deploy the
applications. code of each application.

Supports multiple operating systems Support only the Android operation


like Linux, Windows, and Mac OS. system.

Maharashtra state Board of Technical Education 7


Mobile Application Development (22617) Harshal Dilip Makode

2. What is IDE? Why Java development toolkit is essential to install an


android operating system?
Ans
IDE (Integrated Development Environment): An Integrated Development
Environment is a software suite that consolidates the essential tools developers
need for software development in one application. IDEs typically include a code
editor, debugger, build automation tools, and sometimes a graphical user
interface for designing and testing. For Android development, Android Studio is
the official and widely used IDE.
Java Development Toolkit (JDK) and Android Operating System Installation:
The Java Development Toolkit (JDK) is necessary for Android app development
because Android applications are primarily written in the Java programming
language. Here's why JDK is essential:
1. Java as the Primary Language
2. Compilation of Java Code
3. Android Development Kit (SDK)
4. Android Studio Dependency
5. Compatibility with Android Studio

IV. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 8


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 3: Configure android development tools(ADT) plug-in


and create android virtual device.

I. Theory:

Configuration set up steps should be known beforehand as learnt in the practical no.2
Android Development Tools (ADT) is a plugin for the Android studio that is designed
to give you a powerful, integrated environment in which to build Android
applications. ADT extends the capabilities of Android studio to let you quickly set up
new Android projects, create an application UI, add components based on the Android
Framework API, debug your applications using the Android SDK tools, and even
export signed (or unsigned) APKs in order to distribute your application. Developing
in Android studio with ADT is highly recommended and is the fastest way to get
started. With the guided project setup, it provides, as well as tools integration, custom
XML editors, and debug output pane, ADT gives you an incredible boost in
developing Android applications.
Setting up Android Development Tools (ADT)
Get Android Development Tools (ADT) from ADT Bundle
The ADT Bundle includes everything you need to begin developing apps:
• Android studio + ADT plugin
• Android SDK Tools Android Platform-tools
• The latest Android platform
• The latest Android system image for the emulator

II. Practical related Questions

1. List basic requirements for configuring android operating system?


Ans:
1. Java Development Kit (JDK):
2. Android Studio
3. Android SDK (Software Development Kit)
4. Operating System
5. Hardware Requirements.
6. USB Driver (for device debugging)
7. Android Device (for testing)
8. Version Control System (Optional)
9. Integrated Development Environment (IDE) Preferences
10. Internet Connection

Maharashtra state Board of Technical Education 9


Mobile Application Development (22617) Harshal Dilip Makode

11. Emulator (Optional)


2. Why bytecode cannot run in Android?
Ans:
That's because Android uses Dalvik Virtual Machine and not traditional JVM. The
class file i.e. the byte code for Android is first optimized even more to make it mobile
friendly (Which usually has a custom format according to specifications of Dalvik
VM), which differs from normal bytecode. Hence direct JAVA bytecode won’t run.

III. Exercise

1. What is a Build Type in Gradle?


Ans:
Build types define certain properties that Gradle uses when building and packaging
your app, and are typically configured for different stages of your development
lifecycle.
There are two build types defined by default, debug and release, and you can
customize them and create additional build types.
The default debug build type enables debug options and signs the APK with the debug
key, while the release build type is not debuggable and can be configured to shrink,
obfuscate, and sign your APK with a release key for distribution.

2. Explain the build process in Android.


Ans:
The build process in Android involves several steps that transform your source code
and resources into an executable Android application. Here's an overview of the key
stages in the Android build process:
1. Source Code and Resources
2. Gradle Build System
3. Compilation of Java/Kotlin Code
4. Dex (Dalvik Executable) Conversion
5. Resource Processing
6. AndroidManifest.xml Merging
7. APK Packaging
8. Signing the APK
9. Debug vs. Release Builds
10. Build Variants and Product Flavors
11. Instant Run (Optional)

Maharashtra state Board of Technical Education 10


Mobile Application Development (22617) Harshal Dilip Makode

IV. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 11


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 4: Develop a program to display Hello World on


screen.

I. Theory:

In android studio students must be aware of the directory structure and the control
flow of the program. Program should be either executed on the android mobile phones
or on the suitable emulators. To execute a simple program, like to display Hello World
on screen syntax of writing a program in android is pre-requisite as the programming
language used is JAVA only. The main activity code is a Java file MainActivity.java.
This is the actual application file which ultimately gets converted to a Dalvik
executable and runs your application.
Following is the default code generated by the application wizard for Hello World!
application:
package com.example.helloworld; import android.os.Bundle;
import android.app.Activity; import android.view.Menu; import
android.view.MenuItem;
import android.support.v4.app.NavUtils; public class MainActivity extends
Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main,menu);
return true;
}
}
The Manifest File: Whatever component you develop as a part of your application,
you must declare all its components in a manifest file called AndroidManifest.xml
which resides at the root of the application project directory. This file works as an
interface between Android OS and your application, so if you do not declare your
component in this file, then it will not be considered by the OS. The <activity> tag is
used to specify an activity and android:name attribute specifies the fully qualified
class name of the Activity subclass and the android:label attributes specifies a string to

Maharashtra state Board of Technical Education 12


Mobile Application Development (22617) Harshal Dilip Makode

use as the label for the activity. You can specify multiple activities using <activity>
tags. The action for the intent filter is named android.intent.action.MAIN to indicate
that this activity serves as the entry point for the application. The category for the
intent- filter is named android.intent.category.LAUNCHER to indicate that the
application can be launched from the device's launcher icon. The @string refers to the
strings.xml file explained below. Hence, @string/app_name refers to the app_name
string defined in the strings.xml file, which is "HelloWorld". Similar way, other
strings get populated in the application. Following is the list of tags which you will
use in your manifest file to specify different Android application components:
1) <activity>elements for activities
2) <service> elements for services
3) <receiver> elements for broadcast receivers
4) <provider> elements for content providers

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 2 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 13


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno1.java

package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class Practicalno1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno1);
}
}

activity_practicalno1.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Practicalno1">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

</androidx.constraintlayout.widget.ConstraintLayout>

Maharashtra state Board of Technical Education 14


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 15


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 5: Develop a program to implement linear layout


and absolute layout.

I. Theory:

To develop and place the android components accurately on the display screen,
android provides various layout managers. Layout managers can be used on the
simple android program too. Various layout managers can be selected as per the
program requirements.
Layouts which are subclasses of View Group class and a typical layout defines
the visual structure for an Android user interface and can be created either at run
time using View/View Group objects or you can declare your layout using
simple XML file main_layout.xml which is located in the res/layout folder of
your project. layouts defined in XML file. A layout may contain any type of
widgets such as buttons, labels, textboxes etc. Layout Attributes Each layout has
a set of attributes which define the visual properties of that layout. There are
few common attributes among all the layouts and there are other attributes
which are specific to that layout. Types of layouts are Linear and Absolute
layouts.
Linear Layout: -

Maharashtra state Board of Technical Education 16


Mobile Application Development (22617) Harshal Dilip Makode

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 2 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

III. Program code

Practicalno5.java

package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class Practicalno5 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno5);
}
}

Maharashtra state Board of Technical Education 17


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno5.xml

1. Linear Layout: -

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".practicalno5">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />

</LinearLayout>

Maharashtra state Board of Technical Education 18


Mobile Application Development (22617) Harshal Dilip Makode

2. AbsoluteLayout

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


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno5">

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter your age"
android:layout_x="100dp"
android:layout_y="150dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_x="100dp"
android:layout_y="200dp" />

</AbsoluteLayout>

Maharashtra state Board of Technical Education 19


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 20


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 6: Develop a program to implement frame layout,


table layout and relative layout.

I. Theory:

To develop and place the android components accurately on the display screen,
android provides various layout managers. Layout managers can be used on the
simple android program too. Various layout managers can be selected as per the
program requirements.
1. Frame Layout:
Frame Layout is designed to block out an area on the screen to display a single
item. Generally, Frame Layout should be used to hold a single child view,
because it can be difficult to organize child views in a way that's scalable to
different screen sizes without the children overlapping each other. You can,
however, add multiple children to a Frame Layout and control their position
within the Frame Layout by assigning gravity to each child, using the android:
layout gravity attribute. Child views are drawn in a stack, with the most recently
added child on top. The size of the Frame Layout is the size of its largest child
(plus padding), visible or not (if the Frame Layout's parent permits).

2. Relative Layout:
A Relative Layout is a very powerful utility for designing a user interface
because it can eliminate nested view groups and keep your layout hierarchy flat,
which improves performance. If you find yourself using several nested Linear
Layout groups, you may be able to replace them with a single Relative Layout.

Maharashtra state Board of Technical Education 21


Mobile Application Development (22617) Harshal Dilip Makode

3. Table Layout:
A Table Layout consists of a number of Table Row objects, each defining a row
(actually, you can have other children, which will be explained below). Table
Layout containers do not display border lines for their rows, columns, or cells.
Each row has zero or more cells; each cell can hold one View object. The table
has as many columns as the row with the most cells. A table can leave cells
empty. Cells can span columns, as they can in HTML. The width of a column is
defined by the row with the widest cell in that column.

Maharashtra state Board of Technical Education 22


Mobile Application Development (22617) Harshal Dilip Makode

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 2 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

III. Program code

Practicalno6.java

package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class Practicalno6 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno6);
}
}

Maharashtra state Board of Technical Education 23


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno6.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".practicalno6">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#FFC107"
android:layout_marginBottom="16dp">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"/>

<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_gravity="center"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FrameLayout Example"
android:layout_gravity="top|center"/>

</FrameLayout>

Maharashtra state Board of Technical Education 24


Mobile Application Development (22617) Harshal Dilip Makode

<TableLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#4CAF50"
android:layout_marginBottom="16dp">

<TableRow>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"/>

<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/ic_launcher_foreground"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TableLayout Example"/>

</TableRow>

</TableLayout>

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#2196F3">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"/>

Maharashtra state Board of Technical Education 25


Mobile Application Development (22617) Harshal Dilip Makode

<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_centerInParent="true"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RelativeLayout Example"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="16dp"/>

</RelativeLayout>

</LinearLayout>

Maharashtra state Board of Technical Education 26


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 27


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 7: Develop a program to implement Text View and


Edit Text.

I. Theory:

In this practical, UI controls in android like Text view and edit view are studied.
Wherein the UI controls can be developed, used and placed on the screen using
different layout managers as per the problem statement requirements.
1. Text View:
In Android, Text View displays text to the user and optionally allows them to edit it
programmatically. Text View is a complete text editor; however basic class is
configured to not allow editing but we can edit it. View is the parent class of Text
View Being a subclass of view the text view component can be used in your app’s.
GUI inside a View Group, or as the content view of an activity. We can create a Text
View instance by declaring it inside a layout (XML file) or by instantiating it
programmatically (Java Class).
2. Edit Text:
In Android, Edit Text is a standard entry widget in android apps. It is an overlay over
Text View that configures itself to be editable. Edit Text is a subclass of Text View
with text editing operations. Often use Edit Text in our applications in order to provide
an input or text field, especially in forms. The simplest example of Edit Text is Login
or Sign-in form. Text Fields in Android Studio are basically Edit Text.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 2 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 28


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno7.java

package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class Practicalno7 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno7);
}
}

Maharashtra state Board of Technical Education 29


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno7.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".practicalno7">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Enter your text:"/>

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type here"/>

</LinearLayout>

Maharashtra state Board of Technical Education 30


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 31


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 8: Develop a program to implement Auto Complete


Text View.

I. Theory:

In this practical, UI controls in android like Text view and edit view are studied.
Wherein the UI controls can be developed, used and placed on the screen using
different layout managers as per the problem statement requirements.
Auto Complete Text View:
Android Auto Complete Text View completes the word based on the reserved words,
so no need to write all the characters of the word. Android Auto Complete Text View
is an editable text field, it displays a list of suggestions in a drop-down menu from
which user can select only one suggestion or value. Android Auto Complete Text View
is the subclass of Edit Text class. The Multi Auto Complete Text View is the subclass
of AutoComplete Text View class. An editable text view that shows completion
suggestions automatically while the user is typing. The list of suggestions is displayed
in a drop-down menu from which the user can choose an item to replace the content of
the edit box. The drop down can be dismissed at any time by pressing the back key or,
if no item is selected in the drop down, by pressing the enter centre key. The list of
suggestions is obtained from a data adapter and appears only after a given number of
characters defined by the threshold. Auto Complete Text View is a component used to
show suggestions while writing in an editable text field. The suggestions list is shown
in a drop-down menu from which a user can select the desired item. The list of
suggestions is obtained from an adapter and it appears only after a number of
characters that are specified in the threshold. To use an Auto Complete Threshold
field, it needs to be defined in the layout.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 2 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 32


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno8.java

package com.hdm.harshalmakodepractical;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class practicalno8 extends AppCompatActivity {


private EditText editText;
private AutoCompleteTextView autoCompleteTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno8);
editText = findViewById(R.id.editText);
autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
String[] countries = {"Country 1", "Country 2", "Country 3", "Country 4"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, countries);
autoCompleteTextView.setAdapter(adapter);
}
}

Maharashtra state Board of Technical Education 33


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno8.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=". practicalno8">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your text:"/>

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type here"/>

<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Select a country"/>

</LinearLayout>

Maharashtra state Board of Technical Education 34


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 35


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 9: Develop a program to implement Button, Image


Button and Toggle Button.

I. Theory:

In this practical, UI controls in android like Buttons are studied. There are various
types of buttons like Image button and toggle button which is studied.

1. Buttons-
In Android, Button represents a push button. The android. widget. Button is subclass
of Text View class and Compound Button is the subclass of Button class. A Push
buttons can be clicked, or pressed by the user to perform an action. There are different
types of buttons used in android such as Compound Button, Toggle Button, Radio
Button. Button is a subclass of Text View class and compound button is the subclass
of Button class. On a button we can perform different actions or events like click
event, pressed event, touch event etc. Android buttons are GUI components which are
sensible to taps (clicks) by the user. When the user taps/clicks on button in an Android
app, the app can respond to the click/tap. These buttons can be divided into two
categories: the first is Buttons with text on, and second is buttons with an image on.

2. Types of buttons–
Buttons can be divided into two categories the first is Buttons with text on, and second
is buttons with an image on.

3. Image Button –
A button with images on can contain both an image and a text. Android buttons with
images on are also called Image Button. In Android, Image Button is used to display a
normal button with a custom image in a button. In simple words we can say, Image
Button is a button with an image that can be pressed or clicked by the users. By
default it looks like a normal button with the standard button background that changes
the color during different button states. An image on the surface of a button is defined
within a xml (i.e. layout ) by using src attribute or within java class by using
setImageResource() method. We can also set an image or custom drawable in the
background of the image button . Image Button has all the properties of a normal
button so you can easily perform any event like click or any other event which you
can perform on a normal button.
Note: Standard button background image is displayed in the background of button
whenever you create an image button. To remove that image, you can define your own
background image in xml by using background attribute or in java class by using
setBackground() method.

Maharashtra state Board of Technical Education 36


Mobile Application Development (22617) Harshal Dilip Makode

4. Toggle Button-
A toggle button allows the user to change a setting between two states. You can add a
basic toggle button to your layout with the Toggle Button object. If you need to
change a button's state yourself, you can use the Compound Button.setChecked() or
Compound Button.toggle() method. To detect when the user activates the button or
switch, create a Compound Button. OnCheckedChangeListener object and assign it to
the button by calling setOnCheckedChangeListener().
It is beneficial if user have to change the setting between two states. It can be used to
On/Off Sound, Wi-Fi, Bluetooth etc. By default, the android Toggle Button will be in
OFF (Unchecked) state. We can change the default state of Toggle Button by using
android:checked attribute. In case, if we want to change the state of Toggle Button to
ON (Checked), then we need to set android:checked = "true" in our XML layout file.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 37


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno9.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.ToggleButton;

public class practicalno9 extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno9);
Button button = findViewById(R.id.button);
ImageButton imageButton = findViewById(R.id.imageButton);
ToggleButton toggleButton = findViewById(R.id.toggleButton);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(practicalno9.this, "Button Clicked",
Toast.LENGTH_SHORT).show();
}
});

imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(practicalno9.this, "ImageButton Clicked",
Toast.LENGTH_SHORT).show();
}
});

Maharashtra state Board of Technical Education 38


Mobile Application Development (22617) Harshal Dilip Makode

toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (toggleButton.isChecked()) {
Toast.makeText(practicalno9.this, "ToggleButton Checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno9.this, "ToggleButton Unchecked",
Toast.LENGTH_SHORT).show();
}
}
});
}
}

Maharashtra state Board of Technical Education 39


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno9.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".practicalno9">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_marginTop="20dp"/>

<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher_foreground"
android:layout_marginTop="20dp"
android:background="#5C24AA"
/>

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle"
android:layout_marginTop="20dp"/>
</LinearLayout>

Maharashtra state Board of Technical Education 40


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 41


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 10: Develop a program to implement login window


using above UI controls.

I. Theory:

In this practical, all the previous UI controls in android like Text View, Edit Text
Buttons which are studied are implemented in this practical. Events are also handled
on the android UI controls used in the practical.

A login application is the screen asking your credentials to login to some


particular application. You might have seen it when logging into facebook,
twitter etc. Define two Text View asking username and password of the user.
The password Text View must have input Type set to password.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 42


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno10.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class practicalno10 extends AppCompatActivity {


private EditText editTextUsername;
private EditText editTextPassword;
private TextView textViewResult;

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

editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
textViewResult = findViewById(R.id.textViewResult);
}

public void onLoginButtonClick(View view) {


String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();

if (username.equals("Harshal") && password.equals("harshal")) {


textViewResult.setText("Login successful!");
} else {
textViewResult.setText("Login failed. Please check your credentials.");
}
}
}

Maharashtra state Board of Technical Education 43


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno10.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".practicalno10">

<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:padding="10dp"/>

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:padding="10dp"
android:inputType="textPassword"/>

<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="20dp"
android:padding="10dp"
android:onClick="onLoginButtonClick"/>

<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"

Maharashtra state Board of Technical Education 44


Mobile Application Development (22617) Harshal Dilip Makode

android:text=""
android:textSize="18sp"
android:layout_gravity="center"/>

</LinearLayout>

Maharashtra state Board of Technical Education 45


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 46


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 11: Develop a program to implement Checkbox.

I. Theory:

Android CheckBox is a type of two state button either checked or unchecked. There
can be a lot of usage of checkboxes. For example, it can be used to know the hobby of
the user, activate/deactivate the specific action etc.

Android Checkbox class is the subclass of Compound Button class.

Methods of Checkbox class


There are many inherited methods of View, Text View, and Button classes in the
Checkbox class. Some of them are as follows:
• public boolean isChecked(): Returns true if it is checked otherwise false.
• public void setChecked(boolean status): Changes the state of the
Checkbox.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 47


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno11.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

public class practicalno11 extends AppCompatActivity {

CheckBox javaCheckbox, pythonCheckbox, kotlinCheckbox, cSharpCheckbox,


javascriptCheckbox;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno11);
javaCheckbox = findViewById(R.id.javaCheckbox);
pythonCheckbox = findViewById(R.id.pythonCheckbox);
kotlinCheckbox = findViewById(R.id.kotlinCheckbox);
cSharpCheckbox = findViewById(R.id.cSharpCheckbox);
javascriptCheckbox = findViewById(R.id.javascriptCheckbox);

javaCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(javaCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "Java is checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno11.this, "Java is unchecked",
Toast.LENGTH_SHORT).show();
}

Maharashtra state Board of Technical Education 48


Mobile Application Development (22617) Harshal Dilip Makode

}
});

pythonCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(pythonCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "Python is checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno11.this, "Python is unchecked",
Toast.LENGTH_SHORT).show();
}
}
});

kotlinCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(kotlinCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "Kotlin is checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno11.this, "Kotlin is unchecked",
Toast.LENGTH_SHORT).show();
} }
});

cSharpCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(cSharpCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "C# is checked",
Toast.LENGTH_SHORT).show();

Maharashtra state Board of Technical Education 49


Mobile Application Development (22617) Harshal Dilip Makode

} else {
Toast.makeText(practicalno11.this, "C# is unchecked",
Toast.LENGTH_SHORT).show();
} }
});

javascriptCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean
b) {
if(javascriptCheckbox.isChecked()) {
Toast.makeText(practicalno11.this, "JavaScript is checked",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(practicalno11.this, "JavaScript is unchecked",
Toast.LENGTH_SHORT).show();
}
}
});

}
}

Maharashtra state Board of Technical Education 50


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno11.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".practicalno11">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select the languages:"
android:textSize="30sp"/>

<CheckBox
android:id="@+id/javaCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:textSize="20sp"/>

<CheckBox
android:id="@+id/pythonCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Python"
android:textSize="20sp"/>

<CheckBox
android:id="@+id/kotlinCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kotlin"
android:textSize="20sp"/>

<CheckBox
android:id="@+id/cSharpCheckbox"

Maharashtra state Board of Technical Education 51


Mobile Application Development (22617) Harshal Dilip Makode

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C#"
android:textSize="20sp"/>

<CheckBox
android:id="@+id/javascriptCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JavaScript"
android:textSize="20sp"/>

</LinearLayout>

Maharashtra state Board of Technical Education 52


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 53


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 12: Develop a program to implement Radio Button


and Radio Group.

I. Theory:

Radio Buttons are used when we need to select only one item from a list of presented
items. If Radio Buttons are in Radio Group, when one Radio Button within a group is
selected, all others are automatically deselected. Android Checkbox class is the
subclass of Compound Button class.

Radio Button is generally used with Radio Group. Radio Group is a set of radio
buttons, marking one radio button as checked makes all other radio buttons as
unchecked. A radio button consists of two states – checked and unchecked. Clicking
an unchecked button changes its state to “checked” state and “unchecked” for the
previously selected radio button. To toggle a checked state to unchecked state, we
need to choose another item.
Following are the important attributes related to Radio Group control.
1. android:checkedButton : This is the id of child radio button that should be checked
by default within this radio group.
2. android:orientation : This property on the Radio group defines the orientation to
position its child view consisting of Radio Buttons.
Following are the few methods of radio button:
1. check(id): This sets the selection to the radio button whose identifier is
passed in parameter. -1 is used as the selection identifier to clear the selection.
2. clearCheck() : It clears the selection. When the selection is cleared, no radio
button in this group is selected and getCheckedRadioButtonId() returns null.
3. getCheckedRadioButtonId() : It returns the identifier of the selected radio
button in this group. If its empty selection, the returned value is-1.
4. setOnCheckedChangeListener(): This registers a callback to be invoked
when the checked radio button changes in this group. We must supply instance
of Radio Group. OnCheckedChangeListener to setOnCheckedChangeListener()
method.

Maharashtra state Board of Technical Education 54


Mobile Application Development (22617) Harshal Dilip Makode

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 55


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno12.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class practicalno12 extends AppCompatActivity {


RadioButton radioButton1;
RadioButton radioButton2;
RadioButton radioButton3;
RadioButton radioButton4;
RadioGroup radioGroup;

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

radioButton1 = findViewById(R.id.radioButton1);
radioButton2 = findViewById(R.id.radioButton2);
radioButton3 = findViewById(R.id.radioButton3);
radioButton4 = findViewById(R.id.radioButton4);
radioGroup = findViewById(R.id.radioGroup);

radioButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(practicalno12.this, "Selected Radio Button 1",
Toast.LENGTH_SHORT).show();
}
});

Maharashtra state Board of Technical Education 56


Mobile Application Development (22617) Harshal Dilip Makode

radioButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(practicalno12.this, "Selected Radio Button 2",
Toast.LENGTH_SHORT).show();
}
});

radioGroup.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int i) {
RadioButton selectedRadioButton = findViewById(i);
String selectedText = selectedRadioButton.getText().toString();
Toast.makeText(practicalno12.this, "Selected: " + selectedText,
Toast.LENGTH_SHORT).show();
}
});

}
}

Maharashtra state Board of Technical Education 57


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno12.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".practicalno12">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Single Radio Buttons"
android:textSize="20sp"
android:textAlignment="center"
/>

<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio Button 1" />

<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio Button 2" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Radio Button inside RadioGroup"
android:textSize="20sp"
android:textAlignment="center"
android:layout_marginTop="20dp"
/>

Maharashtra state Board of Technical Education 58


Mobile Application Development (22617) Harshal Dilip Makode

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>

<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />

<RadioButton
android:id="@+id/radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
</LinearLayout>

Maharashtra state Board of Technical Education 59


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 60


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 13: Develop a program to implement Progress Bar.

I. Theory:

Progress bars are used to show progress of a task. For example, when you are
uploading or downloading something from the internet, it is better to show the
progress of download/upload to the user. In android there is a class called Progress
Dialog that allows you to create progress bar.
A user interface element that indicates the progress of an operation. For a visual
overview of the difference between determinate and indeterminate progress modes,
see Progress & activity. Display progress bars to a user in a non-interruptive way.
Progress bar supports two modes to represent progress: determinate and
indeterminate.
Indeterminate Progress
Use indeterminate mode for the progress bar when you do not know how long an
operation will take. Indeterminate mode is the default for progress bar and shows a
cyclic animation without a specific amount of progress indicated.
Determinate Progress
Use determinate mode for the progress bar when you want to show that a specific
quantity of progress has occurred. For example, the percent remaining of a file being
retrieved, the amount records in a batch written to database, or the percent remaining
of an audio file that is playing.
Progress Dialog is a class that allows you to create progress bar. In order to do this,
you need to instantiate an object of this class. Its syntax is.
ProgressDialog dialog = new ProgressDialog(this);

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 61


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno13.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class practicalno13 extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno13);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(practicalno13.this, practicalno13_1.class);
startActivity(i);
}
},5000);
}
}

Maharashtra state Board of Technical Education 62


Mobile Application Development (22617) Harshal Dilip Makode

Practicalno13_1.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;

public class practicalno13_1 extends AppCompatActivity {


Button b1;
int finalI = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno131);
b1 = findViewById(R.id.b1);
Handler handler = new Handler();

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProgressDialog dialog=new ProgressDialog(practicalno13_1.this);
dialog.setCancelable(true);
dialog.setMessage("File downloading....");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setMax(100);
dialog.show();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i < 100;i++){
finalI = i;
try {
Thread.sleep(100);

Maharashtra state Board of Technical Education 63


Mobile Application Development (22617) Harshal Dilip Makode

} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
dialog.setProgress(finalI);
}
});
if(i == 99){
handler.post(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
});
}
}
}
}).start();
}
});
}
}

Maharashtra state Board of Technical Education 64


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno13.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".practicalno13">

<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading...."
android:layout_marginTop="20dp"
android:textSize="30dp"
android:textStyle="bold" />

</LinearLayout>

Maharashtra state Board of Technical Education 65


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno131.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno13_1"
android:orientation="vertical"
android:gravity="center">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DOWNLOAD FILE"
android:id="@+id/b1"
/>

</LinearLayout>

Maharashtra state Board of Technical Education 66


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 67


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 14: Develop a program to implement List View, Grid


View, Image View and Scroll View.

I. Theory:

A View occupies a rectangular area on the screen and is responsible for drawing and
event handling. View is the base class for widgets, which are used to create interactive
UI components (buttons, text fields, etc.). The View Group subclass is the base class
for layouts, which are invisible containers that hold other Views (or other View
Groups) and define their layout properties.
List View
List of scrollable items can be displayed in Android using List View. It helps you to
displaying the data in the form of a scrollable list. Users can then select any list item
by clicking on it. List View is default scrollable so we do not need to use scroll View
or anything else with List View.
List View is widely used in android applications. A very common example of List
View is your phone contact book, where you have a list of your contacts displayed in a
List View and if you click on it then user information is displayed.
Grid View
In android Grid View is a view group that display items in two-dimensional scrolling
grid (rows and columns), the grid items are not necessarily predetermined but they are
automatically inserted to the layout using a List Adapter. Users can then select any
grid item by clicking on it. Grid View is default scrollable so we don't need to use
Scroll View or anything else with Grid View.
Image View
In Android, Image View class is used to display an image file in application. Image
file is easy to use but hard to master in Android, because of the various screen sizes in
Android devices. An android is enriched with some of the best UI design widgets that
allows us to build good looking and attractive UI based application.
Scroll View
In android scroll View can hold only one direct child. This means that, if you have
complex layout with more views (Buttons, Text Views or any other view) then you
must enclose them inside another standard layout like Table Layout, Relative Layout
or Linear Layout. You can specify layout_width and layout_height to adjust width and
height of screen. You can specify height and width in dp(density pixel) or px(pixel).
Then after enclosing them in a standard layout, enclose the whole layout in scroll
View to make all the element or views scrollable.

Maharashtra state Board of Technical Education 68


Mobile Application Development (22617) Harshal Dilip Makode

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 69


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno14.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class practicalno14 extends AppCompatActivity {


ListView lv;
String[] subject =
{"Java","Javascript","C","C++","VB.net","Python","Assembly","Scripting
language","Java","Javascript","C","C++","VB.net","Python","Assembly","Scripting
language"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno14);
lv = findViewById(R.id.lv);

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,


android.R.layout.simple_list_item_1,subject);

lv.setAdapter(adapter);

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = adapter.getItem(position);

Maharashtra state Board of Technical Education 70


Mobile Application Development (22617) Harshal Dilip Makode

Toast.makeText(practicalno14.this,value,Toast.LENGTH_SHORT).show();
}
});

Handler handler = new Handler();


handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(practicalno14.this, practicalno14_1.class);
startActivity(i);
}
},5000);

}
}

Maharashtra state Board of Technical Education 71


Mobile Application Development (22617) Harshal Dilip Makode

Practicalno14_1.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;

public class practicalno14_1 extends AppCompatActivity {


GridView gv;
String[] subject =
{"Java","Javascript","C","C++","VB.net","Python","Assembly","Scripting
language","Java","Javascript","C","C++","VB.net","Python","Assembly"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno141);
gv = findViewById(R.id.gv);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,subject);

gv.setAdapter(adapter);

gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = adapter.getItem(position);
Toast.makeText(practicalno14_1.this,value,
Toast.LENGTH_SHORT).show();
}
});
}
}

Maharashtra state Board of Technical Education 72


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno14.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno14"
android:orientation="vertical">

<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

</LinearLayout>

activity_practicalno141.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno14_1"
android:orientation="vertical"
android:gravity="center">

<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/gv"
android:numColumns="3"
android:columnWidth="100dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"/>

</LinearLayout>

Maharashtra state Board of Technical Education 73


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 74


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 15: Develop a program to implement Custom Toast


Alert.

I. Theory:

An Android Toast is a small message displayed on the screen, similar to a tool tip or
other similar popup notification. Android Toast can be used to display information for
the short period of time. A toast contains message to be displayed quickly and
disappears after sometime. It provides simple feedback about an operation in a small
popup. A Toast is displayed on top of the main content of an activity. For example,
navigating away from an email before you send it triggers a "Draft saved toast to let
you know that you can continue editing later.
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 button on an email trigger a "Sending message..." toast
Following is the example to create a toast.
Toast toast = Toast.makeText(getApplicationContext(),
"This is a message displayed in a Toast",
Toast.LENGTH_SHORT); toast.show();

The Toast.makeText() method is a factory method which creates a Toast object. The
method takes 3 parameters. First the methods need a Context object which is obtained
by calling getApplicationContext(). Note: The getApplicationContext() method is a
method that exists inside activities, so the above code has to be located in an Activity
subclass to work.
The second parameter is the text to be displayed in the Toast. The third parameter is
the time duration the Toast is to be displayed.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 75


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno15.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class practicalno15 extends AppCompatActivity {


CheckBox checkBox1;
CheckBox checkBox2;
CheckBox checkBox3;

Button orderButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno15);
checkBox1 = findViewById(R.id.checkBox1);
checkBox2 = findViewById(R.id.checkBox2);
checkBox3 = findViewById(R.id.checkBox3);

orderButton = findViewById(R.id.orderButton);

// Set click listener for the button


orderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onOrderButtonClick(view);
}
});
}
private void onOrderButtonClick(View view) {

Maharashtra state Board of Technical Education 76


Mobile Application Development (22617) Harshal Dilip Makode

StringBuilder selectedItems = new StringBuilder();

if (checkBox1.isChecked()) {
selectedItems.append("Item 1: Rs. 10.0\n");
}
if (checkBox2.isChecked()) {
selectedItems.append("Item 2: Rs. 15.0\n");
}
if (checkBox3.isChecked()) {
selectedItems.append("Item 3: Rs. 20.0\n");
}

if (selectedItems.length() > 0) {
selectedItems.deleteCharAt(selectedItems.length() - 1);
Toast.makeText(this, "Selected Items and Prices:\n" + selectedItems.toString(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No items selected", Toast.LENGTH_SHORT).show();
}
}

Maharashtra state Board of Technical Education 77


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno15.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno15"
android:padding="16dp"
android:orientation="vertical">

<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 1"
android:layout_marginBottom="8dp"/>

<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 2"
android:layout_marginBottom="8dp"/>

<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 3"
android:layout_marginBottom="16dp"/>

<Button
android:id="@+id/orderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Order"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"/>
</LinearLayout>

Maharashtra state Board of Technical Education 78


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 79


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 16: Develop a program to implement Date and Time


Picker.

I. Theory:

Android provides controls for the user to pick a time or pick a date as ready-to-use
dialogs. Each picker provides controls for selecting each part of the time (hour,
minute, AM/PM) or date (month, day, year). Using these pickers helps ensure that
your users can pick a time or date that is valid, formatted correctly, and adjusted to the
user's locale.
Date Picker:
Android Date Picker allows you to select the date consisting of day, month and year in
your custom user interface. For this functionality android provides DatePicker and
DatePickerDialog components.
Time Picker:
Android Time Picker allows you to select the time of day in either 24 hour or AM/PM
mode. The time consists of hours, minutes and clock format. Android provides this
functionality through TimePicker class. Following xml attribute is used to create time
picker.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 80


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno16.java

package com.hdm.harshalmakodepractical;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;
public class practicalno16 extends AppCompatActivity {
Button btnDatePicker, btnTimePicker;
EditText txtDate, txtTime;
private int mYear, mMonth, mDay, mHour, mMinute;

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

btnDatePicker=(Button)findViewById(R.id.btn_date);
btnTimePicker=(Button)findViewById(R.id.btn_time);
txtDate=(EditText)findViewById(R.id.in_date);
txtTime=(EditText)findViewById(R.id.in_time);

btnDatePicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);

Maharashtra state Board of Technical Education 81


Mobile Application Development (22617) Harshal Dilip Makode

mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);

DatePickerDialog datePickerDialog = new


DatePickerDialog(practicalno16.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" +
year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});

btnTimePicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);

TimePickerDialog timePickerDialog = new


TimePickerDialog(practicalno16.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
txtTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
});
}
}

Maharashtra state Board of Technical Education 82


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno16.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno16"
android:padding="16dp">

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_date"
android:layout_marginTop="82dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT DATE"
android:id="@+id/btn_date"
android:layout_alignBottom="@+id/in_date"
android:layout_toRightOf="@+id/in_date"
android:layout_toEndOf="@+id/in_date" />

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_time"
android:layout_below="@+id/in_date"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT TIME"

Maharashtra state Board of Technical Education 83


Mobile Application Development (22617) Harshal Dilip Makode

android:id="@+id/btn_time"
android:layout_below="@+id/btn_date"
android:layout_alignLeft="@+id/btn_date"
android:layout_alignStart="@+id/btn_date" />

</RelativeLayout>

Maharashtra state Board of Technical Education 84


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 85


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 17: Develop a program to create an activity.

I. Theory:

An activity represents a single screen with a user interface. For example, an email
application might have one activity that shows a list of new emails, another activity to
compose an email, and one for reading emails.

An activity is the single screen in android. It is like window or frame of Java.


By the help of activity, you can place all your UI components or widgets in a
single screen.
If an application has more than one activity, then one of them should be marked
as the activity that is presented when the application is launched.
As in C, C++ or Java programming language program starts from main ()
function, android system initiates its program within an Activity starting with a
call on onCreate() method. Android Activity class is the subclass of
ContextThemeWrapper class. An activity class loads all the UI component using
the XML file available in res/layout folder of the project. Following statement
loads UI components from res/layout/activity_main.xmlfile:
setContentView(R.layout.activity_main);
To write our own activity the new activity must be the derived from
Activity class as given below

public class MainActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Code goes here*/
}
/** Called when the activity is about to become visible. */
@Override
protected void onStart() {
super.onStart();
/*Code goes here*/
}
/** Called when the activity has become visible. */
@Override

Maharashtra state Board of Technical Education 86


Mobile Application Development (22617) Harshal Dilip Makode

protected void onResume() {


super.onResume();
/*Code goeshere*/
}
/** Called when another activity is taking focus. */
@Override
protected void onPause() {
super.onPause();
/*Code goes here*/
}
/** Called when the activity is no longer visible. */
@Override
protected void onStop() {
super.onStop();
/*Code goes here*/
}
/** Called just before the activity is destroyed. */
@Override
public void onDestroy() {
super.onDestroy();
/*Code goes here*/
}
}

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 87


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno16.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

public class practicalno17 extends AppCompatActivity {


String TAG = "Practical no 17";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno17);
Log.d(TAG, "onCreate: Activity created");
}

@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: Activity started");
}

@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: Activity resumed");
}

@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: Activity paused");
}

@Override

Maharashtra state Board of Technical Education 88


Mobile Application Development (22617) Harshal Dilip Makode

protected void onStop() {


super.onStop();
Log.d(TAG, "onStop: Activity stopped");
}

@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: Activity destroyed");
}

@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart: Activity restarted");
}
}

Maharashtra state Board of Technical Education 89


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 90


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 18: Develop a program to implement new activity


using explicit intent and implicit intent.

I. Theory:

Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc. It facilitates communication
between different android components.
Android application components can connect to other Android applications. This
connection is based on a task description represented by an Intent object.
Intents are asynchronous messages which allow application components to request
functionality from other Android components. Intents allow you to interact with
components from the same applications as well as with components contributed by
other applications. For example, an activity can start an external activity for taking a
picture.
Mostly Intents are used for:
a. For Launching an Activity
b. To start a New Service
c. For Broadcasting Messages
d. To Display a list of contacts in List View
Types of intents:
There are two types of intents
a. Implicit Intent
b. Explicit Intent
Implicit Intent:
The implicit intent is the intent where instead of defining the exact components, you
define the action that you want to perform for different activities.
Syntax:
Intent i=new Intent();
i.setAction(Intent.ACTION_SEND);
Explicit Intent:
An explicit intent is an Intent where you explicitly define the component that needs to
be called by the Android System. An explicit intent is one that you can use to launch a
specific app component, such as a particular activity or service in your app.
Syntax:
Intent I = new
Intent(getApplicationContext(), NextActivity.class);
I.putExtra("value1", "This value for Next Activity");
I.putExtra("value2", "This value for Next Activity");

Maharashtra state Board of Technical Education 91


Mobile Application Development (22617) Harshal Dilip Makode

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 92


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno18.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class practicalno18 extends AppCompatActivity {


EditText numberInput;
Button factorialButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno18);
numberInput = findViewById(R.id.editTextNumber);
factorialButton = findViewById(R.id.factorialButton);
factorialButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String inputStr = numberInput.getText().toString();
if (!inputStr.isEmpty()) {
int number = Integer.parseInt(inputStr);
Intent intent = new Intent(practicalno18.this, practicalno18_1.class);
intent.putExtra("NUMBER", number);
startActivity(intent);
}
}
});
}
}

Maharashtra state Board of Technical Education 93


Mobile Application Development (22617) Harshal Dilip Makode

Practicalno18_1.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class practicalno18_1 extends AppCompatActivity {


TextView resultTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno181);
resultTextView = findViewById(R.id.resultTextView);

Intent intent = getIntent();


int number = intent.getIntExtra("NUMBER", 0);

long factorial = calculateFactorial(number);

resultTextView.setText("Factorial of " + number + " is: " + factorial);


}

long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}

Maharashtra state Board of Technical Education 94


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno18.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno18"
android:padding="16dp">

<EditText
android:id="@+id/editTextNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number" />

<Button
android:id="@+id/factorialButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/editTextNumber"
android:text="Factorial"
android:layout_marginLeft="15dp"/>

</RelativeLayout>

Maharashtra state Board of Technical Education 95


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno18_1.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno18_1">

<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="18sp" />

</RelativeLayout>

Maharashtra state Board of Technical Education 96


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 97


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 19: Develop a program to implement content


provider.

I. Theory:

Content Provider is one of the pillars of Android. It is a component which


i)- hides database details (database name, table name, column info. etc.)
ii)- allows the application to share data among multiple applications.
A content provider component supplies data from one application to other on request.
Such requests are handled by the methods of the Content Resolver class. A content
provider can use different ways to store its data and the data can be stored in a
database, in files, or even over a network.
Content providers let you centralize content in one place and have many different
applications access it as needed. A content provider behaves very much like a database
where you can query it, edit its content, as well as add or delete content using insert(),
update(), delete(), and query() methods. In most cases this data is stored in an SQlite
database.
A content provider is implemented as a subclass of Content Provider class and must
implement a standard set of APIs that enable other applications to perform
transactions.
public class MyApp extends Content Provider
{
}

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 98


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Content_Provider.java

package com.hdm.harshalmakodepractical;

import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.HashMap;

public class Content_Provider extends ContentProvider {

static final String PROVIDER_NAME = "com.demo.product.provider";


static final String URL = "content://" + PROVIDER_NAME + "/products";
static Uri CONTENT_URI = Uri.parse(URL);

private HashMap<String, String> values = null;

private SQLiteDatabase db = null;

static final String id = "id";


static final String name = "name";
static final String price = "price";
static final int uriCode = 1;
UriMatcher uriMatcher = null;

final String DATABASE_NAME = "ProductDB";


final String TABLE_NAME = "products";
private static final int DATABASE_VERSION = 1;

Maharashtra state Board of Technical Education 99


Mobile Application Development (22617) Harshal Dilip Makode

public Content_Provider() {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

uriMatcher.addURI(PROVIDER_NAME, "products", uriCode);

// to access a particular row


// of the table
uriMatcher.addURI(
PROVIDER_NAME,
"products/*",
uriCode
);
}

@Override
public boolean onCreate() {
MyProductDatabaseHelper dbHelper = new
MyProductDatabaseHelper(getContext());
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
} else return false;
}

@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable
String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);

if (uriMatcher.match(uri) == uriCode) {
queryBuilder.setProjectionMap(values);
} else {
throw new IllegalArgumentException("Unknown URI " + uri);
}

if (sortOrder == null || sortOrder.equals("")) {


sortOrder = id;
}

Maharashtra state Board of Technical Education 100


Mobile Application Development (22617) Harshal Dilip Makode

Cursor cursor =
queryBuilder.query(db, projection, selection, selectionArgs, null, null,
sortOrder);

cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}

@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
long rowID = db.insert(TABLE_NAME, "", contentValues);
if (rowID > 0) {
Uri tempUri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(tempUri, null);
return tempUri;
}
throw new SQLiteException("Failed to add a record into " + uri);
}

@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues,
@Nullable String selection, @Nullable String[] selectionArgs) {
int count;
if (uriMatcher.match(uri) == uriCode) {
count = db.update(TABLE_NAME, contentValues, selection, selectionArgs);
} else {
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}

@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable
String[] selectionArgs) {
int count;
if (uriMatcher.match(uri) == uriCode) {
count = db.delete(TABLE_NAME, selection, selectionArgs);

Maharashtra state Board of Technical Education 101


Mobile Application Development (22617) Harshal Dilip Makode

} else {
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}

@Nullable
@Override
public String getType(@NonNull Uri uri) {
if (uriMatcher.match(uri) == uriCode) {
return "vnd.android.cursor.dir/products";
} else {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}

/*
* Database helper class
* */
private class MyProductDatabaseHelper extends SQLiteOpenHelper {
//sql query to create a new table
String CREATE_DB_TABLE =
(" CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY
KEY AUTOINCREMENT, name TEXT NOT NULL, price NUMBER NOT
NULL);");

public MyProductDatabaseHelper(@Nullable Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_DB_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int
newVersion) {
database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

Maharashtra state Board of Technical Education 102


Mobile Application Development (22617) Harshal Dilip Makode

onCreate(database);
}
}
}

Practicalno19.java

package com.hdm.harshalmakodepractical;

import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class practicalno19 extends AppCompatActivity {


EditText productNameEditText, productPriceEditText;
Button addProductButton,b1;

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

productNameEditText = findViewById(R.id.productNameEditText);
productPriceEditText = findViewById(R.id.productPriceEditText);
addProductButton = findViewById(R.id.addProductButton);

b1 = findViewById(R.id.b1);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

Maharashtra state Board of Technical Education 103


Mobile Application Development (22617) Harshal Dilip Makode

Intent i = new Intent(practicalno19.this,practicalno19_1.class);


startActivity(i);
}
});

addProductButton.setOnClickListener(view -> {
//get product name and price
String productName = productNameEditText.getText().toString();
String productPrice = productPriceEditText.getText().toString();

if (!productName.isEmpty() && !productPrice.isEmpty()) {


//Key-value object to add value in the database
ContentValues values =new ContentValues();
values.put(Content_Provider.name, productName);
values.put(Content_Provider.price, productPrice);

//insert data using Content URI


Uri uri = getContentResolver().insert(Content_Provider.CONTENT_URI,
values);
Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please fill all fields",
Toast.LENGTH_SHORT).show();
}
});
}
}

Maharashtra state Board of Technical Education 104


Mobile Application Development (22617) Harshal Dilip Makode

Practicalno19.java

package com.hdm.harshalmakodepractical;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class practicalno19_1 extends AppCompatActivity {


Button refreshButton;
TextView myTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno191);
refreshButton = findViewById(R.id.refreshButton);
myTextView = findViewById(R.id.myTextView);

refreshButton.setOnClickListener(view -> {

Uri contactUri = Uri.parse("content://com.demo.product.provider/products");

String[] projection = null;


String selectionClause = null;
String[] selectionArguments = null;
String sortOrder = null;
Cursor cursor = getContentResolver().query(
contactUri,
projection,
selectionClause,
selectionArguments,
sortOrder
);

//our product data string

Maharashtra state Board of Technical Education 105


Mobile Application Development (22617) Harshal Dilip Makode

StringBuilder stringBuilder = new StringBuilder();

//check cursor and iterate over


if (cursor != null && cursor.moveToFirst()) {
do {
stringBuilder.append("ID: ");

stringBuilder.append(cursor.getString(cursor.getColumnIndexOrThrow("id")));

stringBuilder.append("\t");
stringBuilder.append("\t");

stringBuilder.append("Name: ");

stringBuilder.append(cursor.getString(cursor.getColumnIndexOrThrow("name")));

stringBuilder.append("\t");
stringBuilder.append("\t");

stringBuilder.append("Price: ");

stringBuilder.append(cursor.getString(cursor.getColumnIndexOrThrow("price")));

stringBuilder.append("\n");
stringBuilder.append("\n");

} while (cursor.moveToNext());
//close the cursor object
cursor.close();
} else {
stringBuilder.append("Noting to show");
}
//set string value in textView
myTextView.setText(stringBuilder);
});
}
}

Maharashtra state Board of Technical Education 106


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno19.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno19">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:orientation="vertical"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp">

<EditText
android:id="@+id/productNameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Product Name"
android:inputType="textPersonName"
tools:ignore="Autofill" />

<EditText
android:id="@+id/productPriceEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="Enter Product Price"
android:inputType="numberDecimal"
tools:ignore="Autofill" />

<Button
android:id="@+id/addProductButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"

Maharashtra state Board of Technical Education 107


Mobile Application Development (22617) Harshal Dilip Makode

android:layout_marginTop="15dp"
android:textColor="@color/white"
android:textAlignment="center"
android:text="Add New Product" />

<Button
android:id="@+id/b1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show result"
android:layout_marginTop="15dp"/>

</LinearLayout>
</RelativeLayout>

Maharashtra state Board of Technical Education 108


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno191.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno19_1">

<Button
android:id="@+id/refreshButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="refresh products"
android:textColor="@color/white" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/refreshButton">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:textColor="@color/black"
android:layout_height="wrap_content" />
</LinearLayout>

</ScrollView>
</RelativeLayout>

Maharashtra state Board of Technical Education 109


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 110


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 20: Develop a program to implement service.

I. Theory:

In android, Service is a component which keep an app running in the background to


perform long running operations based on our requirements. For Service, we don’t
have any user interface and it will run the apps in background like playing the music
in background or handle network operations when the user in different app.
A service is a component which runs in the background without direct interaction with
the user. As the service has no user interface, it is not bound to the lifecycle of an
activity.
Services are used for repetitive and potentially long running operations, i.e., Internet
downloads, checking for new data, data processing, updating content providers.
Services run with a higher priority than inactive or invisible activities and therefore it
is less likely that the Android system terminates them. Services can also be configured
to be restarted if they get terminated by the Android system once sufficient system
resources are available again.
There are the three different types of services:
1. Foreground service
2. Background service
3. Bound service

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 111


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

MyService.java

package com.hdm.harshalmakodepractical;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {


MediaPlayer myPlayer;

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.faded);
myPlayer.setLooping(false);
}

@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
myPlayer.start();
}

@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
}
}

Maharashtra state Board of Technical Education 112


Mobile Application Development (22617) Harshal Dilip Makode

Practicalno20.java

package com.hdm.harshalmakodepractical;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class practicalno20 extends AppCompatActivity {
Button buttonStart, buttonStop,buttonNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno20);
buttonStart = findViewById(R.id.buttonStart);
buttonStop = findViewById(R.id.buttonStop);
buttonNext = findViewById(R.id.buttonNext);
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(new Intent(practicalno20.this, MyService.class));
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(new Intent(practicalno20.this, MyService.class));
}
});
buttonNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(practicalno20.this,practicalno20_1.class);
startActivity(intent);
}
});
}
}

Maharashtra state Board of Technical Education 113


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno20.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno20">

<Button
android:id="@+id/buttonStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Start Service" />

<Button
android:id="@+id/buttonStop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/buttonStart"
android:text="Stop Service" />

<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="100dp"
android:text="Next Page" />

</RelativeLayout>

Maharashtra state Board of Technical Education 114


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 115


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 21: Develop a program to implement broadcast


receiver.

I. Theory:

Broadcast Receivers simply respond to broadcast messages from other applications or


from the system. For example, applications can also initiate broadcasts to let other
applications know that some data has been downloaded to the device and is available
for them to use, so this is broadcast receiver who will intercept this communication
and will initiate appropriate action.

Creating the Broadcast Receiver:


A broadcast receiver is implemented as a subclass of Broadcast Receiver class and
overriding the onReceive() method where each message is received as an Intent object
parameter.

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.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 116


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno21.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class practicalno21 extends AppCompatActivity {

private MyReceiver myReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

myReceiver = new MyReceiver();


IntentFilter filter2 = new
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
IntentFilter filter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
filter.addAction("custom.action.MY_INTENT");
filter2.addAction("custom.action.MY_INTENT");
registerReceiver(myReceiver, filter);
registerReceiver(myReceiver, filter2);

setContentView(R.layout.activity_practicalno21);
}

@Override
protected void onDestroy() {
unregisterReceiver(myReceiver);

Maharashtra state Board of Technical Education 117


Mobile Application Development (22617) Harshal Dilip Makode

super.onDestroy();
}

// Define your BroadcastReceiver class


public static class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Toast.makeText(context, "Boot Completed!",
Toast.LENGTH_SHORT).show();
} else if (intent.getAction().equals("custom.action.MY_INTENT")) {
Toast.makeText(context, "Custom Intent Received!",
Toast.LENGTH_SHORT).show();
} else if
(intent.getAction().equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
Toast.makeText(context, "AIRPLANE MODE CHANGED!",
Toast.LENGTH_LONG).show();
}
}
}
}
}

Maharashtra state Board of Technical Education 118


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno21.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".practicalno21">

<Button
android:id="@+id/broadcastButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Broadcast Intent"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
/>

</RelativeLayout>

Maharashtra state Board of Technical Education 119


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 120


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 22: Develop a program to implement sensors.

I. Theory:

Most of the android devices have built-in sensors that measure motion, orientation,
and various environmental condition. Android allows us to get the raw data from these
sensors and use it in our application.
The android platform supports three broad categories of sensors. Motion Sensors,
Environmental sensors, Position sensors. Some of the sensors are hardware based and
some are software-based sensors. Whatever the sensor is, android allows us to get the
raw data from these sensors and use it in our application. For this, android provides us
with some classes. Android provides Sensor Manager and Sensor classes to use the
sensors in our application. In order to use sensors, first thing you need to do is to
instantiate the object of SensorManager class.
Example: SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
The next thing you need to do is to instantiate the object of Sensor class by calling the
getDefaultSensor() method of the SensorManager class. Its syntax is given below:
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
Once that sensor is declared, you need to register its listener and override two methods
which are onAccuracyChanged and onSensorChanged. Its syntax is as follows:
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) { }

Methods:
1. getDefaultSensor(int type) :- This method get the default sensor for a given type.
Explain methods
2. getOrientation(float[] R, float[] values) :- This method returns a description of the
current primary clip on the clipboard but not a copy of its data.
3. getInclination(float[] I) :- This method computes the geomagnetic inclination angle
in radians from the inclination matrix.
4. registerListener(SensorListener listener, int sensors, int rate) :-This method registers
a listener for the sensor.
5. unregisterListener(SensorEventListener listener, Sensor sensor) :-This method
unregisters a listener for the sensors with which it is registered.
6. getOrientation(float[] R, float[] values) :-This method computes the device's
orientation based on the rotation matrix.

Maharashtra state Board of Technical Education 121


Mobile Application Development (22617) Harshal Dilip Makode

7. getAltitude(float p0, float p) :-This method computes the Altitude in meters from
the atmospheric pressure and the pressure at sea-level.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 122


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno22.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class practicalno22 extends AppCompatActivity implements


SensorEventListener {
SensorManager sensorManager;
Sensor accelerometer;
LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno22);

layout = findViewById(R.id.layout);
sensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
accelerometer =
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

if (accelerometer == null) { } else {


sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}
displaySensorList();

Maharashtra state Board of Technical Education 123


Mobile Application Development (22617) Harshal Dilip Makode

private void displaySensorList() {


SensorManager sensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
TextView sensorListTextView = findViewById(R.id.sensorListTextView);

StringBuilder sensorList = new StringBuilder();


for (Sensor sensor : sensorManager.getSensorList(Sensor.TYPE_ALL)) {
sensorList.append(sensor.getName()).append("\n");
}

sensorListTextView.setText(sensorList.toString());
}

@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];

if (x > 5 || y > 5 || z > 5) {


layout.setBackgroundColor(Color.GREEN);
} else {
layout.setBackgroundColor(Color.WHITE);
}
}

@Override
public void onAccuracyChanged(Sensor sensor, int i) { }

Maharashtra state Board of Technical Education 124


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno22.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=". practicalno22">

<TextView
android:id="@+id/sensorListTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sensor List:"
android:textSize="18sp"
android:textStyle="bold" />

</LinearLayout>

Maharashtra state Board of Technical Education 125


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 126


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 23: Develop a program to build Camera.

I. Theory:

The Android framework includes support for various cameras and camera features
available on devices, allowing you to capture pictures and videos in your application.
Camera can be used in your application in following ways.
1. Using existing android camera application in our application
2. Directly using Camera API provided by android in our application
You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera
application installed on your phone. Its syntax is given below:
Intent intent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
We will be using the camera API to integrate the camera in our application. First you
will need to initialize the camera object using the static method provided by the api
called Camera. Open. Its syntax is:
Camera object = null;
object = Camera.open();
Methods:
1. startActivityForResult(Intent intent, int requestCode, Bundle options) It starts an
activity, but can take extra bundle of options withit.
2. startActivityFromChild(Activity child, Intent intent, int requestCode) It launchesthe
activity when your activity is child of any otheractivity.
3. startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle
options) It work same as above, but it can take extra values in the shape of bundle
with it.
4. startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)It
launches activity from the fragment you are currentlyinside.
5. startActivityFromFragment(Fragment fragment, Intent intent, intrequestCode,
Bundle options) It not only launches the activity from the fragment, but can take extra
values withit.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 127


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno23.java

package com.hdm.harshalmakodepractical;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.Manifest;
import android.widget.VideoView;

public class practicalno23 extends AppCompatActivity {


private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int REQUEST_VIDEO_CAPTURE = 2;
private static final int REQUEST_CAMERA_PERMISSION = 100;
private ImageView imageView;
private VideoView videoView;
private Button captureImageButton, captureVideoButton;
private Uri imageUri;

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

imageView = findViewById(R.id.imageView);
captureImageButton = findViewById(R.id.captureImageButton);

Maharashtra state Board of Technical Education 128


Mobile Application Development (22617) Harshal Dilip Makode

captureVideoButton = findViewById(R.id.captureVideoButton);
videoView = findViewById(R.id.videoView);

// Check if the CAMERA permission is not granted


if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED) {
// Request CAMERA permission
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
} else {
// Permission is already granted, proceed with camera action
setupCaptureButtonListeners();
}
}

private void setupCaptureButtonListeners() {


captureImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});

captureVideoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakeVideoIntent();
}
});
}

private void dispatchTakePictureIntent() {


Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}

private void dispatchTakeVideoIntent() {

Maharashtra state Board of Technical Education 129


Mobile Application Development (22617) Harshal Dilip Makode

Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);


if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
// Display the captured image in the ImageView
if (data != null && data.getExtras() != null) {
Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
if (imageBitmap != null) {
imageView.setImageBitmap(imageBitmap);
} else {
Toast.makeText(this, "Error capturing image",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No data received from camera",
Toast.LENGTH_SHORT).show();
}
} else if (requestCode == REQUEST_VIDEO_CAPTURE) {
Uri videoUri = data.getData();
if (videoUri != null) {
// Display the captured video in the VideoView
videoView.setVideoURI(videoUri);
videoView.start();
} else {
Toast.makeText(this, "Error capturing video",
Toast.LENGTH_SHORT).show();
}
}
}
}

Maharashtra state Board of Technical Education 130


Mobile Application Development (22617) Harshal Dilip Makode

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
setupCaptureButtonListeners();
} else {
Toast.makeText(this, "Camera permission denied",
Toast.LENGTH_SHORT).show();
}
}
}

Maharashtra state Board of Technical Education 131


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno23.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".practicalno23"
android:orientation="vertical"
android:weightSum="5">

<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:src="@android:drawable/ic_menu_camera" />

<Button
android:id="@+id/captureImageButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:text="Capture Image" />

<Button
android:id="@+id/captureVideoButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:text="Capture Video" />

<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"/>

</LinearLayout>

Maharashtra state Board of Technical Education 132


Mobile Application Development (22617) Harshal Dilip Makode

AndriodManifest.xml

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


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

<uses-feature android:name="android.hardware.camera" />


<uses-permission android:name="android.permission.CAMERA" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.HarshalMakodePractical"
tools:targetApi="31">

<activity
android:name=".Practicalno23"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>

</application>

</manifest>

Maharashtra state Board of Technical Education 133


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 134


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 24: Develop a program for providing Bluetooth


connectivity.

I. Theory:

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.
1. Scan for other Bluetooth devices
2. Get a list of paired devices.
3. Connect to other devices through service discovery.
Android provides Bluetooth Adapter class to communicate with Bluetooth. Create an
object of this calling by calling the static method getDefaultAdapter(). Its syntax is
given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following
Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Once you enable the Bluetooth, you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of Bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 135


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno24.java

package com.hdm.harshalmakodepractical;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.util.Set;

public class practicalno24 extends AppCompatActivity {


private BluetoothAdapter bluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView deviceListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno24);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth is not supported on this
device", Toast.LENGTH_LONG).show();
finish();
}

Maharashtra state Board of Technical Education 136


Mobile Application Development (22617) Harshal Dilip Makode

Button getVisibleBtn = findViewById(R.id.btnGetVisible);

getVisibleBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
makeDeviceVisible();
}
});
Button turnOnBtn = findViewById(R.id.btnTurnOn);
Button turnOffBtn = findViewById(R.id.btnTurnOff);
Button listDevicesBtn = findViewById(R.id.btnListDevices);
deviceListView = findViewById(R.id.deviceListView);

enableBluetooth();

turnOnBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
enableBluetooth();
}
});

turnOffBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
disableBluetooth();
}
});

listDevicesBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listPairedDevices();
}
});
}

private void enableBluetooth() {


if (!bluetoothAdapter.isEnabled()) {

Maharashtra state Board of Technical Education 137


Mobile Application Development (22617) Harshal Dilip Makode

if
(checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(new
String[]{android.Manifest.permission.BLUETOOTH_CONNECT}, 1);
} else {
if (bluetoothAdapter != null) {
Intent enableBluetoothIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, 1);
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is not supported on
this device", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already turned on",
Toast.LENGTH_SHORT).show();
}
}

private void disableBluetooth() {


if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
Toast.makeText(getApplicationContext(), "Bluetooth turned off",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already turned off",
Toast.LENGTH_SHORT).show();
}
}

private void listPairedDevices() {


if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.BLUETOOTH_CONNECT) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
pairedDevices = bluetoothAdapter.getBondedDevices();

Maharashtra state Board of Technical Education 138


Mobile Application Development (22617) Harshal Dilip Makode

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,


android.R.layout.simple_list_item_1);

if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
adapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
adapter.add("No paired devices found");
}

deviceListView.setAdapter(adapter);
}

private void makeDeviceVisible() {


if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Bluetooth is not turned on",
Toast.LENGTH_SHORT).show();
return;
}

Intent discoverableIntent = new


Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATI
ON, 300);
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.BLUETOOTH_ADVERTISE) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(discoverableIntent);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode == 1) {

Maharashtra state Board of Technical Education 139


Mobile Application Development (22617) Harshal Dilip Makode

if (grantResults.length > 0 && grantResults[0] ==


PackageManager.PERMISSION_GRANTED &&
grantResults.length > 1 && grantResults[1] ==
PackageManager.PERMISSION_GRANTED) {
// Both Bluetooth permissions are granted, proceed with enabling Bluetooth
enableBluetooth();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth permissions are
required to enable Bluetooth", Toast.LENGTH_SHORT).show();
}
}
}
}

Maharashtra state Board of Technical Education 140


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno24.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno24">

<Button
android:id="@+id/btnTurnOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On Bluetooth"
android:layout_centerHorizontal="true"/>

<Button
android:id="@+id/btnTurnOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn Off Bluetooth"
android:layout_below="@id/btnTurnOn"
android:layout_centerHorizontal="true"/>

<Button
android:id="@+id/btnListDevices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Paired Devices"
android:layout_below="@id/btnTurnOff"
android:layout_centerHorizontal="true"/>

<Button
android:id="@+id/btnGetVisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Visible"
android:layout_below="@id/btnListDevices"
android:layout_centerHorizontal="true"/>

Maharashtra state Board of Technical Education 141


Mobile Application Development (22617) Harshal Dilip Makode

<ListView
android:id="@+id/deviceListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnGetVisible"/>
</RelativeLayout>

Maharashtra state Board of Technical Education 142


Mobile Application Development (22617) Harshal Dilip Makode

AndriodManifest.xml

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


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

<uses-feature android:name="android.hardware.bluetooth"
android:required="true" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADVERTISE" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.HarshalMakodePractical"
tools:targetApi="31">

<activity
android:name=".Practicalno24"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>

</application>

</manifest>

Maharashtra state Board of Technical Education 143


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 144


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 25: Develop a program for animation.

I. Theory:

Animation is the process of creating motion and shape change. Tween Animation
takes some parameters such as start value, end value, size, time duration, rotation
angle etc., and perform the required animation on that object. It can be applied to any
type of object.
In order to perform animation in android, we are going to call a static function
loadAnimation() 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.myanimation);
In order to apply this animation to an object, we will just call the startAnimation()
method of the object. Its syntax is:
ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);
Methods:
1. start(): This method starts the animation.
2. setDuration(long duration) :This method sets the duration of an animation.
3. getDuration() : This method gets the duration which is set by above method.
4. end() : This method ends the animation.
5. cancel() : This method cancels the animation.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 145


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno25.java

package com.hdm.harshalmakodepractical;

import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

public class practicalno25 extends AppCompatActivity {

private ImageView imageView1;

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

imageView1 = findViewById(R.id.imageView1);

// Set up the animations


final Animation rotateAnimation =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
final Animation zoomAnimation =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom);
final Animation fadeInOutAnimation =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in_out);

// Set up onClick listeners for the buttons


Button buttonRotate = findViewById(R.id.buttonRotate);
Button buttonZoom = findViewById(R.id.buttonZoom);
Button buttonFade = findViewById(R.id.buttonFade);

buttonRotate.setOnClickListener(new View.OnClickListener() {
@Override

Maharashtra state Board of Technical Education 146


Mobile Application Development (22617) Harshal Dilip Makode

public void onClick(View v) {


imageView1.startAnimation(rotateAnimation);
}
});

buttonZoom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView1.startAnimation(zoomAnimation);
}
});

buttonFade.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView1.startAnimation(fadeInOutAnimation);
}
});
}

// Optional: You can define these methods if you set onClick in XML
public void onRotateButtonClick(View view) {

imageView1.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.rotate));
}

public void onZoomButtonClick(View view) {

imageView1.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.zoom));
}

public void onFadeButtonClick(View view) {

imageView1.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in_out));
}
}

Maharashtra state Board of Technical Education 147


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno25.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno25">

<ImageView
android:id="@+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@android:drawable/ic_dialog_alert"
android:layout_centerInParent="true"
android:scaleType="fitXY" />

<Button
android:id="@+id/buttonRotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rotate"
android:layout_below="@id/imageView1"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true"
android:onClick="onRotateButtonClick" />

<Button
android:id="@+id/buttonZoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Zoom"
android:layout_below="@id/buttonRotate"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true"
android:onClick="onZoomButtonClick" />

<Button
android:id="@+id/buttonFade"
android:layout_width="wrap_content"

Maharashtra state Board of Technical Education 148


Mobile Application Development (22617) Harshal Dilip Makode

android:layout_height="wrap_content"
android:text="Fade"
android:layout_below="@id/buttonZoom"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true"
android:onClick="onFadeButtonClick" />

</RelativeLayout>

Maharashtra state Board of Technical Education 149


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 150


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 26: Perform Async task using SQLite.

I. Theory:

Android AsyncTask is an abstract class provided by Android which gives us the


liberty to perform heavy tasks in the background and keep the UI thread light thus
making the application more responsive.
Android application runs on a single thread when launched. Due to this single thread
model tasks that take longer time to fetch the response can make the application non-
responsive. To avoid this, we use android AsyncTask to perform the heavy tasks in
background on a dedicated thread and passing the results back to the UI thread. Hence
use of AsyncTask in android application keeps the UI thread responsive at all times.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 151


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno26.java

package com.hdm.harshalmakodepractical;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class practicalno26 extends AppCompatActivity {


private EditText etName, etAge;
private Button btnInsert;

private static final String DATABASE_NAME = "mydatabase";


private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "mytable";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";

private SQLiteDatabase database;

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

etName = findViewById(R.id.etName);
etAge = findViewById(R.id.etAge);
btnInsert = findViewById(R.id.btnInsert);

Maharashtra state Board of Technical Education 152


Mobile Application Development (22617) Harshal Dilip Makode

MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);


database = dbHelper.getWritableDatabase();

btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = etName.getText().toString();
String ageString = etAge.getText().toString();

if (name.isEmpty() || ageString.isEmpty()) {
Toast.makeText(practicalno26.this, "Please enter name and age",
Toast.LENGTH_SHORT).show();
return;
}

int age = Integer.parseInt(ageString);

new InsertDataTask().execute(name, String.valueOf(age));


}
});
}

private class InsertDataTask extends AsyncTask<String, Void, Void> {


@Override
protected Void doInBackground(String... params) {
String name = params[0];
int age = Integer.parseInt(params[1]);

database.execSQL("INSERT INTO " + TABLE_NAME + " (" +


COLUMN_NAME + ", " + COLUMN_AGE + ") VALUES ('" + name + "', " + age +
");");

Log.d("InsertDataTask", "Data inserted successfully - Name: " + name + ",


Age: " + age);

return null;
}

@Override
protected void onPostExecute(Void aVoid) {

Maharashtra state Board of Technical Education 153


Mobile Application Development (22617) Harshal Dilip Makode

super.onPostExecute(aVoid);
Toast.makeText(practicalno26.this, "Data inserted successfully",
Toast.LENGTH_SHORT).show();
}
}

private static class MyDatabaseHelper extends SQLiteOpenHelper {


MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " TEXT," +
COLUMN_AGE + " INTEGER);");

Log.d("MyDatabaseHelper", "Database created successfully");


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}

Maharashtra state Board of Technical Education 154


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno26.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno26"
android:padding="16dp">

<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"/>

<EditText
android:id="@+id/etAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/etName"
android:layout_marginTop="8dp"
android:inputType="number"
android:hint="Enter Age"/>

<Button
android:id="@+id/btnInsert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/etAge"
android:layout_marginTop="16dp"
android:text="Insert Data"/>

</RelativeLayout>

Maharashtra state Board of Technical Education 155


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 156


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 27: Create sample application with login module.


(Check username and password) On successful login, Change Text
View “Login Successful” and on login fail, alert user using Toast
“Login fail”.

I. Theory:

This day Login and Registration form in Android are part of every application. So,
when we are programming, we work with many registration forms. Forms can be very
different from a simple login or registration to a complex ordering form for any
application.
A login application is the screen asking your credentials to login to some particular
application. You might have seen it when logging into Facebook, twitter etc. First you
have to define two Text View asking username and password of the user.
Define a button with login text.
In the java file, inside the method of onClick get the username and passwords text
using getText() and toString() method and match it with the text using equals()
function.
The last thing you need to do is to provide a security mechanism, so that unwanted
attempts should be avoided. For this initialize a variable and on each false attempt,
decrement it. And when it reaches to 0, disable the login button.

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 157


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno27.java

package com.hdm.harshalmakodepractical;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class practicalno27 extends AppCompatActivity {


private EditText editTextUsername, editTextPassword;
private Button buttonLogin;
private TextView textViewAttempts;
private int loginAttempts = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno27);
editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
buttonLogin = findViewById(R.id.buttonLogin);
textViewAttempts = findViewById(R.id.textViewAttempts);

buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();

if (isValidCredentials(username, password)) {
showLoginSuccess();
} else {
loginAttempts--;

Maharashtra state Board of Technical Education 158


Mobile Application Development (22617) Harshal Dilip Makode

textViewAttempts.setText("Attempts remaining: " + loginAttempts);

if (loginAttempts <= 0) {
buttonLogin.setEnabled(false);
showLoginFailure("Login disabled. Too many failed attempts.");
} else {
showLoginFailure("Invalid username or password. Try again.");
}
}
}
});
}

private boolean isValidCredentials(String username, String password) {


// Replace this with your authentication logic
return username.equals("Harshal") && password.equals("harshal123");
}

private void showLoginSuccess() {


Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT).show();
}

private void showLoginFailure(String message) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}

Maharashtra state Board of Technical Education 159


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno27.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno27"
android:padding="16dp">

<TextView
android:id="@+id/textViewUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:layout_marginTop="16dp"/>

<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewUsername"
android:layout_marginTop="8dp"
android:inputType="text"/>

<TextView
android:id="@+id/textViewPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_below="@id/editTextUsername"
android:layout_marginTop="16dp"/>

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewPassword"
android:layout_marginTop="8dp"

Maharashtra state Board of Technical Education 160


Mobile Application Development (22617) Harshal Dilip Makode

android:inputType="textPassword"/>

<TextView
android:id="@+id/textViewAttempts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attempts remaining: 3"
android:layout_below="@id/editTextPassword"
android:layout_marginTop="16dp"/>

<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/textViewAttempts"
android:layout_marginTop="16dp"/>

</RelativeLayout>

Maharashtra state Board of Technical Education 161


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 162


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 28: Create login application where you will have to
validate username and password till the username and password is
not validated, login button should remain disabled.

I. Theory:

This day Login and Registration form in Android are part of every application out
there. So, when we are programming, we work with many registration forms. Forms
can be very different from a simple login or registration to a complex ordering form
for any application.
With registration, how you can check data that the user has entered with simple
validation. Validation can check many conditions. We can verify if an email address is
a valid email and if a user entered all the required data, for instance, we check if Edit
Text is empty for the first and last name. We can prepare a way to notify the user that
the data is not valid. On login activity, we should check for password length. There are
a few things login and registration form need:
• Clean user interface.
• Validation (check if the email is an email and if the user entered all the data).
• Notifications for the user that the data is incorrect.
• Instructions for the user (e.g. how many characters are required for password).

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 163


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno28.java

package com.hdm.harshalmakodepractical;

import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;

public class practicalno28 extends AppCompatActivity {


private EditText editTextUsername, editTextPassword;
private Button buttonLogin;
private TextView textViewAttempts;
private int loginAttempts = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno28);
editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
buttonLogin = findViewById(R.id.buttonLogin);
textViewAttempts = findViewById(R.id.textViewAttempts);

buttonLogin.setEnabled(false);

TextWatcher textWatcher = new TextWatcher() {


@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

Maharashtra state Board of Technical Education 164


Mobile Application Development (22617) Harshal Dilip Makode

boolean isValidInput = isUsernameValid(s.toString()) &&


isPasswordValid(editTextPassword.getText().toString());
buttonLogin.setEnabled(isValidInput);
}

@Override
public void afterTextChanged(Editable s) {
}
};

editTextUsername.addTextChangedListener(textWatcher);
editTextPassword.addTextChangedListener(textWatcher);

buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();

if (isValidCredentials(username, password)) {
showLoginSuccess();
} else {
loginAttempts--;
textViewAttempts.setText("Attempts remaining: " + loginAttempts);

if (loginAttempts <= 0) {
buttonLogin.setEnabled(false);
showLoginFailure("Login disabled. Too many failed attempts.");
} else {
showLoginFailure("Invalid username or password. Try again.");
}
}
}
});
}

private boolean isUsernameValid(String username) {


return username.length() >= 8;
}

Maharashtra state Board of Technical Education 165


Mobile Application Development (22617) Harshal Dilip Makode

private boolean isPasswordValid(String password) {


return password.length() >= 8;
}

private boolean isValidCredentials(String username, String password) {


return username.equals("Harshal@") && password.equals("harshal123");
}

private void showLoginSuccess() {


Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT).show();
}

private void showLoginFailure(String message) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}

Maharashtra state Board of Technical Education 166


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno28.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno28"
android:padding="16dp">

<TextView
android:id="@+id/textViewUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:layout_marginTop="16dp"/>

<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewUsername"
android:layout_marginTop="8dp"
android:inputType="text"/>

<TextView
android:id="@+id/textViewPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_below="@id/editTextUsername"
android:layout_marginTop="16dp"/>

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewPassword"
android:layout_marginTop="8dp"

Maharashtra state Board of Technical Education 167


Mobile Application Development (22617) Harshal Dilip Makode

android:inputType="textPassword"/>

<TextView
android:id="@+id/textViewAttempts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attempts remaining: 3"
android:layout_below="@id/editTextPassword"
android:layout_marginTop="16dp"/>

<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/textViewAttempts"
android:layout_marginTop="16dp"
android:enabled="false"/>

</RelativeLayout>

Maharashtra state Board of Technical Education 168


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 169


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 29: Develop a program to: a) Send SMS b) Receive


SMS

I. Theory:

Android devices can send and receive messages to or from any other phone that
supports Short Message Service (SMS). Android offers the Messenger application that
can send and receive SMS messages.
A host of third-party apps for sending and receiving SMS messages are also available
in Google Play. The SMS protocol was primarily designed for user-to-user
communication and is not well-suited for apps that want to transfer data. You should
not use SMS to send data messages from a web server to your app on a user device.
SMS is neither encrypted nor strongly authenticated on either the network or the
device
Access to the SMS features of an Android device is protected by user permissions.
Just as your app needs the user's permission to use phone features, so also does an app
need the user's permission to directly use SMS features.
You have two choices for sending SMS messages:
• Use an implicit Intent to launch a messaging app such as Messenger, with the
ACTION_SENDTOaction.
• Send the SMS message using the sendTextMessage() method or other methods of the
SmsManagerclass.
To receive SMS messages, the best practice is to use the onReceive() method of the
Broadcast Receiver class. The Android framework sends out system broadcasts of
events such as receiving an SMS message, containing intents that are meant to be
received using a Broadcast Receiver. Your app receives SMS messages by listening
for the SMS_RECEIVED_ACTION broadcast.
Methods :
1 ArrayList<String> divideMessage(String text) :-This method divides a message text
into several fragments, none bigger than the maximum SMS message size.
2 static SmsManager getDefault() :- This method is used to get the default instance of
the Sms Manager
3 void sendDataMessage(String destination Address, String scAddress, short
destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent):-
This method is used to send a data based SMS to a specific application port.
4 void sendTextMessage(String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent) :-Send a text based SMS.

Maharashtra state Board of Technical Education 170


Mobile Application Development (22617) Harshal Dilip Makode

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 171


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno29.java

package com.hdm.harshalmakodepractical;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class practicalno29 extends AppCompatActivity {


private EditText editTextPhoneNumber, editTextMessage;
private Button buttonSend;
private TextView textView;
private static final int REQUEST_SMS_PERMISSION = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno29);
editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
editTextMessage = findViewById(R.id.editTextMessage);
buttonSend = findViewById(R.id.buttonSend);

Maharashtra state Board of Technical Education 172


Mobile Application Development (22617) Harshal Dilip Makode

textView = findViewById(R.id.textView);

registerReceiver(smsReceiver, new
IntentFilter("android.provider.Telephony.SMS_RECEIVED"));

buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phoneNumber = editTextPhoneNumber.getText().toString();
String message = editTextMessage.getText().toString();

if (!phoneNumber.isEmpty() && !message.isEmpty()) {


if (checkAndRequestPermission()) {
sendSMS(phoneNumber, message);
}
} else {
Toast.makeText(practicalno29.this, "Please enter phone number and
message", Toast.LENGTH_SHORT).show();
}
}
});

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}

private boolean checkAndRequestPermission() {


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
REQUEST_SMS_PERMISSION);
return false;

Maharashtra state Board of Technical Education 173


Mobile Application Development (22617) Harshal Dilip Makode

} else {
return true;
}
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_SMS_PERMISSION) {
// Check if the permission is granted
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission granted, proceed with sending SMS
String phoneNumber = editTextPhoneNumber.getText().toString();
String message = editTextMessage.getText().toString();
sendSMS(phoneNumber, message);
} else {
// Permission denied, show a message or handle accordingly
Toast.makeText(this, "SMS permission denied",
Toast.LENGTH_SHORT).show();
}
}
}

private void sendSMS(String phoneNumber, String message) {


try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(this, "SMS sent successfully",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to send SMS", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}

private BroadcastReceiver smsReceiver = new BroadcastReceiver() {

Maharashtra state Board of Technical Education 174


Mobile Application Development (22617) Harshal Dilip Makode

@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])
pdu);
String senderPhoneNumber = smsMessage.getOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
displayReceivedSMS(senderPhoneNumber, messageBody);
}
}
}
}
};

private void displayReceivedSMS(String sender, String message) {


String currentText = textView.getText().toString();
String newText = "Sender: " + sender + "\nMessage: " + message + "\n\n" +
currentText;
textView.setText(newText);
}
}

Maharashtra state Board of Technical Education 175


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno29.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno29"
android:padding="16dp">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Received SMS will be displayed here." />

<EditText
android:id="@+id/editTextPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_marginTop="16dp"
android:hint="Enter phone number"/>

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextPhoneNumber"
android:layout_marginTop="8dp"
android:hint="Enter message"/>

<Button
android:id="@+id/buttonSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send SMS"
android:layout_below="@id/editTextMessage"
android:layout_marginTop="16dp"/>
</RelativeLayout>

Maharashtra state Board of Technical Education 176


Mobile Application Development (22617) Harshal Dilip Makode

AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.HarshalMakodePractical"
tools:targetApi="28" >
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity
android:name=".practicalno29"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Maharashtra state Board of Technical Education 177


Mobile Application Development (22617) Harshal Dilip Makode

SmsReceiver.java

package com.hdm.harshalmakodepractical;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
String senderPhoneNumber = smsMessage.getOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
displayReceivedSMS(context, senderPhoneNumber, messageBody);
}
}
}
}

private void displayReceivedSMS(Context context, String sender, String message)


{
String toastMessage = "Received SMS from: " + sender + "\nMessage: " +
message;
Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
}
}

Maharashtra state Board of Technical Education 178


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 179


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 30: Develop a program to send and receive e-mail.

I. Theory:

To send email from your Android application, you have to write an Activity that needs
to launch an email client and sends an email using your Android device. This practical
focuses on integrating the existing email clients in the new applications.
Intent Object - Action to send Email:
You will use ACTION_SEND action to launch an email client installed on your
Android device. Following is simple syntax to create an intent with ACTION_SEND
action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);
Intent Object – Data Type to send Email
To send an email you need to specify mailto: as URI using setData() method and data
type will be to text/plain using setType() method as follows:
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 180


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno30.java

package com.hdm.harshalmakodepractical;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class practicalno30 extends AppCompatActivity {

private EditText recipientEditText;


private EditText subjectEditText;
private EditText bodyEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno30);
recipientEditText = findViewById(R.id.editRecipient);
subjectEditText = findViewById(R.id.editSubject);
bodyEditText = findViewById(R.id.editBody);
}

public void sendEmail(View view) {


// Retrieve user-defined values
String recipient = recipientEditText.getText().toString().trim();
String subject = subjectEditText.getText().toString().trim();
String body = bodyEditText.getText().toString().trim();

// Create an Intent with ACTION_SEND action


Intent emailIntent = new Intent(Intent.ACTION_SEND);

// Set the data type for the email


emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");

Maharashtra state Board of Technical Education 181


Mobile Application Development (22617) Harshal Dilip Makode

// Set the email recipient


emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient});

// Set the email subject


emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);

// Set the email body


emailIntent.putExtra(Intent.EXTRA_TEXT, body);

// Verify that the device has an email client to handle this intent
if (emailIntent.resolveActivity(getPackageManager()) != null) {
// Start the email client
startActivity(emailIntent);
}
}
}

Maharashtra state Board of Technical Education 182


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno30.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno30"
android:padding="16dp">

<EditText
android:id="@+id/editRecipient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Recipient Email" />
<EditText
android:id="@+id/editSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editRecipient"
android:layout_marginTop="16dp"
android:hint="Email Subject" />
<EditText
android:id="@+id/editBody"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editSubject"
android:layout_marginTop="16dp"
android:hint="Email Body" />
<Button
android:id="@+id/btnSendEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editBody"
android:layout_marginTop="16dp"
android:text="Send Email"
android:onClick="sendEmail" />

</RelativeLayout>

Maharashtra state Board of Technical Education 183


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 184


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 31: Deploy map-based application. Part I

I. Theory:

Android allows us to integrate google maps in our application. You can show any
location on the map, or can show different routes on the map. You can also customize
the map according to your choices.
Add the map fragment into xml layout file. Its syntax is given below –
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Add some permissions along with the Google Map
API key in the AndroidManifest.XML file. Its syntax is given below:
<!--Permissions-->
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.
READ_GSERVICES" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STO
RAGE" />

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 185


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno31.java

package com.hdm.harshalmakodepractical;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class practicalno31 extends FragmentActivity implements


OnMapReadyCallback {
private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno31);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;
LatLng Warora = new LatLng(20.246368, 79.023188);
mMap.addMarker(new MarkerOptions().position(Warora).title("Marker in
Warora"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(Warora,13
),4000,null);
}
}

Maharashtra state Board of Technical Education 186


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno31.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno31">

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

Maharashtra state Board of Technical Education 187


Mobile Application Development (22617) Harshal Dilip Makode

AndroidManifest.xml

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


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

<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
/><uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.HarshalMakodePractical"
tools:targetApi="28">

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAxF2PlYeU8Bry0pk1vdC0Tu7KTeLjxj0U" />

<activity
android:name=".practicalno31"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>
</manifest>

Maharashtra state Board of Technical Education 188


Mobile Application Development (22617) Harshal Dilip Makode

build.gradle

dependencies {

implementation 'com.google.android.gms:play-services-maps:18.0.2'

implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

Maharashtra state Board of Technical Education 189


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 190


Mobile Application Development (22617) Harshal Dilip Makode

Practical No. 32: Deploy map-based application. Part II

I. Theory:

Android allows us to integrate google maps in our application. You can show any
location on the map, or can show different routes on the map. You can also customize
the map according to your choices.
Methods available in the Google Map class are given below.
1. addCircle(CircleOptions options) : This method add a circle to the map
2. addPolygon(PolygonOptions options) : This method add a polygon to the map
3. addTileOverlay(TileOverlayOptions options) : This method add tile overlay to the
map
4. animateCamera(CameraUpdate update) : This method Moves the map according to
the update with an animation
5. clear() : This method removes everything from the map
6. getMyLocation() : This method returns the currently displayed user location
7. moveCamera(CameraUpdate update) : This method repositions the camera
according to the instructions defined in the update
8. setTrafficEnabled(boolean enabled) : This method Toggles the traffic layer on or off
9. snapshot(GoogleMap.SnapshotReadyCallback callback) : This method Takes a
snapshot of the map
10. stopAnimation() : This method stops the camera animation if there is one in
progress

II. Resources required

Sr. No. Instrument Specification Quantity Remarks


/Object
1. Android enabled 8 GB RAM 1 Data cable is
smartphone / Android mandatory for
version supporting emulators
emulator

Maharashtra state Board of Technical Education 191


Mobile Application Development (22617) Harshal Dilip Makode

III. Program code

Practicalno32.java

package com.hdm.harshalmakodepractical;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

public class practicalno32 extends FragmentActivity implements


OnMapReadyCallback {
private GoogleMap mMap;
private Polyline routePolyline;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practicalno32);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(@NonNull GoogleMap googleMap) {

Maharashtra state Board of Technical Education 192


Mobile Application Development (22617) Harshal Dilip Makode

mMap = googleMap;
LatLng warora = new LatLng(20.246368, 79.023188);
mMap.addMarker(new MarkerOptions().position(warora).title("Marker in
Warora"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(warora, 13),
4000, null);
LatLng origin = new LatLng(20.246368, 79.023188);
LatLng destination = new LatLng(20.994957, 78.204946);
drawRoute(mMap, origin, destination);
mMap.addCircle(new CircleOptions()

.center(warora).fillColor(Color.parseColor("#9F6FFF76")).strokeColor(Color.GREEN
).radius(300)
);
}

private void drawRoute(GoogleMap googleMap, LatLng origin, LatLng


destination) {
if (routePolyline != null) {
routePolyline.remove();
}
PolylineOptions polylineOptions = new PolylineOptions()
.add(origin, destination)
.width(10)
.color(Color.BLUE);
routePolyline = googleMap.addPolyline(polylineOptions);
}
}

Maharashtra state Board of Technical Education 193


Mobile Application Development (22617) Harshal Dilip Makode

activity_practicalno32.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".practicalno32"
android:weightSum="1"
android:orientation="vertical">

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.9"/>

<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thank You"
android:onClick="next"
android:layout_gravity="center"/>

</LinearLayout>

Maharashtra state Board of Technical Education 194


Mobile Application Development (22617) Harshal Dilip Makode

AndroidManifest.xml

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


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

<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
/><uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.HarshalMakodePractical"
tools:targetApi="28">

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAxF2PlYeU8Bry0pk1vdC0Tu7KTeLjxj0U" />

<activity
android:name=".practicalno32"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>
</manifest>

Maharashtra state Board of Technical Education 195


Mobile Application Development (22617) Harshal Dilip Makode

build.gradle

dependencies {

implementation 'com.google.android.gms:play-services-maps:18.0.2'

implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

Maharashtra state Board of Technical Education 196


Mobile Application Development (22617) Harshal Dilip Makode

IV. Output

V. Marks Obtained

Marks Obtained Dated signature of


Teacher

Process Related Product Total


(10) Related (15) (25)

Maharashtra state Board of Technical Education 197

You might also like