Lab manual AP[1]
Lab manual AP[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
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 bel
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’.
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.
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.
To run your first android app in Android Studio you may refer to Running your first Android app.
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.
In Android Virtual Emulator all functions that are feasible on real Android mobile is works on virtual Device
like:
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.
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.
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.
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
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.
a. Method
b. Variable
c. Block
d. Nested class
class Test
{
// static method static
void m1()
{
System.out.println("from m1");
}
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
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
<application android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
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
Java
package com.geeksforgeeks.myapplication;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity; public class
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
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
<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" />
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
<resources>
<string name="app_name">NameOfTheApplication</string>
<string name="checked">Checked</string>
<string name="unchecked">Unchecked</string>
</resources>
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.
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.
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
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.
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.
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.
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.
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
our app dummy app. You can any app from these options because we are using a view intent filter.
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
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
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.
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.
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.
The Life Cycle of Android Services
In android, services have 2 possible paths to complete its life cycle namely Started and Bounded.
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
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.
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.
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.
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:
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.
<item
android:id="@+id/message"
android:icon="@android:drawable/ic_menu_send"
app:showAsAction="always" android:title="message" />
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" />
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().
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.
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.
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.
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.
Following are the six abstract methods and their description which are essential to override as the part of
ContenProvider class:
Abstract Method Description
query() A method that accepts arguments and fetches the data from the desired table. Data is retired
as a cursor object.
insert() To insert a new row in the database of the content provider. It returns the
content URI of the inserted row.
update() This method is used to update the fields of an existing row. It returns the
number of rows updated.
delete() This method is used to delete the existing rows. It returns the
number of rows deleted.
onCreate() As the content provider is created, the android system calls 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
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 2: Delete the default code from the main.dart file. Step 3: Add the
dependency to your pubspec.yaml file:
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.
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.
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.
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.
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"
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.
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
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 M
sc ethods Description