0% found this document useful (0 votes)
20 views56 pages

Android Practical File PDF

The document outlines the practical assignments for an Android Programming laboratory course at Rayat Bahra Institute of Management, detailing tasks such as installation of Java and Android Studio, usage of Android SDK, and various programming exercises in Java. It includes a structured index with dates for allotment and submission of each practical, alongside descriptions of key components and examples related to Android development. The document serves as a guide for students to complete their assignments effectively within the specified timeline.

Uploaded by

kikoh33866
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views56 pages

Android Practical File PDF

The document outlines the practical assignments for an Android Programming laboratory course at Rayat Bahra Institute of Management, detailing tasks such as installation of Java and Android Studio, usage of Android SDK, and various programming exercises in Java. It includes a structured index with dates for allotment and submission of each practical, alongside descriptions of key components and examples related to Android development. The document serves as a guide for students to complete their assignments effectively within the specified timeline.

Uploaded by

kikoh33866
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

RAYAT BAHRA INSTITUTE

OF MANAGEMENT

ANDROID PROGRAMMING
LABORATORY

NAME –NAVJOT
ROLL NO – 2114192
BCA 6TH SEM
COURSE CODE –UGCA 1944

1
INDEX

Serial Name of the Practical Date of Date of Remarks


No. allotment Submission
01. Installation of Java, android framework. 12-01-2024 12-01-2024
02. Android SDK Manager and its all components 12-01-2024 19-01-2024
O3. Program Based on overriding, constructor, classes in 19-01-2024 19-01-2024
java
04 Program based on the final, this and static keyword in 19-01-2024 02-02-2024
JAVA.
05 Directory Structure of an android project, common 02-02-2024 09-02-2024
default resources folders the values folder, leveraging
Android XML
06 Application based on Text Boxes and Button 09-02-2024 16-02-2024
07 Application based on check boxes and buttons 16-02-2024 23-02-2024
08 Application based on Radio Buttons 23-02-2024 01-03-2024
09 Application based on Intent and Intent filters 01-03-2024 01-03-2024
10 Application based on Activities and Services 01-03-2024 15-03-2024
11 Application based on Action Bar 15-03-2024 15-03-2024
12 Application based on Option Menu 15-03-2024 22-03-2024
13 Application based on Rating Bar 22-03-2024 22-03-2024
14 Application based on Media Player 22-03-2024 29-03-2024
15 Application based on Content Providers 29-03-2024 29-03-2024
16 Application based on Accessing Camera 29-03-2024 12-04-2024
17 Application based on Accessing Location 12-04-2024 12-04-2024
18 Application based on the Activation Of Sensors 12-04-2024 12-04-2024
19 Application based on Animations 12-04-2024 12-04-2024

2
Practical 1 – Installation of Java, android framework
The public integrated development environment (IDE) for Android apps is Android Studio,
which is supported by Google. Java was replaced by kotlin on May 7, 2019, which became
the preferred language for Android apps. But still, Java is being used to develop Android
apps. Android Studio 3.6.1 has the following features.

• Gradle-based build support.

• Drag and drop objects in the Layout Editor allow you to create UI components.

• Common Android programs and features can be created using template-based wizards.

• Built-in support for Google Cloud Platform enabling integration with Firebase Cloud
Messaging (formerly known as ‘Google Cloud Messaging’) and Google App Engine.

• Lint tools to capture performance, usage, version compatibility, and other information.

system requirements

The following requirements are necessary before downloading and installing Android
Studio.

• Operating System Version - Microsoft Windows 7/8/10 (32-bit or 64-bit).

• Random Access Memory (RAM) - A minimum of 4 GB RAM and 8 GB RAM is


recommended.

• Free disk space - minimum 2 GB and


recommended 4 GB.

• Minimum JDK version - Java Development


Kit (JDK) .

• Minimum screen resolution -


1280*800.resolution

Installing Android Studio

Step 1

To download Android Studio, visit the official


Android Studio website on your browser.

3
Step 2

Click on the "Download Android Studio"


option.

Step 3

Double-click the downloaded "Android


Studio-ide.exe" file

Step 4

The "Android Studio Setup" screen appears


and you can click "Next" to continue.

Step 5

Select the component you want to install and


click the "Next" button.

Step 6

Now, find the location where you want to install Android Studio and click "Next" to proceed.

4
Step 7

Select the start menu folder for the "Android


Studio" shortcut and click the "Install"
button to proceed

Step 8

Click on the "Next" button after successfully


completing the installation

Step 9

Click the "Finish" button to continue.

Then, your Android Studio welcome screen


will appear on screen.

5
Practical 2 –Android SDK Manager and it’s all components.
Android SDK is a group of libraries and Software Development tools which might be vital for
Developing Android Applications. Whenever Google releases a new edition or update of
Android Software, a corresponding SDK also releases with it. In the up to date or new
version of SDK, some greater capabilities are blanketed which are not gift in the previous
model. Android SDK consists of a few gear which are very critical for the improvement of
Android Application. These equipment offer a clean float of the development system from
developing and debugging. Android SDK is like minded with all working systems consisting of
Windows, Linux, macOS, etc.

