AP Narender Singh Lab

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 64

UGCA(1944)

ANDROID PROGRAMMING

SUBMMITTED TO:- SUBMMITTED BY:-


JASPREET MAM NARENDER SINGH
ROLL NO.:- 2011237
COURSE:- BCA
SEMESTER:-6th

2
Index
S.No Description
Installation of Java, android Framework
1.

Android SDK Manager and its all components


2.

Programs based on the overriding, constructor, classes in Java


3.

Programs based on the Final, this and static keyword in Java


4.

Directory Structure of an Android Project, Common Default Resources


5. Folders, The Values Folder, Leveraging Android XML.

Applications based on Text Boxes and Button


6.

Applications based on Check Boxes and button


7.

Applications based on Radio Buttons


8.

Applications based on Intents and Intent Filters


9.

Applications based on Activities and services


10.

Applications based on Action Bar


11.

Applications based on Option Menu


12.

Applications based on Rating Bar


13.

Applications based on Media Player


14.

Applications based on Content Providers


15.

Applications based on accessing camera


16.

Applications based on accessing location


17.

2
Applications based on the activation of sensors
18.

Applications based on Animations


19.

2
PRACTICAL 1:-

Installation of java, android framework


Android Studio is the official IDE (Integrated Development Environment) for Android app
development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many
excellent features that enhance productivity when building Android apps, such as:

 A blended environment where one can develop for all Android devices
 Apply Changes to push code and resource changes to the running app without restarting the
app
 A flexible Gradle-based build system
 A fast and feature-rich emulator
 GitHub and Code template integration to assist you to develop common app features and
import sample code
 Extensive testing tools and frameworks
 C++ and NDK support
 Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud
Messaging and App Engine, and many more.
 Provides GUI tools that simplify the less interesting parts of app development. 
 Easy integration with real time database ‘firebase’.
System Requirements

 Microsoft Windows 7/8/10 (32-bit or 64-bit)


 4 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator) 
 2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for
Android SDK and emulator system image)
 1280 x 800 minimum screen resolution
Installation Guide
Step 1: Head over to this link to get the Android Studio executable or zip file. 
Step 2: Click on the Download Android Studio Button. 

2
Click on the “I have read and agree with the above terms and conditions” checkbox followed by
the download button. 

Click on the Save file button in the appeared prompt box and the file will start downloading. 
Step 3: After the downloading has finished, open the file from downloads and run it. It will
prompt the following dialog box. 

Click on next. In the next prompt, it’ll ask for a path for installation. Choose a path and hit next. 
Step 4: It will start the installation, and once it is completed, it will be like the image shown
below. 

2
Click on next.

Step 5: Once “Finish” is clicked, it will ask whether the previous settings need to be imported [if
the android studio had been installed earlier], or not. It is better to choose the ‘Don’t import
Settings option’.  

Click the OK button. 
Step 6: This will start the Android Studio. 

2
Meanwhile, it will be finding the available SDK components.

Step 7: After it has found the SDK components, it will redirect to the Welcome dialog box. 

Click on Next. 

Choose Standard and click on Next. Now choose the theme, whether the Light theme or
the Dark one. The light one is called the IntelliJ theme whereas the dark theme is
called Dracula. Choose as required. 

2
Click on the Next button. 
Step 8: Now it is time to download the SDK components. 

Click on Finish. Components begin to download let it complete.

The Android Studio has been successfully configured. Now it’s time to launch and build
apps. Click on the Finish button to launch it. 
Step 9: Click on Start a new Android Studio project to build a new app. 

2
To run your first android app in Android Studio you may refer to Running your first Android
app.

2
PRACTICAL 2:-

Android SDK manager and it’s all components


Android SDK is a collection of libraries and Software Development tools that are essential for
Developing Android Applications. Whenever Google releases a new version or update of Android
Software, a corresponding SDK also releases with it. In the updated or new version of SDK, some
more features are included which are not present in the previous version. Android SDK consists of
some tools which are very essential for the development of Android Application. These tools
provide a smooth flow of the development process from developing and debugging. Android SDK
is compatible with all operating systems such as Windows, Linux, macOS, etc.

Components of Android SDK


Android SDK Components play a  major role in the Development of Android applications.
Below are the important components:
1. Android SDK Tools
Android SDK tool is an important component of Android SDK. It consists of a complete set of
development and debugging tools. Below are the SDK developer tools:
Android SDK Build tool.
Android Emulator.
Android SDK Platform-tools.
Android SDK Tools.
These are shown below :

2
2. Android SDK Build-Tools
Android SDK build tools are used for building actual binaries of Android App. The main
functions of Android SDK Build tools are built, debug, run and test Android applications. The
latest version of the Android SDK Build tool is  30.0.3. While downloading or updating  Android
in our System, one must ensure that its latest version is download in SDK Components.
3. Android Emulator
An Android Emulator is a device that simulates an Android device on your system. In Android
Emulator the virtual android device is shown on our system on which we run the Android
application that we code. 

In Android Virtual Emulator all  functions that are feasible on real Android mobile is works on
virtual Device like:

 phone calls, text messages.


 stimulate different network speeds.
 specify the location of a device
 access on google play store and lot’s more.

