AP Narender Singh Lab
AP Narender Singh Lab
AP Narender Singh Lab
ANDROID PROGRAMMING
2
Index
S.No Description
Installation of Java, android Framework
1.
2
Applications based on the activation of sensors
18.
2
PRACTICAL 1:-
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
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.
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:-
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:
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:
2
2
PRACTICAL 3:-
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:-
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:-
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
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.
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
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>
2
PRACTICAL 6:-
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:-
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.
2
android:text="Cheese"/>
</LinearLayout>
2
PRACTICAL 8:-
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:-
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>
2
apply plugin: ‘kotlin-android’
apply plugin: ‘kotlin-android-extensions’
2
Now choose Gmail app,
our app dummy app. You can any app from these options because we are using a view
intent filter.
2
PRACTICAL 10:-
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.
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:-
2
android:label=”@string/app_name”
…..
</application>
Output:
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.
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:-
<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:-
2
PRACTICAL 14:-
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:-
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.
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.
Example
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:-
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:-
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:-
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:-
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