Components of Android SDK

Android SDK Components play a foremost function within the Development of Android
applications. Below are the essential components:

1. Android SDK Tools

Android SDK device is an essential aspect of Android SDK. It consists of a complete set of
development and debugging equipment. Below are the SDK developer equipment:

• Android SDK Build tool.

• Android Emulator.

• Android SDK Platform-gear.

• Android SDK Tools.

6
2. Android SDK Build-Tools

Android SDK construct equipment are used for constructing actual binaries of Android App.
The primary capabilities of Android SDK Build tools are built, debug, run and take a look at
Android programs. The cutting-edge model of the Android SDK Build device is 30.0.3. While
downloading or updating Android in our System, one ought to ensure that its latest model is
down load in SDK Components.

3. Android Emulator

An Android Emulator is a tool that simulates an Android device in your system. Suppose we
need to run our android software that we code. One alternative is that we will run this on
our Android Mobile with the aid of Enabling USB Debugging on our mobile. Another option
is to use an Android Emulator. In Android Emulator, we are shown a virtual android device
on our system in which we run the Android application we code.

4. Android SDK platform tools

Android SDK Platform-tools are helpful while working on Project and error messages will be
shown at the same time. It is mainly used for testing purposes. This includes:

• Android Debug Bridge (ADB), a command-line tool that helps communicate with the
device. It allows us to perform actions like Installing App and Debugging App.

• Fastboot allows you to flash the device with a new system image.

• Systrace tools help compile and manage systems. Very important for App Debugging.

5. Android SDK tools

7
The Android SDK tool is part of the SDK tool. It has some tools and other utilities which are
important for developing Android application. It has complete Debugging and Development
tools for android.

6. SDK settings

These are numbered according to Android version. The new version of the SDK platform has
more features and is more compatible but the older version is less compatible with fewer
features. As in Android 11.0(R) it is more compatible and has more features but below
versions like Android 10.0(Q), Android4.4(KitKat) have fewer features and not compatible it
is more consistent.

7. SDK update sites

SDK Update Sites have some built-in sites to check Android SDK Updates Tools. In this case,
we need to make sure that we do not uncheck the bottom button because these are
checked by default which will check for updates if we remove it it will not check for updates
for them.