2
But there is one disadvantage of this emulator is that. It is very slow when System’s PC has less
RAM. It works fine when a maximum GB of RAM is present on our device.
4. Android SDK Platform-tools
Android SDK Platform-tools is helpful when we are working on Project and they will show the
error messages at the same time. It is specifically used for testing. It includes:
Android Debug Bridge (ADB), is a command-line tool that helps to communicate with the
device. It allows us to perform an action such as Installing App and Debugging App etc.
Fastboot allows you to flash a device with a new system image.
Systrace tools help to collect and inspect timing information. It is very crucial for App
Debugging.
5. Android SDK Tools
Android SDK tool is a component of SDK tool. It consists of a set of tools which and other
Utilities which are crucial for the development of Android Application. It contains the complete
set of Debugging and Development tools for android.
6. SDK Platforms
For Each Android Software, one SDK platform is available as shown below:

Like in this Android 11.0(R) is installed.


These are numbered according to the android version. The new version of the SDK platform has
more features and more compatible but the old version is less compatible with fewer features. Like
in Android 11.0(R) have more compatible and have more feature but the below versions like
Android 10.0(Q), Android4.4(KitKat) have less feature and is less compatible.
7. SDK Update Sites
In SDK Update Sites, some sites are embedded in it which will check for Android SDK Updates
Tools. In this, one must ensure we don’t unclick the button below because these are checked by
default which will check for updates if we will unclick it then it doesn’t check updates for those. 

2
2
PRACTICAL 3:-

Programs based on overriding, constructor, classes in


java

Overriding :-
Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or
parent classes. When a method in a subclass has the same name, same parameters or
signature, and same return type(or sub-type) as a method in its super-class, then the
method in the subclass is said to override the method in the super-class.

Constructor :-
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling the constructor, memory for the
object is allocated in the memory. It is a special type of method which is used to
initialize the object. Every time an object is created using the new() keyword, at least
one constructor is called.

2
2
PRACTICAL 4:-

Programs based on the Final, this and static keyword in


java.

final keyword
Final keyword defines itself that once final keyword is used then one cannot extend or
change its value. In java the final keyword is used in different methods to define any
variable that can be only assigned one time in program.
Use of final keyword
The final keyword has mainly three uses one of them is to create final class. Second
one is to use final methods and third one is to use final data member.
Following are uses final keyword:
1. Stop Inheritance.
2. Stop Method overriding.
3. Stop value change.
class Test {
    final static int x;
    static
    {
        x = 10;
    }
    public static void main(String[] args)
    {
        System.out.println(x);}
}

Static keyword

2
static keyword is used java for memory management. Static variables are usually
stored in static memory. Static variables are rarely used other than being declared as
constants.
We can use static keyword with methods, variable, blocks and nested class. The static
keyword belongs to the class than instance of the class.
static can be:
a. Method
b. Variable
c. Block
d. Nested class

class Test
{
    // static method
    static void m1()
    {
        System.out.println("from m1");
    }
 
    public static void main(String[] args)
    {
          // calling m1 without creating
          // any object of class Test
           m1();
    }
}

2
PRACTICAL 5:-

Directory structure of an android project, common


default resources folders, the values of folders,
leveraging android XML
After completing the setup of Android Architecture we can create an android
application in the studio. We need to create a new project for each sample application
and we should understand the folder structure. It looks like this:

The android project contains different types of app modules, source code files, and
resource files. We will explore all the folders and files in the android app.  
1. Manifests Folder
2. Java Folder
3. res (Resources) Folder
 Drawable Folder
 Layout Folder
 Mipmap Folder
 Values Folder
 Gradle Scripts
Manifests Folder

2
Manifests folder contains AndroidManifest.xml for creating our android application.
This file contains information about our application such as the Android version,
metadata, states package for Kotlin file, and other application components. It acts as an
intermediator between android OS and our application.
Following is the manifests folder structure in the android application. 

AndroidManifest.xml 
 
XML

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


<manifest xmlns:android="http:// schemas.android.com/apk/res/android"
    package="com.geeksforgeeks.myapplication">
 
    <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>

2
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Java folder
The Java folder contains all the java and Kotlin source code (.java) files that we create
during the app development, including other Test files. If we create any new project
using Kotlin, by default the class file MainActivity.kt file will create automatically
under the package name “com.geeksforgeeks.myfirstkotlinapp” as shown below. 

MainActivity.kt and MainActivity.java


Kotlin

package com.geeksforgeeks.myapplication
 
    import androidx.appcompat.app.AppCompatActivity import android.os.Bundle
 

2
    class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    }
}

Java

package com.geeksforgeeks.myapplication;
 
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

2
Resource (res) folder
The resource folder is the most important folder because it contains all the non-code
sources like images, XML layouts, and UI strings for our android application. 
 

 
res/drawable folder
It contains the different types of images used for the development of the application.
We need to add all the images in a drawable folder for the application development.
 
res/layout folder
The layout folder contains all XML layout files which we used to define the user
interface of our application. It contains the activity_main.xml file.
 
XML

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


<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http:// schemas.android.com/apk/res/android"
    xmlns:app="http:// schemas.android.com/apk/res-auto"
    xmlns:tools="http:// schemas.android.com/tools"

2
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>

