Android Programming Practical File
Android Programming Practical File
Practical file of
“Android Programming”
SUBMITTED BY: SUBMITTED TO:
NAME Ms. Bhavisha Dhir
Section-A (group 1) Asst. Professor
ROLL NO
INDEX
The Java Development Kit (JDK), officially called “Java SE”, is needed for writing Java programs.
The JDK is freely available from Sun Micro-systems, now it is part of Oracle. check it–
[Link]
• If you have installed the older versions of JDK/JRE, uninstall all of them.
• Go to Control Panel >> “Programs” >> Select Programs and Features” >>
Uninstall ALL programs begin with “Java”, like “Java SE Development Kit, etc.
Click the Search button and Type “cmd” Choose “Command Prompt”, or Rightclick “Start”
button run enter “cmd”. the following commands to verify that JDK/JRE is properly installed
and display their version.
1
Installing the Android SDK
Note: You can copy the SDK from your friends or any other computer with the same OS because the
download size is 3GB of zip data and expand to 5 GB of disk data.
iv Click Apply. Android Studio starts installing your selected packages. After completing the
installation, the Status of the installed packages and tools changes from Not Installed to
Installed.
v Click OK.
2
2. Android SDK Manager and its 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.
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:
3
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.
Thus, it simply means that without needing any physical device Android SDK component “Android
Emulator” provides a virtual device on the System where we run our Application. The emulator’s
come with the configuration for Various android phones, tablets, Wear OS, and Android TV devices.
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:
4
6. SDK Platforms:- For Each Android Software, one SDK platform is available as shown
below:
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.
5. 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.
5
3 Programs based on the overriding, constructor, classes in java.
Overriding in JAVA:-
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.
}}
}}
Output:-
Constructor in JAVA :-
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.
class Main {
// constructor
Main() {
6
[Link]("Constructor Called:");
name = "Programiz";
Output:-
Constructor Called:
{ int x = 5;
7
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.
Stop Inheritance.
Stop Method overriding.
Stop value change.
class Test {
final static int x;
static
{
x = 10;
}
public static void main(String[] args)
{
[Link](x);
}
}
Static keyword :
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.
8
5:- Directory structure of an android project, common default resources
folders, the values of folders, leveraging android XML.
Android Studio is the official IDE (Integrated Development Environment) developed by the JetBrains
community which is freely provided by Google for android app development. 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
4. Gradle Scripts
Manifests Folder
Manifests folder contains [Link] for creating our android application. This
file contains information about our application such as the Android version, metadata, states
9
package for Kotlin file, and other application components. It acts as an intermediator between android
OS and our application.
[Link]
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="[Link]" />
</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
10
default the class file [Link] file will create automatically under the package name
“[Link]” as shown below.
Kotlin
package [Link]
Java
package [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState)
{
[Link](savedInstanceState);
setContentView([Link].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.
11
1. res (Resources) Folder.
Drawable Folder
Layout Folder
Mipmap Folder
Values Folder
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"
12
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
res/mipmap folder
This folder contains [Link] 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 [Link] file which contains the
resources.
XML
<resources>
<string name="app_name">NameOfTheApplication</string>
<string name="checked">Checked</string>
<string name="unchecked">Unchecked</string>
</resources>
13
• [Link]: The [Link] is an XML file which is used to store the colors for the
resources.
colorPrimary
colorPrimaryDark
colorAccent
These colors are used in some predefined resources of the android studio as well. These
colors as needed to be set opaque otherwise it could result in some exceptions to arise.
• [Link]: The [Link] is used for defining the dimensions for different
widgets to be included in the Android project. It is a good coding practice to use [Link]
to define a dimension rather than just writing the dimension in the resource, due to the fact
that if ever any need arises to change the dimension, instead of making a change to all, only
the [Link] can be changed once and the change is reflected in all.
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="nav_header_vertical_spacing">8dp</dimen>
<dimen name="nav_header_height">176dp</dimen>
<dimen name="fab_margin">16dp</dimen>
</resources>
14
• [Link]: One of the most important as well as widely used values file is the
[Link] due to its applicability in the Android project. Basic function of the [Link] is
to define the strings in one file so that it is easy to use same string in different positions in the
android project plus it makes the project looks less messy.
<resources>
<string name="app_name">Workshop app</string>
<string name="navigation_drawer_open">Open navigation drawer</string>
<string name="navigation_drawer_close">Close navigation drawer</string>
<string name="action_settings">Settings</string>
<string name="hello_blank_fragment">Hello blank fragment</string>
<string name="date">Date:</string>
<string name="timings">Timings:</string>
</resources>
• [Link]: Another important file in the values folder is the [Link] where all the
themes of the Android project are defined. The base theme is given by default having the
option to customize or make changes to the customized theme as well. Every theme has a
parent attribute which defines the base of the theme. There are a lot of options to choose from
depending on the need of the Android project. Below mentioned is the implementation of
[Link] resource
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="[Link]">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item> </style>
<style name="[Link]">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="[Link]" parent="[Link]" />
<style name="[Link]" parent="[Link]" />
</resources>
15
<?xml version="1.0" encoding="utf-8"?>
<!--ViewGroup1-->
<LinearLayout
xmlns:android="[Link]
res/android"
xmlns:app="[Link]
auto"
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:orientation="vertical"
android:padding="24dp"
tools:context=".MainActivity">
<!--TextView1 widget inside ViewGroup1-->
<TextView
style="@style/[Link].H
eadline5" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GEEKSFORGEEKS"
android:textColor="@color/green_500" />
<!--TextView2 widget inside ViewGroup1-->
<TextView
style="@style/[Link]
.Headline6" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Enter the user information"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!--ViewGroup2-->
<RelativeLayout
android:layout_width="match_pare
nt"
android:layout_height="wrap_conte
nt"
android:layout_marginTop="8dp"
android:clipToPadding="false">
<!--EditText1 widget inside ViewGroup2-->
<EditText
android:id="@+id/editText
1"
android:layout_width="mat
ch_parent"
android:layout_height="wr
ap_content"
16
android:hint="Enter first
name" />
<!--EditText2 widget inside ViewGroup2-->
<EditText
android:id="@+id/editText2
"
android:layout_width="mat
ch_parent"
android:layout_height="wra
p_content"
android:layout_below="@i
d/editText1"
android:hint="Enter last
name" />
<!--Button widget inside ViewGroup2-->
<Button
android:layout_width="wra
p_content"
android:layout_height="wra
p_content"
android:layout_below="@i
d/editText2"
android:layout_alignParent
End="true"
android:text="Submit" />
</RelativeLayout><!--End of ViewGroup2-->
</LinearLayout><!--End of ViewGroup1-->
17
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.
Creating a Button
• For creating a button we can use Button tag
• Just go inside the layout and type <Button
You will get a dropdown now press enter. Now you can set the width and height for you button. You
see the xml code for a button below.
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a button" />
android:id=”@+id/button”: This is the id for your button after @+id/ i.e. here the id for your button
is “button” (without quotes). This id will be used to handle the button in java coding. Whenever we
put @+id in android:id tag of any view a respective hex value is stored in a variable named with the
id you have given here in [Link] file. Now these things are done automatically so you do not need to
bother much about this. Basically what you need to know is this is the id that will be used for handling
this button.
Now we will create an Edit Text. For creating Edit Text we have the tag <EditText
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
18
So the code for the final layout that we have created yet is.
<LinearLayout
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a button" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Now if you will switch to the design view you will see something like this:-
19
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 Code: -
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" android:orientation="vertical"
android:gravity="center" android:background="#CDC5C5">
<TextView
android:layout_width="match_paren
t"
android:layout_height="wrap_conte
nt" android:text="choose food"
android:id="@+id/textView1"
android:gravity="center"
android:textSize="30sp"
android:textColor="#2B2121"/>
<LinearLayout
android:layout_width="match_paren
t"
android:layout_height="wrap_conte
nt" android:orientation="vertical"
android:gravity="center">
<CheckBox
android:layout_width="match_pare
nt"
android:layout_height="wrap_conte
nt" android:text="Pizza"
android:id="@+id/pizza"
android:textSize="30sp"
android:textColor="#2B2121"
android:paddingStart="40dp"
android:paddingEnd="40dp"
android:paddingTop="20dp"
android:paddingBottom="20dp"/>
<CheckBox
android:layout_width="match_pare
nt"
android:layout_height="wrap_conte
nt" android:text="Burger"
android:id="@+id/burger"
android:textSize="30sp"
20
android:textColor="#2B2121"
android:paddingStart="40dp"
android:paddingEnd="40dp"
android:paddingTop="20dp"
android:paddingBottom="20dp"/>
<CheckBox
android:layout_width="match_pare
nt"
android:layout_height="wrap_conte
nt" android:text="Noodle"
android:id="@+id/noodle"
android:textSize="30sp"
android:textColor="#2B2121"
android:paddingStart="40dp"
android:paddingEnd="40dp"
android:paddingTop="20dp"
android:paddingBottom="20dp"/>
</LinearLayout>
<Button
android:layout_width="wrap_conten
t"
android:layout_height="wrap_conte
nt" android:text="Order Now"
android:textSize="30sp"
android:textColor="#2B2121"
android:background="#FFC107"
android:id="@+id/btn"/>
</[Link]
tCompat>
JavaCode:
21
btn = findViewById([Link]);
pizza = findViewById([Link]);
burger =
findViewById([Link]);
noodle =
findViewById([Link]);
[Link](new [Link]()
{ @Override public
void onClick(View v) {
String total = "";
if([Link]()){
total+=
"Pizza"+"\n";
}
if([Link]()){ to
tal+= "Burger"+"\n";
}
if([Link]()){ to
tal+= "Noodle"+"\n";
}
[Link]([Link], total,
Toast.LENGTH_SHORT).show();
}
});
}
}
Output:-
22
8:- Application based on Radio Button.
RadioButton is a two states button which is either checked or unchecked. If a single radio button is
unchecked, we can click it to make checked radio button. Once a radio button is checked, it cannot be
marked as unchecked by user. RadioButton is generally used with RadioGroup. RadioGroup contains
several radio buttons, marking one radio button as checked makes all other radio buttons as
unchecked.
XML Code:-
<TextView
android:layout_width="match_paren
t"
android:layout_height="wrap_conte
nt" android:text="Choose gender"
android:textSize="30sp"
android:gravity="center"
android:textColor="#AE1414"/>
<RadioGroup
android:layout_width="match_pare
nt"
android:layout_height="wrap_conte
nt" android:id="@+id/radioGroup"
android:orientation="vertical">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#100707"
android:text="Male"
android:textSize="30sp"
android:id="@+id/male" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#100707"
android:text="Female"
android:textSize="30sp"
android:id="@+id/female" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
23
android:textColor="#100707"
android:text="Others" android:textSize="30sp"
android:id="@+id/others" />
</RadioGroup>
<Button
android:layout_width="wrap_conte
nt"
android:layout_height="wrap_conte
nt" android:text="Submit"
android:textSize="35sp"
android:id="@+id/btn"/>
</LinearLayout>
Java Code:-
package [Link];
import
[Link];
import [Link];
import [Link];
import [Link];
import
[Link];
import
[Link];
import [Link];
public class MainActivity extends AppCompatActivity
{ RadioGroup radioGroup;
RadioButton male;
RadioButton female;
RadioButton others;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
male = findViewById([Link]);
female =
findViewById([Link]); others
= findViewById([Link]); btn
= findViewById([Link]);
[Link](new [Link]()
24
{ @Override public
void onClick(View v) {
String result = "";
if([Link]()){
result = "Male";
} else if([Link]()){
resul t = "Female";
} else{ result =
"Others";
}
[Link]([Link], result,
Toast.LENGTH_SHORT).show();
}
});
}
}
Output:-
25
9:- Application based on Intents and Intents Filters.
An Intent is a messaging object you can use to request an action from another app component.
Although intents facilitate communication between components in several ways, there are three
fundamental use cases:
Starting an activity
An Activity represents a single screen in an app. You can start a new instance of an Activity by
passing an Intent to startActivity(). The Intent describes the activity to start and carries any necessary
data.
If you want to receive a result from the activity when it finishes, call startActivityForResult(). Your
activity receives the result as a separate Intent object in your activity's onActivityResult() callback.
For more information, see the Activities guide.
Starting a service
A Service is a component that performs operations in the background without a user interface. With
Android 5.0 (API level 21) and later, you can start a service with JobScheduler. For more information
about JobScheduler, see its API-reference documentation.
For versions earlier than Android 5.0 (API level 21), you can start a service by using methods of the
Service class. You can start a service to perform a one-time operation (such as downloading a file) by
passing an Intent to startService(). The Intent describes the service to start and carries any necessary
data.
If the service is designed with a client-server interface, you can bind to the service from another
component by passing an Intent to bindService(). For more information, see the Services guide.
Delivering a broadcast
A broadcast is a message that any app can receive. The system delivers various broadcasts for system
events, such as when the system boots up or the device starts charging. You can deliver a broadcast to
other apps by passing an Intent to sendBroadcast() or sendOrderedBroadcast().
The rest of this page explains how intents work and how to use them. For related information, see
Interacting with Other Apps and Sharing Content.
i Explicit intents specify which application will satisfy the intent, by supplying either
the target app's package name or a fully-qualified component class name. You'll typically use
an explicit intent to start a component in your own app, because you know the class name of
the activity or service you want to start. For example, you might start a new activity within
your app in response to a user action, or start a service to download a file in the background.
ii Implicit intents do not name a specific component, but instead declare a general
action to perform, which allows a component from another app to handle it. For example, if
you want to show the user a location on a map, you can use an implicit intent to request that
another capable app show a specified location on a map.
26
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.
Example:
XML
<intent-filter
android:icon="drawable resource"
android:label="string resource"
android:priority="integer" >
...
</intent-filter>
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.
Add the following dependency to the [Link](Module:app) file. We are adding these two
dependencies because to avoid using findViewById() in our [Link] file. Try this out
otherwise use the normal way like findViewById().
27
Navigate to the app > res > layout > activity_main.xml and add the below code to that file.
Go to the [Link] file and refer to the following code. Below is the code for
the [Link] file. Comments are added inside the code to understand the code in more detail.
28
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.
29
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
Java Code:
import [Link]
import [Link]
onCreate()
onPause()
1. onCreate() Method
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
30
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
Open the app folder, and then open the subfolder manifest, and then open
the [Link] 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,
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 [Link] 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.
31
Let’s say one needs to add Bluetooth permission within the app, then it must be declared like this:
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
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.
In android, services have 2 possible paths to complete its life cycle namely Started and Bounded.
32
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:
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.
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.
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.
33
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.
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.
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.
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 [Link] file. The
string value of the application’s title is provided by @string/app_name resource present under
the application nodes.
<application
android:label=”@string/app_name”
</application>
Output:
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 “[Link]” 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.
34
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:
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.
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.
35
Step 3: Working with the Activity File
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.
Head over to [Link] 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’.
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
Specify the location of the user in the app by displaying the title of the current Activity.
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 features that were introduced with a particular API does not provide backward compatibility.
36
12:- Application based on Option Menu.
Android Option Menus are the primary menus of android. They can be used for settings, search,
delete item [Link], we are going to see two examples of option menus. First, the simple option
menus and second, options menus with [Link], we are inflating the menu by calling the inflate()
method of MenuInflater class. To perform event handling on menu items, you need to override
onOptionsItemSelected() method of Activity class.
Android Option Menu Example:- Let's see how to create menu in android. Let's see the simple
option menu example that contains three menu items. <?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link] android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link]">
<[Link] android:layout_width="match_parent"
android:layout_height="wrap_content" android:theme="@style/[Link]">
<[Link] android:id="@+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/[Link]" />
</[Link]>
<include layout="@layout/content_main" />
</[Link]>
Output:-
37
13:- Application based on Rating Bar.
Android RatingBar can be used to get the rating from the user. The Rating returns a floatingpoint
number. It may be 2.0, 3.5, 4.0 [Link] RatingBar displays the rating in stars. Android RatingBar
is the subclass of AbsSeekBar [Link] getRating() method of android RatingBar class returns the
rating number.
<Button
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="submit" android:id="@+id/button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.615" />
<RatingBar
android:id="@+id/ratingBar" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="72dp"
android:layout_marginTop="60dp" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
Output:-
38
14:- Applications based on Media Player.
Xml code:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
" xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="#C6C0C0"
android:gravity="center">
<TextView
android:layout_width="match_pa
rent"
android:layout_height="wrap_co
ntent" android:text="Apna Music
" android:id="@+id/apnaMusic"
android:textColor="#1C1717"
android:textStyle="bold"
android:textSize="30dp"
android:gravity="center"
android:layout_marginTop="23d
p"/>
<ImageView
android:layout_width="match_parent
" android:layout_height="300dp"
android:layout_marginTop="40dp"
android:layout_marginBottom="40dp
" android:src="@drawable/img_2"/>
<LinearLayout
android:layout_width="match_pa
rent"
android:layout_height="wrap_co
ntent" android:gravity="center">
<Button
android:layout_width="120dp"
android:layout_height="wrap_co
ntent" android:text="Play"
android:id="@+id/play"
android:textSize="20dp"
android:onClick="play"
android:layout_margin="5dp"/>
<Button
android:layout_width="120dp"
android:layout_height="wrap_co
ntent" android:text="stop"
android:id="@+id/stop"
android:textSize="20dp"
android:onClick="stop"
android:layout_margin="5dp"/>
39
<Button
android:layout_width="120dp"
android:layout_height="wrap_co
ntent"
android:text="Pause"
Java code:-
package [Link]; import
[Link];
import
[Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main); player =
[Link](this, [Link].music1);
}
Output:-
40
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.
XML Code:-
41
16:- Application Based on accessing Camera.
Step 1:- Open Android Studio.
Specify your project name and the location where you want to save your project. Click on Next.
The above picture shows that my app's name is My Application, by default. However, you can change
the name to whatever you want.
Step 2:-Drag a button from the Toolbar, change the button name to Camera, and change button ID to
btncamera.
You can put any picture you want to see in the ImageView. For that, copy your image from your PC
and paste it to the "Drawables" folder which you can find in the left corner of the screen. Then, double
click on ImageView and give the source of that image i.e src= @drawable/imagename.
42
Step 3:- Now, the part remaining is the coding section.
Step 4 :- Now, we need to execute our camera app. We will do this by using a virtual device called
emulator which is already present in the Android Studio.
43
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:
Before moving any of the above methods we will have to take location permission.
Step 1:- Define uses permissions for location access in the manifest file
<!– To request foreground location access, declare one of these permissions. –>
<!– Required only when requesting background location access on Android 10 (API level 29) –>
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.
Output:-
44
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.
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.
This app will show us light intensity in our room with the help of a light sensor present in our phone.
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.
<RelativeLayout
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
45
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>
Go to the [Link] file and refer to the following code. Below is the code for
the [Link] file. Comments are added inside the code to understand the code in more detail.
46
19:- 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.
I. Property Animation
II. View Animation
III. 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.
Methods Description
clearAnimation() This method will clear the animation running on a specific v49iew.
47
Permissions declared in the AndroidManifest.xml file play a critical role in defining what system features the application can access. This ensures user privacy and security by preventing unauthorized access to sensitive data and device capabilities. For example, permissions like INTERNET and BLUETOOTH enable the application to connect to the internet and use Bluetooth functionality, respectively. Without declaring necessary permissions, the system would restrict the app's capability to perform certain actions, hence affecting its intended functionality. Users grant these permissions during app installation or runtime, adding another layer of user consent .
Foreground services in Android are services that actively notify users of their presence and operations via notifications; these are necessary for ongoing user-visible tasks like music playback. Background services perform operations without user interaction and are suitable for tasks like data synchronization. They minimize user awareness to enhance UX for non-critical operations. Bound services enable application components to bind to them, creating a client-server interface where components can send/receive data. This service stops once all bound components have disconnected, making it ideal for operations needing direct component interaction, such as real-time data retrieval .
Lifecycle methods in Android services such as onStartCommand() and onBind() are crucial as they dictate the service's execution and behavior. onStartCommand() triggers service execution upon an external component's startService() call, enabling continuous operation independent of the initiating component, maintaining processes like data fetching. onBind(), for bound services, handles client connections through bindService(), facilitating client-service IPC. These methods ensure services perform intended tasks efficiently, control operation length, and manage resource allocation based on current service needs, impacting overall app performance significantly .
Content providers in Android are pivotal for managing and facilitating data sharing across applications by serving as a unified interface for structured access to data. They abstract data storage methods and present a consistent API, allowing apps to perform CRUD operations on shared data. By managing permissions, content providers ensure secure data access only to authorized applications. This modular data access is beneficial for complex data types like images or contacts, where direct file access could compromise security or data integrity .
The strings.xml file simplifies organization in an Android project by providing a centralized place to store and manage all string resources used in the application. This setup avoids cluttering the code with hard-coded strings, thereby making it easier to manage translations and content modifications. By organizing strings separately, it also reduces duplication, improves maintainability, and follows the DRY (Don't Repeat Yourself) principle, keeping the project neat and manageable .
An Android application's ActionBar is a fundamental UI component that includes the App Icon, which displays the branding logo of the application; View Controls, displaying the current activity title or allowing navigation UI elements such as tabs and spinners; Action Buttons, providing quick access to essential functions; and the Action Overflow menu, containing additional actions for the app. These components foster a cohesive navigation experience, maintaining UI consistency across activities and enhancing user interaction efficiency by providing access to primary application features directly from the ActionBar .
The onCreate() method in Android is fundamental for initializing an activity since it sets up the activity's initial state. When an activity starts, onCreate() is called to perform one-time initializations such as setting the content view of the activity with setContentView(), which loads the UI layout from the XML file. Additionally, it allows developers to link UI components to their controllers using findViewById() and restore saved instance data if previously provided in onSaveInstanceState(Bundle). Thus, onCreate() establishes the groundwork for user interaction with the activity .
Understanding the distinction between services and threads in Android is crucial because they serve different roles in app execution and performance optimization. Threads are part of Java's threading model, allowing concurrent operations within the same process, enabling UI responsiveness by performing tasks such as computations or network operations asynchronously. Services, however, are designed for operations running in the background independent of UI, like downloading files, and they persist beyond the lifecycle of the activities that start them. Misusing threads as services can lead to resource leaks, while inappropriate service use can cause app inefficiencies, making this distinction key to efficient Android development .
The styles.xml file in an Android project enables customization of the application's styling by defining themes and styles that can be applied across the app's UI components. Each theme in styles.xml inherits from a parent theme, allowing developers to modify properties like primary colors, accent colors, and UI element appearances without altering default settings. This capability facilitates the creation of consistent UI aesthetics throughout the app and allows for easy UI updates by changing style attributes in one centralized file .
XML is beneficial in Android UI development because it provides a scalable and lightweight markup language to define UI layouts. It keeps UI definitions separate from application logic, which aids in maintaining a clear MVC (Model-View-Controller) architecture. XML facilitates easy manipulation of UI elements through tags, making it more manageable and less error-prone than hard-coded layouts. Furthermore, XML layouts automatically link with Java through resource identifiers, improving separation of concerns and enabling efficient UI component management .