8
Practical 3 –Program Based on overriding, constructor, classes in java
public class Student {
//instance variables of the class
int id;
String name;

Student(){
System.out.println("this a default constructor");
}

Student(int i, String n){


id = i;
name = n;
}

public static void main(String[] args) {


//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

System.out.println("\nParameterized Constructor values: \n");


Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}
OUTPUT

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David

9
Practical 4- Program based on the final, this and static keyword in JAVA.
The final keyword in java is used to restrict the user. The java final key-word may be used in
many context. Final can be:

1. Variable

2. Method

3. Class

The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only.

Example of final variable


class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

OUTPUT

The static keyword in Java is specially used for reminiscence control. The static keyword in
Java is used to percentage the same variable or approach of a given class. The customers
can observe static keywords with variables, techniques, blocks, and nested classes. The
static key-word belongs to the class than an example of the magnificence. The static
keyword is used for a constant variable or a technique that is the equal for every instance of
a class.

Program to demonstrate use of static keyword with methods and variables

class Student {

10
String name;
int rollNo
// static variable
static String cllgName;

// static counter to set unique roll no


static int counter = 0;

public Student(String name)


{
this.name = name;

this.rollNo = setRollNo();
}

// getting unique rollNo


// through static variable(counter)
static int setRollNo()
{
counter++;
return counter;
}

// static method
static void setCllg(String name) { cllgName = name; }

// instance method
void getStudentInfo()
{
System.out.println("name : " + this.name);
System.out.println("rollNo : " + this.rollNo);

// accessing static variable


System.out.println("cllgName : " + cllgName);
}
}
Output
// Driver class
public class StaticDemo { name : Alice
public static void main(String[] args) rollNo : 1
{
cllgName : XYZ
// calling static method
// without instantiating Student class name : Bob
Student.setCllg("XYZ"); rollNo : 2

Student s1 = new Student("Alice"); cllgName : XYZ


Student s2 = new Student("Bob");

11
s1.getStudentInfo();
s2.getStudentInfo() }}
Program 5- Directory Structure of an android project, common default resources folders the
values folder, leveraging Android XML

Directory Structure of an android project

• src - Java source documents related to your project. This includes the Activity
"controller" documents as well as your models and helpers.

• res - Resource files related to your mission. All pics, strings, layouts, and different
resource files are saved within the aid document hierarchy below the res listing.

• res/format - XML layout documents that describe the views and layouts for each pastime
and for partial views inclusive of list objects.

• res/values - XML documents which keep numerous characteristic values. These


encompass strings.Xml, dimens.Xml, styles.Xml, colorations.Xml, themes.Xml, and so on.

• res/drawable - Here we shop the various density-impartial graphic property used in our
software.

• res/drawable-hdpi - Series of folders for density precise photos to use for numerous
resolutions.

• res/mipmap - most generally used for application icons. See this segment for extra
information.

The most frequently edited files are:

• res/layout/activity_foo.Xml - This record describes the format of the activity's UI. This
method the location of each view item on one app display.

• src/.../FooActivity.Java - The Activity "controller" that constructs the pastime


using the view, and handles all event coping with and examine good judgment for one app
display.

• AndroidManifest.Xml - This is the Android software definition file. It consists of statistics


approximately the Android utility along with minimum Android model, permission to access
Android tool abilties which includes internet get admission to permission, ability to use
phone permission, and so on.

Other less edited folders include:

• gen - Generated Java code files, this library is for Android internal use only.

• assets - Uncompiled supply documents related to your project; Rarely used.

• bin - Resulting utility bundle documents associated with your assignment as soon as it’s
been built.

12
• libs - Before the advent of Gradle construct system, this listing become used for any
secondary libraries (jars) you may want to link to your app.

Common default resources folders the values folder

The res/values folder is used to keep the values for the resources which can be used in
many Android tasks to consist of functions of coloration, patterns, dimensions etc.
Colorings.Xml: The colorings.Xml is an XML report that's used to keep the colors for the
sources. An Android project contains three essential colorings namely:

• colorPrimary

• colorPrimaryDark

• colorAccent

The implementation of colors.xml resource:

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


<resources>
<color name="colorPrimary">#1294c8</color>
<color name="colorPrimaryDark">#1294c8</color>
<color name="colorAccent">#FF4081</color>
<color name="text_color">#555555</color>
<color name="colorText">#FFFFFF</color>
<color name="colorTextHint">#51d8c7</color>
</resources>

dimens.xml: The dimens.xml is used for defining the dimensions for different widgets to
be included in the Android project. It is a good coding practice to use dimens.xml to define
a dimension rather than just writing the dimension in the resource, due to the fact that if
ever any need arises to change the dimension, instead of making a change to all, only the
dimens.xml can be changed once and the change is reflected in all.
The implementation of dimens.xml resource:
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="nav_header_vertical_spacing">8dp</dimen>
<dimen name="nav_header_height">176dp</dimen>
<dimen name="fab_margin">16dp</dimen>
</resources>

13
strings.xml: One of the most important as well as widely used values file is the strings.xml
due to its applicability in the Android project. Basic function of the strings.xml is to define
the strings in one file so that it is easy to use same string in different positions in the
android project plus it makes the project looks less messy.
The implementation of strings.xml resource:
<resources>
<string name="app_name">Workshop app</string>

<string name="navigation_drawer_open">Open navigation


drawer</string>
<string name="navigation_drawer_close">Close navigation
drawer</string>
<string name="action_settings">Settings</string>
<string name="hello_blank_fragment">Hello blank fragment</string>
<string name="date">Date:</string>
<string name="timings">Timings:</string>
</resources>

styles.xml: Another important file in the values folder is the styles.xml where all the
themes of the Android project are defined. The base theme is given by default having the
option to customize or make changes to the customized theme as well. Every theme has a
parent attribute which defines the base of the theme. There are a lot of options to choose
from depending on the need of the Android project.
The implementation of styles.xml resource:
<resources>

<!-- Base application theme. -->


<style name="AppTheme"
parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item
name="colorPrimary">@color/colorPrimary</item>
<item
name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item
name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

14
</style>
<style name="AppTheme.AppBarOverlay"
parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay"
parent="ThemeOverlay.AppCompat.Light" />
</resources>

15
PRACTICAL :6
Certainly! Below is a simple example of an Android application that
includes text boxes and a button. The application allows users to
enter text into the text boxes and performs an action when the
button is clicked. In this example, we'll create an app that
concatenates the text entered into two text boxes and displays the
result in a Toast message.
activity_main.xml (layout file):

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


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

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text 1"
android:layout_marginBottom="16dp"/>

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

16
android:layout_height="wrap_content"
android:hint="Enter text 2"
android:layout_below="@id/editText1"

android:layout_marginBottom="16dp"/>

<Button

android:id="@+id/concatenateButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Concatenate"
android:layout_below="@id/editText2"
android:onClick="concatenateText"/>

</RelativeLayout>

MainActivity.java:
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

EditText editText1, editText2;

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

editText1 = findViewById(R.id.editText1);
editText2 = findViewById(R.id.editText2);
}

public void concatenateText(View view) {


String text1 = editText1.getText().toString();
String text2 = editText2.getText().toString();

String concatenatedText = text1 + " " + text2;

17
// Display the concatenated text in a Toast message
Toast.makeText(this, "Concatenated Text: " + concatenatedText,
Toast.LENGTH_SHORT).show();
}
}