res/mipmap folder
This folder contains launcher.xml files to define icons that are used to show on the
home screen. It contains different density types of icons depending upon the size of the
device such as hdpi, mdpi, xhdpi.
 
res/values folder
Values folder contains a number of XML files like strings, dimensions, colors, and
style definitions. One of the most important files is the strings.xml file which contains
the resources. 
 
XML

2
<resources>
    <string name="app_name">NameOfTheApplication</string>
    <string name="checked">Checked</string>
    <string name="unchecked">Unchecked</string>
</resources>

Gradle Scripts folder


Gradle means automated build system and it contains a number of files that are used
to define a build configuration that can be applied to all modules in our application. In
build.gradle (Project) there are buildscripts and in build.gradle (Module) plugins and
implementations are used to build configurations that can be applied to all our
application modules.
 

2
PRACTICAL 6:-

Applications based on Text boxes and Button

Text boxes:-
In your Android application, you may want to accept user input. There are many ways you can
do that and one of the most basics is the textbox.
In Android you can use the EditText class in order to create a textbox on your screen in which
the user will write text. Then, we have to bundle this textbox with a specific key event, so when
the user presses the key the application can get the text written in the textbox as an input and
perform a specific action.

Button:-
In Android applications, a Button is a user interface that is used to perform some action when
clicked or tapped. It is a very common widget in Android and developers often use it. This article
demonstrates how to create a button in Android Studio.

2
PRACTICAL 7:-

Applications based on check boxes and buttons

A check box is used to select or deselect action items. It can be used for a single item
or for a list of multiple items that a user can choose from. The control has three
selection states: unselected, selected, and indeterminate. Use the indeterminate state
when a collection of sub-choices have both unselected and selected states.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <CheckBox android:id="@+id/checkbox_meat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Meat" />
    <CheckBox android:id="@+id/checkbox_cheese"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

2
        android:text="Cheese"/>
</LinearLayout>

2
PRACTICAL 8:-

Applications based on radio buttons

Android radio button is a widget that can have more than one option to choose from.
The user can choose only one option at a time. Each option here refers to a radio button
and all the options for the topic are together referred to as Radio Group. Hence, Radio
Buttons are used inside a RadioGroup. 
Pre-requisites: 
Android App Development Fundamentals for Beginners
Guide to Install and Set up Android Studio
Android | Starting with the first app/android project
Android | Running your first Android app
How to create an Android App to use Radio Buttons
This example will help in developing an Android App that creates Radio Buttons
according to the above example:
Step 1: First create a new Android Application. This will create an XML file
“activity_main.xml” and a Java File “MainActivity.Java”. Please refer the pre-
requisites to learn more about this step.

Step 2: Open the “activity_main.xml” file and add the following widgets in a Relative
Layout: 
A TextView to display the question message
A RadioGroup to hold the option Radio Buttons which are the possible answers

2
4 RadioButtons to hold an answer each.
A Submit and a Clear button to store the response.
Also, Assign the ID to each of the components along with other attributes as shown in
the given image and the code below. The assigned ID on a component helps that
component to be easily found and used in the Java files.
Syntax:
android:id="@+id/id_name"
Here the given IDs are as follows:
RadioGroup: groupradio
RadioButton1: radia_id1
RadioButton2: radia_id2
RadioButton3: radia_id3
RadioButton4: radia_id4
Submit Button: submit
Clear Button: clear
This will make the UI of the Application.

Step 3: Now, after the UI, this step will create the Backend of Application. For this,
open the “MainActivity.java” file and instantiate the components made in the XML file
(RadioGroup, TextView, Clear, and Submit Button) using findViewById() method.
This method binds the created object to the UI Components with the help of the
assigned ID.

2
Syntax: General 
ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);
Syntax: Components used
Button submit = (Button)findViewById(R.id.submit); 
Button clear = (Button)findViewById(R.id.clear); 
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.groupradio); 
Step 4: This step involves setting up the operations on the RadioGroup, RadioButtons,
and the Submit and Clear Buttons.
 These operations are as follows: 
