Android Practical File PDF
Android Practical File PDF
OF MANAGEMENT
ANDROID PROGRAMMING
LABORATORY
NAME –NAVJOT
ROLL NO – 2114192
BCA 6TH SEM
COURSE CODE –UGCA 1944
1
INDEX
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.
• 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.
Step 1
3
Step 2
Step 3
Step 4
Step 5
Step 6
Now, find the location where you want to install Android Studio and click "Next" to proceed.
4
Step 7
Step 8
Step 9
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.
Android SDK Components play a foremost function within the Development of Android
applications. Below are the essential components:
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 Emulator.
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.
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.
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.
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 Id : 0
Student Name : null
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.
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.
class Student {
10
String name;
int rollNo
// static variable
static String cllgName;
this.rollNo = setRollNo();
}
// 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);
11
s1.getStudentInfo();
s2.getStudentInfo() }}
Program 5- Directory Structure of an android project, common default resources folders the
values folder, leveraging Android XML
• 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/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.
• 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.
• gen - Generated Java code files, this library is for Android internal use only.
• 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.
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
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>
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>
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):
<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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = findViewById(R.id.editText1);
editText2 = findViewById(R.id.editText2);
}
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.
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):
<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;
@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);
}
if (checkBox1.isChecked()) {
selectedOptions.append("Option 1\n");
}
if (checkBox2.isChecked()) {
selectedOptions.append("Option 2\n");
}
if (checkBox3.isChecked()) {
selectedOptions.append("Option 3\n");
}
20
}
In this example:
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.
<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;
RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
}
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:
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.
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;
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;
@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" />
</manifest>
In this example:
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.
1. MainActivity.java:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
@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;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
startForeground(1, builder.build());
return START_STICKY;
}
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" />
</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;
@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;
}
32
return super.onOptionsItemSelected(item);
}
}
</menu>
</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:
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;
@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;
}
35
default:
return super.onOptionsItemSelected(item);
}
}
}
<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>
<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">
</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" />
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
<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" />
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
}
}
}
<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>
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsTextView = findViewById(R.id.contactsTextView);
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.");
}
}
}
<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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
@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);
}
}
}
<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.
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.
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:
53
PRACTICAL :19
Objective:
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