In this example:
 We define two EditText views for users to enter text.
 There is a Button that triggers the concatenation process.
 The concatenateText method is specified as the onClick attribute for the Button
in the XML layout file. This method is called when the button is clicked.
 In the concatenateText method, we retrieve the text from the EditText views,
concatenate them, and display the result using a Toast message.

Remember to add necessary permissions in the AndroidManifest.xml file and


handle any runtime permissions if required, depending on the Android version
you are targeting.

18
PRACTICAL :7
Below is an example of an Android application that includes
checkboxes and buttons. The application allows users to select
multiple checkboxes and perform an action when a button is
clicked. In this example, we'll create an app that displays a Toast
message with the selected checkboxes when the button is clicked.
activity_main.xml (layout file):

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


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

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

<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"
android:layout_below="@id/checkBox1"
android:layout_marginBottom="16dp"/>

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

<Button
android:id="@+id/showSelectionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selection"
android:layout_below="@id/checkBox3"
android:onClick="showSelection"/>

19
</RelativeLayout>

MainActivity.java:

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

CheckBox checkBox1, checkBox2, checkBox3;

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

checkBox1 = findViewById(R.id.checkBox1);
checkBox2 = findViewById(R.id.checkBox2);
checkBox3 = findViewById(R.id.checkBox3);
}

public void showSelection(View view) {


StringBuilder selectedOptions = new StringBuilder();

if (checkBox1.isChecked()) {
selectedOptions.append("Option 1\n");
}
if (checkBox2.isChecked()) {
selectedOptions.append("Option 2\n");
}
if (checkBox3.isChecked()) {
selectedOptions.append("Option 3\n");
}

// Display the selected options in a Toast message


if (selectedOptions.length() > 0) {
Toast.makeText(this, "Selected Options:\n" + selectedOptions.toString(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No options selected!", Toast.LENGTH_SHORT).show();
}
}

20
}

In this example:

 We define three CheckBox views for users to select options.


 There is a Button that triggers the action to display selected options.
 The showSelection method is specified as the onClick attribute for the Button in
the XML layout file. This method is called when the button is clicked.
 In the showSelection method, we check the status of each checkbox and build a
string containing the selected options. Finally, we display this string in a Toast
message.

Remember to add necessary permissions in the AndroidManifest.xml file and


handle any runtime permissions if required, depending on the Android version
you are targeting.

21
PRACTICAL:8
Below is an example of an Android application that includes radio
buttons. The application allows users to select one option from a set
of radio buttons and perform an action when a button is clicked. In
this example, we'll create an app that displays a Toast message with
the selected radio button option when a button is clicked.

activity_main.xml (layout file):

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


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

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

<RadioButton
android:id="@+id/radioButtonOption1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />

<RadioButton
android:id="@+id/radioButtonOption2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"
android:layout_below="@id/radioButtonOption1"
android:layout_marginTop="16dp"/>

<RadioButton
android:id="@+id/radioButtonOption3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3"
android:layout_below="@id/radioButtonOption2"
android:layout_marginTop="16dp"/>

</RadioGroup>

22
<Button
android:id="@+id/showSelectionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selection"
android:layout_below="@id/radioGroup"
android:onClick="showSelection"/>

</RelativeLayout>

MainActivity.java:

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

RadioGroup radioGroup;

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

radioGroup = findViewById(R.id.radioGroup);
}

public void showSelection(View view) {


int selectedRadioButtonId = radioGroup.getCheckedRadioButtonId();

if (selectedRadioButtonId != -1) {
RadioButton selectedRadioButton = findViewById(selectedRadioButtonId);
String selectedOption = selectedRadioButton.getText().toString();
Toast.makeText(this, "Selected Option: " + selectedOption,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "No option selected!", Toast.LENGTH_SHORT).show();
}
}
}

23
In this example:

 We define a RadioGroup containing three RadioButtons for users to select options.


 There is a Button that triggers the action to display the selected option.
 The showSelection method is specified as the onClick attribute for the Button in
the XML layout file. This method is called when the button is clicked.

24
PRACTICAL :9
Certainly! An application using Intent and Intent Filters in Android can
demonstrate how different components within an app can communicate
with each other and how external components can interact with your app.
Intent is a messaging object that can be used to request an action from
another app component. Intent Filters are expressions in your app's manifest
file that specify the type of intents your component can receive.

Here's a simple example:

Suppose you have two activities, MainActivity and SecondActivity, and you want
to navigate from MainActivity to SecondActivity using an Intent.

1. MainActivity.java:

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

Button btnNavigate;

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

btnNavigate = findViewById(R.id.btnNavigate);

btnNavigate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Creating an intent to navigate from MainActivity to SecondActivity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
}
SecondActivity.java:

25
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intentexample">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="com.example.intentexample.SECOND_ACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>

</manifest>