Unset all the Radio Buttons initially as the default value. This is done by the following
command:
radioGroup.clearCheck();
Add the Listener on the RadioGroup. This will help to know whenever the user clicks
on any Radio Button, and the further operation will be performed. The listener can be
added as follows:
radioGroup.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener(){}
Define the operations to be done when a radio button is clicked. This involves getting
the specific radio button that has been clicked, using its id. Then this radio button gets
set and the rest of the radio button is reset.
Add the listener on Submit button and clear button. This will be used to check when
the user clicks on the button. This is done as follows:
submit.setOnClickListener(new View.OnClickListener() {} 
clear.setOnClickListener(new View.OnClickListener() {}
In the Submit Button Listener, set the operations to be performed. This involves
displaying the marked answer in the form of Toast.

2
In the Clear Button Listener, set the operations to be performed. This involves
resetting all the radio buttons.
Step5: Now run the app and operate as follows: 
 When the app is opened, it displays a question with 4 answers and a clear and
submit button.
 When any answer is clicked, that radio button gets set.
 Clicking on any other radio button sets that one and resets the others.
 Clicking on Submit button displays the currently marked answer as a Toast.
 Clicking on Clear button resets all the radio buttons to their default state.

2
PRACTICAL 9:-

Applications based on Intents and Intent filters


The intent is a messaging object which tells what kind of action to be performed. The
intent’s most significant use is the launching of the activity. Intent facilitates the
communication between the components.
Fundamental use case of Intents
Starting Activity
An activity represents the single screen in an app, Bypassing intent instance we can
start an activity.
Starting a Service
A Service is a component that performs operations in the background without a user
interface, which is also called a background process.
Delivering a Broadcast
A broadcast is a message that any app can receive. In android, the system delivers
various broadcast system events like device starts charging, disable or enable airplane
mode, etc.
Intent Type
There are two types of intent
Explicit intent: Explicit intent can do the specific application action which is set by
the code like changing activity, In explicit intent user knows about all the things like
after clicking a button which activity will start and Explicit intents are used for
communication inside the application
Implicit Intent: Implicit intents do not name a specific component like explicit intent,
instead declare general action to perform, which allows a component from another app
to handle.

2
For example: when you tap the share button in any app you can see the Gmail,
Bluetooth, and other sharing app options. 
Intent Filter
Implicit intent uses the intent filter to serve the user request.
The intent filter specifies the types of intents that an activity, service, or broadcast
receiver can respond.
Intent filters are declared in the Android manifest file.
Intent filter must contain <action>
Example:
XML

<intent-filter
  android:icon="drawable resource"
  android:label="string resource"
  android:priority="integer" >
   . . .
</intent-filter>

Implementation of Intent Filter with a Demo App


Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New
Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add dependencies to the build.gradle(Module:app) file
Add the following dependency to the build.gradle(Module:app) file. We are adding
these two dependencies because to avoid using findViewById() in
our MainActivity.kt file. Try this out otherwise use the normal way
like findViewById().

2
apply plugin: ‘kotlin-android’
apply plugin: ‘kotlin-android-extensions’

Step 3: Working with the activity_main.xml file


Navigate to the app > res > layout > activity_main.xml and add the below code to that
file.
Step 4: Working with the AndroidManifest.xml File
Step 5: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for
the MainActivity.kt file. Comments are added inside the code to understand the code in
more detail.
Output with Explanation:

Click on Send Button, you will see a screen like this,

2
Now choose Gmail app,

Now go to our app and click the view button,

our app dummy app. You can any app from these options because we are using a view
intent filter.

2
PRACTICAL 10:-

Applications based on activities and services

Activities:-
Activity class is one of the very important parts of the Android Component. Any app,
don’t matter how small it is (in terms of code and scalability), has at least one Activity
class. Unlike most programming languages, in which the main() method is the entry
point for that program or application to start its execution, the android operating system
initiates the code in an Activity instance by invoking specific callback methods that
correspond to specific stages of its Lifecycle. So it can be said that An activity is the
entry point for interacting with the user. Every activity contains the layout, which has a
user interface to interact with the user. As we know that every activity contains a layout
associated with it, so it can be said that the activity class is the gateway, through which
a user can interact programmatically with the UI. Layout for a particular activity is set
with the help of setContentView(). setContentView() is a function that takes View as a
parameter. The view parameter basically contains the layout file for that activity. The
code has been given in both Java and Kotlin Programming Language for Android.
The Following Code Indicates that activity_main is the Layout File of MainActivity
Kotlin
Java

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

2
        setContentView(R.layout.activity_main)
    }
}

While activities are often presented to the user as the full-screen window,
Multiwindow mode, or Picture in Picture mode, here are two methods almost all
subclasses of Activity will implement:
onCreate()
onPause()
1. onCreate() Method
The syntax for Kotlin:
The syntax for Java:
protected void onCreate(Bundle savedInstanceState)
onCreate(Bundle) method is the place, where the user initializes the activity. This
method is called when the activity is starting. This is the method that is used to
initialize most of the things in the android app. onCreate() method
takes savedInstanceState as the parameter, which the object of type Bundle, i.e Bundle
Object which contains the previously saved data of the activity. If the activity is newly
created then the bundle won’t be saving any data of the activity and would contain the
null value.
onCreate() method calls the setContentView() method to set the view corresponding
to the activity. By default in any android application, setContentView point to
activity_main.xml file, which is the layout file corresponding to MainActivity. The
onCreate method uses the findViewById() method so that the user can interact
programmatically with the widgets in android and then customize them according to
need.
Bundle: If the activity is being re-initialized or restarted after previously being closed,
then this Bundle contains the data it most recently supplied

2
in onSaveInstanceState(Bundle). onSaveInstanceState() method is the method that is
called to save the data just before our activity is killed.
2. onPause() Method
The syntax for Kotlin:
override fun onPause() {
super.onPause()
}
The syntax for Java:
protected void onPause() {
super.onPause();
}
This method is called part of the Activity Lifecycle when the user no longer actively
interacts with the activity, but it is still visible on the screen. Let’s suppose the user is
running two apps simultaneously on a mobile phone, i.e when activity B is launched in
front of activity A, activity A will go in the onPause() state, and activity B would go in
the onStart() state of the activity lifecycle. One important point to be remembered is
that for any activity to be accessed by a system, i.e. android here, that activity must be
declared in a Manifest File. The Manifest File is an XML file included in the
Application and is by default known as AndroidManifest.xml.
Declaring Activity in Manifest File
Open the app folder, and then open the subfolder manifest, and then open
the AndroidManifest.xml file.