In this example:

 MainActivity contains a button (btnNavigate) that, when clicked, creates an Intent to


navigate to SecondActivity.
 The Intent specifies the class of the target component (SecondActivity) using its class
object.

26
 SecondActivity is declared in the AndroidManifest.xml file with an <intent-filter> that
specifies an action string com.example.intentexample.SECOND_ACTIVITY.
 When the button is clicked, it launches SecondActivity by starting an instance of the Intent
associated with SecondActivity.
 The AndroidManifest.xml file defines both activities (MainActivity and SecondActivity) and
their intent filters.
 The intent filter for MainActivity specifies the MAIN action and the LAUNCHER category,
indicating that it is the main entry point of the application.
 The intent filter for SecondActivity specifies a custom action string
com.example.intentexample.SECOND_ACTIVITY.

27
PRACTICAL :10
Below is a basic example of an Android application that uses both
activities and services.

Suppose we have an app with two activities: MainActivity and


MyService, where MainActivity starts and stops a background service
(MyService). The service simply runs in the background and displays
a notification.

1. MainActivity.java:

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private Button startServiceButton;


private Button stopServiceButton;

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

startServiceButton = findViewById(R.id.start_service_button);
stopServiceButton = findViewById(R.id.stop_service_button);

startServiceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, MyService.class));
}
});

stopServiceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(MainActivity.this, MyService.class));

28
}
});
}
}

MyService.java:

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.core.app.NotificationCompat;

public class MyService extends Service {

private static final String CHANNEL_ID = "MyServiceChannel";

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();

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


CHANNEL_ID)
.setContentTitle("My Service")
.setContentText("Running in the background")
.setSmallIcon(R.drawable.ic_launcher_foreground);

startForeground(1, builder.build());

return START_STICKY;
}

private void createNotificationChannel() {


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "My Service Channel";
String description = "Channel for My Service";
int importance = NotificationManager.IMPORTANCE_DEFAULT;

29
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);

NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.activitiesandservices">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
<service android:name=".MyService" />
</application>

</manifest>

30
In this example:

 MainActivity contains two buttons, one to start the service and the other to stop it.
 MyService extends the Service class and overrides onStartCommand() to create a
notification and start the service in the foreground.
 We create a notification channel (required for Android Oreo and higher) to display
notifications from the service.
 The service is declared in the AndroidManifest.xml file.
 When the "Start Service" button is clicked in MainActivity, it starts MyService using an
intent. Similarly, clicking the "Stop Service" button stops the service.

This example demonstrates how activities and services can work together in an Android
application.

31
PRACTICAL :11
Certainly! Here's a simple example of an Android application that utilizes the
Action Bar. The Action Bar typically appears at the top of an activity's
window and can display various options and actions for the user to interact
with.

In this example, we'll create an app with a single activity (MainActivity) that
includes an Action Bar with a title and a menu item.

1. MainActivity.java:

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

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

// Handle action bar item clicks here.


@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();

// Handle the menu item click.


if (id == R.id.action_settings) {
Toast.makeText(this, "Settings clicked", Toast.LENGTH_SHORT).show();
return true;
}

32
return super.onOptionsItemSelected(item);
}
}

res/menu/main_menu.xml (menu resource file):

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


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

<!-- Add menu items here -->


<item
android:id="@+id/action_settings"
android:title="Settings"
app:showAsAction="never" />

</menu>

res/layout/activity_main.xml (layout file)


<?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=".MainActivity">

<!-- Add your main content here -->

</RelativeLayout>
AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.actionbar">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

33
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

In this example:

 We override onCreateOptionsMenu() to inflate the menu resource


(main_menu.xml) and add menu items to the Action Bar.
 We override onOptionsItemSelected() to handle clicks on the menu items. In
this case, when the "Settings" menu item is clicked, a Toast message is displayed.
 The menu resource file (main_menu.xml) defines the menu items to be displayed in
the Action Bar. In this case, it contains a single menu item "Settings".
 The layout file (activity_main.xml) is currently empty and can be customized to
include your app's main content.

This example demonstrates the basics of setting up an Action Bar with menu
items in an Android application. You can further customize the Action Bar and
menu items based on your app's requirements.

34
PRACTICAL :12
Certainly! An options menu in an Android application typically appears when
the user presses the menu button on the device or when the user selects the
overflow menu icon in the Action Bar. Here's a simple example of an Android
application that utilizes an options menu:
MainActivity.java

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

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

// Handle options menu item clicks here.


@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();

// Handle the menu item click.


switch (id) {
case R.id.action_settings:
Toast.makeText(this, "Settings clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_about:
Toast.makeText(this, "About clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_exit:
finish(); // Close the activity
return true;

35
default:
return super.onOptionsItemSelected(item);
}
}
}

res/menu/main_menu.xml (menu resource file)

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_settings"
android:title="Settings"
android:orderInCategory="100"
android:showAsAction="never" />