2
Let’s suppose the reader wants to have one more activity, apart from the MainActivity
which is included by default in the project. Before adding one more activity and not
doing any changes,
Adding Permissions to Application
For any service that the Developer wants to use in the Android App, like Internet
service, Bluetooth service, Google Maps, App Notification service, etc, the Developer
needs to take the permission of the Android System. All those Permissions or Requests
must be declared within the Manifest File. Open the AndroidManifest.xml file, with the
procedure shown above. Let’s say the user needs to add Internet permission, that needs
to be accessed by the app. Add the below Internet Permission within the manifest tag.
<uses-permission android:name="android.permission.INTERNET" />
Let’s say one needs to add Bluetooth permission within the app, then it must be
declared like this:
<uses-permission android:name="android.permission.BLUETOOTH" />
Note: Let’s say that the MainActivity extends AppCompatActivity in the code snippet
given at the top, internally the structure is as shown in the image given below. It can be
seen that AppCompatActivity also extends the Activity Class.

2
Services
Services in Android are a special component that facilitates an application to run in
the background in order to perform long-running operation tasks. The prime aim of a
service is to ensure that the application remains active in the background so that the
user can operate multiple applications at the same time. A user-interface is not desirable
for android services as it is designed to operate long-running processes without any
user intervention. A service can run continuously in the background even if the
application is closed or the user switches to another application. Further, application
components can bind itself to service to carry out inter-process communication(IPC) .
There is a major difference between android services and threads, one must not be
confused between the two. Thread is a feature provided by the Operating system to
allow the user to perform operations in the background. While service is an android
component that performs a long-running operation about which the user might not be
aware of as it does not have UI.
Types of Android Services
\1. Foreground Services:
Services that notify the user about its ongoing operations are termed as Foreground
Services. Users can interact with the service by the notifications provided about the
ongoing task. Such as in downloading a file, the user can keep track of the progress in
downloading and can also pause and resume the process.
2. Background Services:
Background services do not require any user intervention. These services do not notify
the user about ongoing background tasks and users also cannot access them. The
process like schedule syncing of data or storing of data fall under this service.
3. Bound Services:
This type of android service allows the components of the application like activity to
bound themselves with it. Bound services perform their task as long as any application
component is bound to it. More than one component is allowed to bind themselves with
a service at a time. In order to bind an application component with a
service bindService() method is used. 

2
The Life Cycle of Android Services
In android, services have 2 possible paths to complete its life cycle namely Started and
Bounded.
1. Started Service (Unbounded Service):
By following this path, a service will initiate when an application component calls
the startService() method. Once initiated, the service can run continuously in the
background even if the component is destroyed which was responsible for the start of
the service. Two option are available to stop the execution of service:
By calling stopService() method,
The service can stop itself by using stopSelf() method.
2. Bounded Service:
It can be treated as a server in a client-server interface. By following this path, android
application components can send requests to the service and can fetch results. A service
is termed as bounded when an application component binds itself with a service by
calling bindService() method. To stop the execution of this service, all the components
must unbind themselves from the service by using unbindService() method.

To carry out a downloading task in the background, the startService() method will be


called. Whereas to get information regarding the download progress and to pause or
resume the process while the application is still in the background, the service must be
bounded with a component which can perform these tasks.
Fundamentals of Android Services

2
A user-defined service can be created through a normal class which is extending
the class Service. Further, to carry out the operations of service on applications, there
are certain callback methods which are needed to be overridden. 
Example of Android Services
Playing music in the background is a very common example of services in android.
From the time when a user starts the service, music play continuously in the
background even if the user switches to another application. The user has to stop the
service explicitly in order to pause the music. Below is the complete step-by-step
implementation of this android service using a few callback methods.

2
PRACTICAL 11:-

Application based on action bar


In Android applications, ActionBar is the element present at the top of
the activity screen. It is a salient feature of a mobile application that has a consistent
presence over all its activities. It provides a visual structure to the app and contains
some of the frequently used elements for the users. 
Components included in the ActionBar are:
App Icon: Display the branding logo/icon of the application.
View Controls: Section that displays the name of the application or current activity.
Developers can also include spinner or tabbed navigation for switching between
views.
Action Button: Contains some important actions/elements of the app that may be
required to the users frequently.
Action Overflow: Include other actions that will be displayed as a menu.
Designing a Custom ActionBar
The following example demonstrates the steps involved in creating a custom
ActionBar for the MainActivity of an application. All important aspects of visual
elements like icon, title, subtitle, action buttons, and overflow menu will be covered. 

Step 1: Default ActionBar


As mentioned earlier, every android app contains an ActionBar by default. This pre-
included ActionBar display title for the current activity that is managed by
the AncdroidManifest.xml file. The string value of the application’s title is provided
by @string/app_name resource present under the application nodes.
<application
       …..
      …..

2
       android:label=”@string/app_name”
     …..
</application>
Output:

Step 2: Creating a new directory and design items of ActionBar


To code the elements of ActionBar, create a new directory in the resource folder of
the application project files. Right-click on the res folder and selects New ->
Directory. Give the name “menu” to the new directory. 

Further, create a new Menu Resource File by right click on the menu directory. As
the ActionBar is being created for the main Activity, type the name as “main” to the
Menu Resource File. With this, a new file named “main.xml” must be created under
the menu directory. In this file, one can declare the items which will be displayed as
the action buttons of the ActionBar.

For every menu items, the following attributes are needed to be configured:
android:title: Its value contains the title of the menu item that will be displayed when
a user clicks and holds that item in the app.
android:id: A unique ID for the menu item that will be used to access it anywhere in
the whole application files.

2
android:orderInCategory: The value of this attribute specify the item’s position in the
ActionBar. There are two ways to define the position of different menu items. The
first one is to provide the same value of this attribute for all items and the position
will be defined in the same order as they are declared in the code. The second way is
to provide a different numeric value for all items and then the items will position
themselves according to ascending order of this attribute’s value.
app:showAsAction: This attribute defines how the item is going to be present in the
action bar. There are four possible flags to choose from:
a. always: To display the item in the ActionBar all the time.
b. ifRoom: To keep the item if space is available.
c. never: With this flag, the item will be not be displayed as an icon in ActionBar,
but will be present in the overflow menu.
d. withText: To represent an item as both icon and the title, one can append this flag
with the always or ifRoom flag(always|withText or ifRoom|withText).
android:icon: The icon of an item is referenced in the drawable directories through
this attribute.
Icon of an ActionBar Item
In order to provide an icon to an item, right-click on the res folder, select new, and
then Image Asset. A dialog box will appear, choose the Icon Type as Action Bar and
Tab Icons. Choose assets type as “Clip Art” and select an image from the clip art
collection. Provide a desired name to the icon. Click on Next, then Finish. This icon
will now get loaded in the drawable directory of the res folder. The name provided by
the developers to these icons will now be used to reference the item’s icon resource.

Step 3: Working with the Activity File

2
The items of an ActionBar is designed with a purpose to perform some operations.
Those operations/actions of the items are declared in that Activity file for which the
ActionBar has been designed. In this example, the target activity is
the MainActivity file. Further, the custom title, subtitle, and application logo are also
defined in this file. Below is the proper code to design all mentioned items and to
display a toast message when a user clicks on the items of ActionBar.
Step 4: Color of the ActionBar
Head over to style.xml file located in the values directory of the res folder. To
change the default color of the ActionBar, one has to change
the colorPrimary resource. Below is the code to make the ActionBar color ‘green’.
Step 5: Working with activity_main.xml file
This file defines the layout of the activity. In this example, the prime focus is on
ActionBar, thus the activity will contain only a simple TextView.
Advantages of ActionBar
Provides a customized area to design the identity of an app
Specify the location of the user in the app by displaying the title of the current
Activity.
Provides access to important and frequently used actions
Support tabs and a drop-down list for view switching and navigation.
Disadvantages of ActionBar
All features of the ActionaBar are not introduced at once but were introduced with
the release of different API levels such as API 15, 17, and 19.
The ActionBar behaves differently when it runs on different API levels.
The features that were introduced with a particular API does not provide backward
compatibility.

2
PRACTICAL 12:-

Applications based on option menu


In Android, there are three types of Menus available to define a set of options and
actions in our android applications. The Menus in android applications are the
following:
Android Options Menu
Android Context Menu
Android Popup Menu
Android Option Menus are the primary menus of android. They can be used for
settings, searching, deleting items, etc. When and how this item should appear as an
action item in the app bar is decided by the Show Action attribute. The values that can
be given for the showAsAction attribute:
always: This ensures that the menu will always show in the action bar.
Syntax:
app:showAsAction="always"
Example: 
XML

<item
    android:id="@+id/message"
    android:icon="@android:drawable/ic_menu_send"
    app:showAsAction="always"
    android:title="message" />

2
never: This means that the menu will never show, and therefore will be available
through the overflow menu Syntax:
app:showAsAction="never"
Example: 
XML

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

2
PRACTICAL 13:-

Applications based on rating bar


RatingBar is used to allow the users to rate some products. In the below
code getRating() function is used to calculate the rating of the products.
The getRating() function returns double type value.
Below steps are involved to create a RatingBar in Android:
Create a new android project.
Add RatingBar in your activity_main.xml.
Add Button to invoke action.
Use TextView to display the ratings.
To use the rating bar in the app, we will use the in-built RatingBar widget, hence the
first step is to import it into the project.
In the MainActivity, make the RatingBar object denoted by the variable ‘rt’ and find
its corresponding view in the XML file. This is done by the findViewById() method.
After the java object has successfully bind to its view, create the ‘stars’ layout, which
the user will interact with, to set the rating.
To get the drawable stars, the method rt.getProcessDrawable() is used. Then to modify
the colours of the stars, the method setColorFilter() is used and the argument
Color.YELLOW is passed. Finally, the Call method is written to extract the value of
the rating that the user has selected, by the method rt.getMethod().

2
PRACTICAL 14:-

Applications based on media player