<item
android:id="@+id/action_about"
android:title="About"
android:orderInCategory="100"
android:showAsAction="never" />

<item
android:id="@+id/action_exit"
android:title="Exit"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>

res/layout/activity_main.xml (layout file):

<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=".MainActivity">

<!-- Add your main content here -->

</RelativeLayout>

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.optionmenu">

<application
android:allowBackup="true"

36
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


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

37
PRACTICAL :13
Certainly! Below is an example of an Android application that utilizes a
Rating Bar. In this example, we'll create an app where users can rate
something by selecting a rating value using the Rating Bar, and then we'll
display the selected rating value in a toast message.
MainActivity.java:

import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

RatingBar ratingBar = findViewById(R.id.ratingBar);

// Set a listener to respond to rating changes


ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
// Display a toast message with the selected rating
Toast.makeText(MainActivity.this, "Rating: " + rating,
Toast.LENGTH_SHORT).show();
}
});
}
}

res/layout/activity_main.xml (layout file):

<?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=".MainActivity">

<RatingBar
android:id="@+id/ratingBar"

38
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:numStars="5"
android:rating="0"
android:stepSize="1" />

</RelativeLayout>

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ratingbar">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


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

39
In this example:
 We have a single activity (MainActivity) with a Rating Bar (RatingBar) defined in
the layout file.
 We set an OnRatingBarChangeListener to listen for changes to the rating value.
When the rating is changed by the user, a toast message displays the selected rating
value.
 The layout file (activity_main.xml) contains only a Rating Bar.
 The AndroidManifest.xml file defines the application's main activity.

This example demonstrates the basic usage of a Rating Bar in an Android application. You
can further customize the Rating Bar's appearance and behavior based on your app's
requirements.

40
PRACTICAL 14
Creating an Android application based on a media player involves allowing
users to play audio or video files, control playback (play, pause, stop, seek),
and display information about the media being played. Below is a basic
example of an Android application that uses the MediaPlayer class to play
audio from a local resource.
MainActivity.java:

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private MediaPlayer mediaPlayer;


private Button playButton;
private Button pauseButton;
private Button stopButton;

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

mediaPlayer = MediaPlayer.create(this, R.raw.sample_audio);

playButton = findViewById(R.id.play_button);
pauseButton = findViewById(R.id.pause_button);
stopButton = findViewById(R.id.stop_button);

playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.start();
}
});

pauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.pause();

41
}
});

stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.sample_audio);
}
});
}

@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}

res/layout/activity_main.xml (layout file):

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


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

<Button
android:id="@+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play" />

<Button
android:id="@+id/pause_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause" />

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

42
android:text="Stop" />

</LinearLayout>

res/raw/sample_audio.mp3: Put your audio file (sample_audio.mp3) in the 'raw'


folder under the 'res' directory. You can add the audio file by right-clicking on the
'res' folder -> New -> Android Resource Directory -> select 'raw' from the Resource
type dropdown -> OK. Then, copy your audio file into the 'raw' folder.
AndroidManifest.xml: Make sure you have the necessary permissions, such as
INTERNET or READ_EXTERNAL_STORAGE if you're playing media from external
sources. In this case, since we're using a local resource, no additional permissions are
required.

In this example:

 We create a MediaPlayer object and load an audio file from the raw resource folder.
 Three buttons (playButton, pauseButton, stopButton) are defined in the layout
file (activity_main.xml). The play button starts playback, the pause button pauses
playback, and the stop button stops playback and resets the MediaPlayer to its initial
state.
 We set onClickListeners for each button to control the MediaPlayer accordingly.
 When the activity is destroyed, we release the MediaPlayer resources to free up
memory

PRACTICAL 15

43
Creating an Android application based on Content Providers involves
interacting with system-provided or custom content providers to access and
manipulate data stored in other applications or the system itself. Below is a
basic example demonstrating how to use a content provider to access and
display contacts stored on the device.
MainActivity.java:

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private TextView contactsTextView;

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

contactsTextView = findViewById(R.id.contactsTextView);

// Define the URI for accessing contacts


Uri contactsUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

// Define the columns to retrieve


String[] projection = {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};

// Query the contacts content provider


Cursor cursor = getContentResolver().query(
contactsUri,
projection,
null,
null,
null
);

// Display the retrieved contacts


if (cursor != null && cursor.getCount() > 0) {

44
StringBuilder stringBuilder = new StringBuilder();
while (cursor.moveToNext()) {
String name =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPL
AY_NAME));
String number =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMB
ER));
stringBuilder.append("Name: ").append(name).append("\n").append("Number:
").append(number).append("\n\n");
}
contactsTextView.setText(stringBuilder.toString());
cursor.close();
} else {
contactsTextView.setText("No contacts found.");
}
}
}

res/layout/activity_main.xml (layout file):

<?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=".MainActivity">

<TextView
android:id="@+id/contactsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contacts:"
android:textSize="18sp" />