MediaPlayer Class in Android is used to play media files. Those are Audio and Video
files. It can also be used to play audio or video streams over the network. So in this
article, the things discussed are:
MediaPlayer State diagram
Creating a simple audio player using MediaPlayer API. Have a look at the following
image. Note that we are going to implement this project using the Kotlin language. 
State Diagram of the MediaPlayer Class
The playing of the audio or video file using MediaPlayer is done using a state
machine.
The following image is the MediaPlayer state diagram.

In the above MediaPlayer state diagram, the oval shape represents the state of the
MediaPlayer instance resides in.
There are two types of arcs showing in the state diagram. One with the single
arrowhead represents the synchronous method calls of the MediaPlayer instance and
one with the double arrowhead represents the asynchronous calls.

2
Steps to create a simple MediaPlayer in Android
Step 1: Create an empty activity project
Create an empty activity Android Studio project. And select Kotlin as a programming
language.
Step 2: Create a raw resource folder
Create a raw resource folder under the res folder and copy one of the .mp3 file
extension.
Step 3: Working with the activity_main.xml file
The layout of the application consists of three buttons PLAY, PAUSE, and STOP
mainly, which is used to control the state of the MediaPlayer instance.
Invoke the following code inside the activity_main.xml file to implement the UI.
Step 4: Working with the MainActivity.kt file 
The MediaPlayer instance needs the attributes needs to be set before playing any
audio or video file.
Invoke the following inside the MainActivity.kt file. Comments are added for better
understanding. 

2
PRACTICAL 15:-

Applications based on content providers


In Android, Content Providers are a very important component that serves the
purpose of a relational database to store the data of applications. The role of the
content provider in the android system is like a central repository in which data of the
applications are stored, and it facilitates other applications to securely access and
modifies that data based on the user requirements. Android system allows the content
provider to store the application data in several ways. Users can manage to store the
application data like images, audio, videos, and personal contact information by
storing them in SQLite Database, in files, or even on a network. In order to share the
data, content providers have certain permissions that are used to grant or restrict the
rights to other applications to interfere with the data.

Content URI
Content URI(Uniform Resource Identifier) is the key concept of Content providers.
To access the data from a content provider, URI is used as a query string. 
Details of different parts of Content URI:
 content:// – Mandatory part of the URI as it represents that the given URI is
a Content URI.
 authority – Signifies the name of the content provider like contacts, browser,
etc. This part must be unique for every content provider.
 optionalPath – Specifies the type of data provided by the content provider. It
is essential as this part helps content providers to support different types of data that
are not related to each other like audio and video files.

2
 optionalID – It is a numeric value that is used when there is a need to access
a particular record.
If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-based
URI.
Operations in Content Provider
Four fundamental operations are possible in Content Provider
namely Create, Read, Update, and Delete. These operations are often termed
as CRUD operations. 
 Create: Operation to create data in a content provider.
 Read: Used to fetch data from a content provider.
 Update: To modify existing data.
 Delete: To remove existing data from the storage.
Working of the Content Provider
UI components of android applications like Activity and Fragments use an
object CursorLoader to send query requests to ContentResolver. The ContentResolver
object sends requests (like create, read, update, and delete) to the ContentProvider as a
client. After receiving a request, ContentProvider process it and returns the desired
result. Below is a diagram to represent these processes in pictorial form.

Creating a Content Provider


Following are the steps which are essential to follow in order to create a Content
Provider:
 Create a class in the same directory where the that MainActivity file resides
and this class must extend the ContentProvider base class.
 To access the content, define a content provider URI address.
 Create a database to store the application data.
 Implement the six abstract methods of ContentProvider class.
 Register the content provider in AndroidManifest.xml file using <provider>
tag.

2
Following are the six abstract methods and their description which are essential to
override as the part of ContenProvider class:
Abstract Method Description

A method that accepts arguments and fetches the data from the 
query()
desired table. Data is retired as a cursor object.

To insert a new row in the database of the content provider. 


insert()
It returns the content URI of the inserted row. 

This method is used to update the fields of an existing row. 


update()
It returns the number of rows updated.

This method is used to delete the existing rows. 


delete()
It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail


getType() Extension(MIME) 
type of data to the given Content URI.

As the content provider is created, the android system calls 


onCreate()
this method immediately to initialise the provider.

Example

The prime purpose of a content provider is to serve as a central repository of data


where users can store and can fetch the data. The access of this repository is given to
other applications also but in a safe manner in order to serve the different
requirements of the user. The following are the steps involved in implementing a
content provider. In this content provider, the user can store the name of persons and

2
can fetch the stored data. Moreover, another application can also access the stored
data and can display the data.
Note: Following steps are performed on Android Studio version 4.0
Creating a Content Provider:
Step 1: Create a new project
1. Click on File, then New => New Project.
2. Select language as Java/Kotlin.
3. Choose empty activity as a template
4. Select the minimum SDK as per your need.
Step 2: Modify the strings.xml file
All the strings used in the activity are stored here.
Step 4: Design the activity_main.xml layout
One Textview, EditText field, two Buttons, and a Textview to display the stored
data will be added in the activity
Step 5: Modify the MainActivity file
Button functionalities will be defined in this file. Moreover, the query to be
performed while inserting and fetching the data is mentioned here
Step 6: Modify the AndroidManifest file
The AndroidManifest file must contain the content provider name, authorities, and
permissions which enable the content provider to be accessed by other applications.

2
PRACTICAL 16:-

Applications based on accessing camera


To add images from the camera in flutter, we’ll use the image_picker package. For
this, you’ll need to use your real device.
Follow the below steps to display the images from the camera:
Step 1: Create a new flutter application.
flutter create <APP_NAME>

Step 2: Delete the default code from the main.dart file.


Step 3: Add the dependency to your pubspec.yaml file:

Step 4: Use the below code in the main.dart file :


main.dart:
When no image is selected, it will result:

2
When the button is tapped, the mobile’s camera will be opened to capture the image as
shown below:
When the image is captured, it will be displayed on the screen as shown below:

Explanation:
Import image_picker package.
Create async selectFromCamera() function and await for camera image.
After loading the image from the camera, the image will be displayed on the screen.

2
PRACTICAL 17:-

Applications based on accessing locations


As a developer when you work on locations in Android then you always have some
doubts about selecting the best and efficient approach for your requirement. So in this
article, we are going to discuss how to get the user’s current location in Android. There
are two ways to get the current location of any Android device:
Android’s Location Manager API
Fused Location Provider: Google Play Services Location APIs
Before moving any of the above methods we will have to take location permission.
Taking Location Permission
Step 1: Define uses permissions for location access in the manifest file
<!– To request foreground location access, declare one of these permissions. –>
<uses-permission
android:name=”android.permission.ACCESS_FINE_LOCATION” />
<uses-permission
android:name=”android.permission.ACCESS_COARSE_LOCATION” />
<!– Required only when requesting background location access on Android 10 (API
level 29) –>
<uses-permission
android:name=”android.permission.ACCESS_BACKGROUND_LOCATION” />
Step 2: Define uses permission for internet access because we are going to use
Internet Provider.

2
Step 3: Write a function for checking that location permission is granted or not. If
permission is not granted then ask for the permissions in run time.

2
PRACTICAL 18:-

Applications based on the activation of sensors


In our childhood, we all have played many android games like Moto Racing and
Temple run in which by tilting the phone the position of the character changes. So, all
these happen because of the sensors present in your Android device. Most Android-
powered devices have built-in sensors that measure motion, orientation, and various
environmental conditions. Android Sensors can be used to monitor the three-
dimensional device movement or change in the environment of the device such as light,
proximity, rotation, movements, magnetic fields, and much more.
Types of Sensors
Motion Sensors: These sensors measure acceleration forces and rotational forces
along three axes. This category includes accelerometers, gravity sensors, gyroscopes,
and rotational vector sensors.
Position Sensors: These sensors measure the physical position of a device. This
category includes orientation sensors and magnetometers.
Environmental Sensors: These sensors measure various environmental parameters,
such as ambient air temperature and pressure, illumination, and humidity. This category
includes barometers, photometers, and thermometers.
Android Sensor API
We can collect raw sensor data by using Android Sensor API. Android sensor API
provides many classes and interfaces. Some of the important classes and interfaces are:
SensorManager Class: Sensor manager is used to accessing various sensors present in
the device.
Sensor Class: The sensor class is used to get information about the sensor such as
sensor name, sensor type, sensor resolution, sensor type, etc.
SensorEvent class: This class is used to find information about the sensor.

2
SensorEventListener interface: This is used to perform some action when sensor
accuracy changes.
Example: Light Sensor App
This app will show us light intensity in our room with the help of a light sensor
present in our phone.
Step by Step Implementation 
Step 1: Create a New Project in your android studio
To create a new project in Android Studio please refer to How to Create/Start a New
Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light Sensor"
android:textSize="20sp"
android:textColor="@color/black"

2
android:layout_centerInParent="true" />

</RelativeLayout>
Step 3: Working With the MainActivity.kt
 
Go to the MainActivity.kt file and refer to the following code. Below is the code for
the MainActivity.kt file. Comments are added inside the code to understand the code in
more detail.

2
PRACTICAL19:-

Applications based on animations

Animation is the process of adding a motion effect to any view, image, or text. With
the help of an animation, you can add motion or can change the shape of a specific
view. Animation in Android is generally used to give your UI a rich look and feel. The
animations are basically of three types as follows: 
Property Animation
View Animation
Drawable Animation
1. Property Animation
Property Animation is one of the robust frameworks which allows animating almost
everything. This is one of the powerful and flexible animations which was introduced
in Android 3.0. Property animation can be used to add any animation in
the CheckBox, RadioButtons, and widgets other than any view.

2. View Animation
View Animation can be used to add animation to a specific view to perform tweened
animation on views. Tweened animation calculates animation information such as size,
rotation, start point, and endpoint. These animations are slower and less flexible. An
example of View animation can be used if we want to expand a specific layout in that
place we can use View Animation. The example of View Animation can be seen in
Expandable RecyclerView.
3. Drawable Animation
Drawable Animation is used if you want to animate one image over another. The
simple way to understand is to animate drawable is to load the series of drawable one

2
after another to create an animation. A simple example of drawable animation can be
seen in many apps Splash screen on apps logo animation.
Important Methods of Animation 

Methods Description

startAnimation() This method will start the animation. 

This method will clear the animation running on a specific


clearAnimation()
v64iew.

You might also like