</LinearLayout>

AndroidManifest.xml: Make sure you have the necessary permissions to access contacts
data. Add the following permission:
<uses-permission android:name="android.permission.READ_CONTACTS" />

In this example:

45
 We define a MainActivity that queries the system's contacts content provider to
retrieve contact names and numbers.
 We use the ContactsContract API to interact with the contacts content provider.
 The retrieved contacts are displayed in a TextView in the activity's layout.
 The application needs the READ_CONTACTS permission to access the device's
contacts data.

This is a basic example of how you can use a content provider to access data from other
applications or the system in your Android application. Depending on your requirements,
you can explore different content providers available in the Android framework or create
your own custom content provider to manage and share data across applications.

46
PRACTICAL 16
Creating an Android application to access the device's camera involves
utilizing the Camera API or the CameraX API to capture photos or videos.
Below is a basic example of an Android application that allows users to
access the camera and capture a photo.
MainActivity.java:

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.ImageView;

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

public class MainActivity extends AppCompatActivity {

private static final int REQUEST_IMAGE_CAPTURE = 1;


private ImageView imageView;

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

imageView = findViewById(R.id.imageView);

// Launch camera when the ImageView is clicked


imageView.setOnClickListener(v -> dispatchTakePictureIntent());
}

private void dispatchTakePictureIntent() {


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

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");

47
imageView.setImageBitmap(imageBitmap);
}
}
}

res/layout/activity_main.xml (layout file):

<?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=".MainActivity">

<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/ic_launcher_background" />

</RelativeLayout>

AndroidManifest.xml: Ensure that your application has the necessary permissions to access
the camera. Add the following permission:
<uses-permission android:name="android.permission.CAMERA" />

48
In this example:

 We define a MainActivity that launches the camera when the ImageView is clicked.
 We use the MediaStore.ACTION_IMAGE_CAPTURE intent action to launch the camera
application.
 After capturing a photo, the image data is returned to the onActivityResult method,
where we display the captured photo in the ImageView.

This is a basic example of how you can access the device's camera and capture photos in
your Android application. Depending on your requirements, you can explore more
advanced features such as capturing videos, using camera features like flash and
autofocus, or implementing camera functionality using CameraX API for better
compatibility across different devices.

49
PRACTICAL 17

To develop a mobile application that utilizes location services to provide users with
nearby points of interest, such as restaurants, cafes, and attractions.

Tools and Technologies:


 Development Platform: Android (using Android Studio)
 Programming Language: Kotlin
 Google Maps API for Android

Steps:
1. Project Setup:
 Create a new Android project in Android Studio.
 Set up the project structure with appropriate folders for activities, layouts, and
resources.
2. Configure Google Maps API:
 Obtain an API key from the Google Cloud Console.
 Configure the Google Maps SDK for Android in your project by adding the API
key to the AndroidManifest.xml file.
3. Design User Interface:
 Design the user interface for the application using XML layout files.
 Include elements such as a map view, search bar, and list view for displaying
nearby places.
4. Request Location Permissions:
 Implement runtime permissions to request access to the device's location.
 Handle permission requests and responses in the activity.
5. Implement Location Services:
 Use the Fused Location Provider API to retrieve the device's current location.
 Set up a location request and request location updates.
 Handle location updates and display the user's current location on the map.
6. Integrate Google Places API:
 Enable the Google Places API for Android in the Google Cloud Console.
 Use the Nearby Search API to retrieve nearby places based on the user's
location.
 Parse the JSON response to extract relevant place information such as name,
address, and ratings.
7. Display Nearby Places:
 Populate the list view with nearby places retrieved from the Google Places API.
 Implement click listeners to show additional details about a selected place.
8. Enhance User Experience:

50
 Implement features such as place markers on the map and custom info
windows to display place details.
 Add animations and transitions to improve the user interface.
9. Testing and Debugging:
 Test the application on various Android devices and screen sizes.
 Use the Android Emulator to simulate different locations and test location-
based features.
 Debug any issues related to location permissions, network connectivity, or API
integration.
10. Privacy and Security:
 Ensure that user location data is handled securely and in compliance with
privacy regulations.
 Encrypt sensitive data and use secure connections when communicating with
external APIs.
11. User Feedback and Iteration:
 Gather feedback from users through beta testing or user surveys.
 Incorporate user feedback to improve the application's functionality and user
experience.
 Release updates with new features and bug fixes based on user input.
12. Documentation:
 Document the project setup, implementation details, and any challenges
encountered during development.
 Provide clear instructions for setting up the project and running the
application.

51
PRACTICAL 18
Objective:
To develop a mobile application that activates and utilizes various sensors
available on the device, such as accelerometer, gyroscope, and proximity
sensor.

Tools and Technologies:


 Development Platform: Android (using Android Studio)
 Programming Language: Kotlin

Steps:
1. Project Setup:
 Create a new Android project in Android Studio.
 Set up the project structure with appropriate folders for activities,
layouts, and resources.
2. Design User Interface:
 Design a simple user interface that displays sensor data in real-time.
 Include TextViews or graphical elements to visualize sensor readings.
3. Activate Sensors:
 Access the system's sensor services and initialize the required sensors
(e.g., accelerometer, gyroscope, proximity sensor) in the activity.
4. Register Sensor Listeners:
 Register sensor listeners to receive updates when sensor data changes.
 Implement sensor event listeners to handle sensor data changes and
update the UI accordingly.
5. Read Sensor Data:
 Retrieve sensor data from sensor events and display it in the user
interface.
 Convert sensor data into meaningful information (e.g., display
accelerometer readings as device orientation or movement).
6. Handle Sensor Events:
 Implement logic to process sensor events and perform actions based on
sensor data.
 For example, trigger an action when the device is tilted or when an
object is detected by the proximity sensor.
7. Enhance User Experience:
 Add visual feedback to indicate sensor activity or changes in sensor data.
 Implement animations or sound effects to enhance the user experience.

52
8. Testing and Debugging:
 Test the application on various Android devices with different sensor
capabilities.
 Use the Android Emulator to simulate sensor data and test sensor-based
features.
 Debug any issues related to sensor initialization, data processing, or UI
updates.
9. Privacy and Security:
 Ensure that sensor data is handled securely and in compliance with
privacy regulations.
 Minimize the collection and storage of sensitive sensor data unless
necessary for application functionality.
10. User Feedback and Iteration:
 Gather feedback from users through beta testing or user surveys.
 Incorporate user feedback to improve the application's functionality and
user experience.
 Release updates with new features and bug fixes based on user input.
11. Documentation:
 Document the project setup, implementation details, and any challenges
encountered during development.
 Provide clear instructions for setting up the project and running the
application.

Conclusion:

Developing a sensor activation application allows you to explore the


capabilities of different sensors available on Android devices and create
innovative features based on sensor data. By following the steps outlined in
this practical guide, you can build a functional and engaging application that
showcases the power of sensor technology.

53
PRACTICAL :19
Objective:

To design and implement a mobile application that utilizes animations to


enhance user experience and interaction.

Tools and Technologies:

 Development Platform: Android (using Android Studio)


 Programming Language: Kotlin
 Android Animation Framework

Steps:

1. Project Setup:
 Create a new Android project in Android Studio.
 Set up the project structure with appropriate folders for activities,
layouts, and resources.
2. Design User Interface:
 Design the user interface for the application using XML layout files.
 Plan the layout and placement of elements considering animation
effects.
3. Basic Animations:
 Implement basic animations such as fade in, fade out, scale, rotate,
and translate.
 Apply animations to UI elements like buttons, text views, and images
to create visual effects.
4. Animation Types:
 Explore different types of animations supported by the Android
Animation Framework, including tween animations, property
animations, and drawable animations.
 Experiment with animation interpolators to customize the
acceleration and deceleration of animations.
5. Activity Transitions:
 Implement activity transitions using shared element transitions, slide
animations, and custom transitions.
 Create smooth transitions between activities to provide a seamless
user experience.

54
6. Gesture-Based Animations:
 Integrate gesture-based animations such as swipe gestures, pinch-to-
zoom, and drag-and-drop animations.
 Implement touch event listeners to detect user interactions and
trigger animations accordingly.
7. Animation Sequences:
 Combine multiple animations to create complex animation sequences
and choreographed effects.
 Use animation listeners to execute code before or after the start or
end of an animation sequence.
8. Interactive Animations:
 Develop interactive animations that respond to user input and
gestures.
 Implement animations that change based on user actions, such as
button clicks or screen taps.
9. Animation Performance:
 Optimize animation performance by minimizing the use of complex
animations and avoiding excessive rendering.
 Profile the application using Android Profiler to identify performance
bottlenecks and optimize animation rendering.
10. Testing and Debugging:
 Test the application on various Android devices and screen sizes.
 Use the Android Emulator to simulate different device configurations
and performance scenarios.
 Debug any issues related to animation timing, layout conflicts, or
resource usage.
11. Privacy and Security:
 Ensure that user data and interactions are handled securely and in
compliance with privacy regulations.
 Minimize the collection and storage of sensitive user information to
protect user privacy.
12. User Feedback and Iteration:
 Gather feedback from users through beta testing, user reviews, and
analytics.
 Incorporate user feedback to improve animation effects,
performance, and usability.
 Release updates with new features and bug fixes based on user input.
13. Documentation:

55
 Document the project setup, implementation details, and any
challenges encountered during development.
 Provide clear instructions for setting up the project, running the
application, and customizing animations.

Conclusion:
Developing an application based on animations allows you to create visually
engaging and interactive user interfaces that enhance the overall user
experience. By following the steps outlined in this practical guide, you can
leverage the power of animation to create compelling and dynamic
applications for Android devices.

56

You might also like