You are on page 1of 171

5.

Activity and Multimedia with Database


• Intent :
• Android uses Intent for communicating between the components of an Application and also from one
application to another application.
• Intent are the objects which is used in android for passing the information among Activities in an Application
and from one app to another also. Intent are used for communicating between the Application components
and it also provides the connectivity between two apps.
• In Android, it is quite usual for users to witness a jump from one application to another as a part of the whole
process
• for example, searching for a location on the browser and witnessing a direct jump into Google Maps or
receiving payment links in Messages Application (SMS) and on clicking jumping to PayPal or GPay
(Google Pay).
• This process of taking users from one application to another is achieved by passing the Intent to the system.
• Intents, in general, are used for navigating among various activities within the same application, but note, is
not limited to one single application, i.e., they can be utilized from moving from one application to another as
well.
• For eg.when we click on the adds on youtube we reach to that particular app.for eg ,navigating from youtube
to Myntra app.
• Android Intent is the message that is passed between components such as activities, content providers,
broadcast receivers, services etc.
• It is generally used with startActivity() method to invoke activity, broadcast receivers etc.
• The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do
action.
• Android intents are mainly used to:
o Start the service
o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message Dial a phone call etc.
Intent Uses In Android:
Android uses Intents for facilitating communication between its components like Activities,
Services and Broadcast Receivers.

Intent for an Activity:


Every screen in Android application represents an activity. To start a new activity you need to
pass an Intent object to startActivity() method. This Intent object helps to start a new activity
and passing data to the second activity.

Intent for Services:


Services work in background of an Android application and it does not require any user
Interface. Intents could be used to start a Service that performs one-time task(for example:
Downloading some file) or for starting a Service you need to pass Intent to startService()
method.

Intent for Broadcast Receivers:


There are various message that an app receives, these messages are called as Broadcast
Receivers. (For example, a broadcast message could be initiated to intimate that the file
downloading is completed and ready to use). Android system initiates some broadcast message
on several events, such as System Reboot, Low Battery warning message etc.
Context.sendBroadcast()
Methods Description

Context.startActivity() This is to launch a new activity or get an existing activity to be action.

Context.startService() This is to start a new service or deliver instructions for an existing service.

Context.sendBroadcast() This is to deliver the message to broadcast receivers.


Types of Intents:
Intent are of two types: Explicit Intent and Implicit Intent
Explicit Intent:
• When we explicitly define which Android component should be opened on some
user action action,then we use Explicit intents.
• We generally use explicit intent to start a new component in our own app,because
we know which exact activity or service you want to start.
• For eg,we can start a new activity in response to user action or start a service to
download a file in background.
• 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.
• Explicit Intents are used to connect the application internally.
•In Explicit we use the name of component which will be affected by Intent. For Example: If
we know class name then we can navigate the app from One Activity to another activity
using Intent. In the similar way we can start a service to download a file in background
process.
• Explicit Intent work internally within an application to perform navigation and data
transfer. The below given code snippet will help you understand the concept of Explicit
Intents
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
Here SecondActivity is the JAVA class name where the activity will now be navigated.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to GFG Home Screen"
android:textAlignment="center"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn1"
android:text="Go to News Screen"
android:onClick="newsScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void newsScreen(View view) {


Intent i = new Intent(getApplicationContext(), MainActivity2.class);
startActivity(i);
}
}
Now we have to create a second activity as a destination activity. The steps to create the second activity are File >
new > Activity > Empty Activity.

Next, go to the activity_main2.xml file, which represents the UI of the project. Below is the code for
the activity_main2.xml file. Comments are added inside the code to understand the code in more detail.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">

<TextView
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to GFG News Screen"
android:textAlignment="center"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn2"
android:text="Go to Home Screen"
android:onClick="homeScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity2 extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}

public void homeScreen(View view) {


Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
Implicit intents:
• When we just want to tell what action we want to perform without worrying which
component will perform it,then we use Implicit intent.
• Implicit intents does not specify particular 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.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-
auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn"
android:text="Search"
android:onClick="search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/editText" />

</androidx.constraintlayout.widget.ConstraintLayout>
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

EditText editText;
Button button;

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = findViewById(R.id.btn);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url=editText.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
}
}
.putExtra
• If you want add information to your intent you can use this method.
• This information is represented as tuple (key, value).
• There are the number of value types that can be included into the extras of intent
(for instance, int, int[], Bundle, Parcelable, and so on).
• For each this method there is a corresponding "read" method that is used to get the
information from the intent.
• So here is a possible example how to use this. Imagine that you want explicitly call
the activity B from activity A and pass to it an array of integers:
int intArray[] = {1,2,3,4}; Intent in = new Intent(this, B.class);
in.putExtra("my_array", intArray); startActivity(in);
Intent Filter:
• Intent Filter are the components which decide the behavior of an intent. As we have read
in our previous tutorial of Intent about the navigation of one activity to another.
• Intent filters specify the type of intents that an Activity, service or Broadcast receiver can
respond to.
• It declares the functionality of its parent component (i.e. activity, services or broadcast
receiver).
• It declares the capability of any activity or services or a broadcast receiver.
Syntax of Intent Filters:
Intent filter is declared inside Manifest file for an Activity.
<!--Here Name of Activity is .MainActivity, image of icon name stored in drawable
folder, label present inside string name is label--> <!--If anything is different please
customize the code according to your app-->
<activity android:name=".MainActivity">
<intent-filter android:icon="@drawable/icon“
android:label="@string/label" >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
• icon: This is displayed as icon for activity.
You can check or save png image of name icon in drawable folder.
If icon image of any other name is stored please replace @drawable/icon with that
image name i.e. @drawable/image_name.
label: The label / title that appears at top in Toolbar of that particular Activity. You
can check or edit label name by opening String XML file present inside Values folder
(Values -> Strings). Replace @string/label to @string/yourlabel.
Intent Filter in Android Manifest Tutorial, Example And Code |
Abhi Android
Attributes of Intent Filter:
Below are the attributes of Intent filter:
1. android:icon
An icon represents the activity, service or broadcast receiver when a user interact with it or when it appears
to user in an application. To set an icon you need to give reference of drawable resource as declared
android:icon=”@drawable/icon”.
How to add custom icon in your App:
Step 1: Open your android project folder in computer / system
Step 2: Open app>> src >> main >> res >> drawable >> here save custom icon image with name

Step 3: Replace @drawable/icon with @drawable/your_image name in the below code


android:icon="@drawable/icon"
2. android:label
A label represents the title of an activity on the toolbar. You can have different Labels for different Activities as per your
requirement or choice. The label should be set as a reference to a string resource. However, you can also use a raw string
to set a label as declared in the below given code snippet
android:label = "@string/label"
or
android:label = "New Activity"
How To Create Custom Label in App:
Step 1: Click on values values
Step 2: Open Strings.xml file present inside values
Step 3: Edit String value to your custom name. For example, we put AbhiAndroid.
Step 4: Now run the App and you will see your custom name in Toolbar. Below you can see
AbhiAndroid printed.

Just like icon attribute, if you have not declared any label for your activity then it will be same as
your parent activity. However if you haven’t declared any label to parent activity then label is set by
<application> element’ label attribute.
Below is sample code of Intent filter for an App having two
activity:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<!--Add code here for first activity-->
</intent-filter>
</activity>
<activity android:name=".Main2Activity">
<intent-filter>
<!--Add code here for second activity-->
</intent-filter>
</activity>
</application>
Elements In Intent Filter:
There are following three elements in an intent filter:
1.Action
2.Data
3.Category
Important Note: Every intent filter must contain action element in it. Data and category element is optional for
it.
1. Action:
It represent an activities action, what an activity is going to do. It is declared with the name attribute as given
below
<action android:name = "string" />
An Intent Filter element must contain one or more action element. Action is a string that specifies the action to
perform. You can declare your own action as given below. But we usually use action constants defined by Intent
class.
<intent-filter> <action android:name="com.example.android.intentfilters.Main2Activity"/> </intent-filter>
There are few common actions for starting an activity like ACTION_VIEW
ACTION_VIEW: This is used in an Intent with startActivity(). This helps when you redirect to see any
website, photos in gallery app or an address to view in a map app.
For example: As we have done in previous topic of Intent, we started a website using implicit intent in that
Intent we used ACTION_VIEW element to view website in the web browser.
Intent intentObj = new Intent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.abhiandroid.com"));
startActivity(intentObj);
There are more actions similar to above like, ACTION_SEND, ACTION_MAIN,
ACTION_WEB_SEARCH and many more.
2. Data:
There are two forms in which you can pass the data, using URI(Uniform Resource Identifiers) or MIME type
of data. For understanding the concept of URI in better manner check the link.
The syntax of data attribute is as follows:
<data
android:scheme="string"
android:host="string"
android:port="string"
android:path="string“
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />
This specifies the format of data associated with an Intent which you use with component. As explained in
above code snippet, data passed through Intent is a type of URI. Check the below given table for better
clarification
ACTION DATA MEANING

Intent.ACTION_CALL tel:phone_number Opens phone application and calls phone number

Opens phone application and dials (but doesn’t call)


Intent.ACTION_DIAL tel:phone_number
phone_number

Opens phone application and dials (but doesn’t call) the voice
Intent.ACTION_DIAL voicemail:
mail number.

Intent.ACTION_VIEW geo:lat,long Opens the maps Application centered on (lat, long).

Intent.ACTION_VIEW geo:0,0?q=address Opens the maps application centered on the specified address.

http://url
Intent.ACTION_VIEW Opens the browser application to the specified address.
https://url

Intent.ACTION_WEB_SEARC Opens the browser application and uses Google search for
plain_text
H given string
3. Category:
This attribute of Intent filter dictates the behavior or nature of an Intent. There is a string which contains
some additional information about the intent which will be handled by a component. The syntax of category
is as follows:
<category android:name="string" />
Most of Intents do not require a category for example: CATEGORY_BROWSABLE,
CATEGORY_LAUNCHER.
BROWSABLE – Browsable category, activity allows itself to be opened with web browser to open the
reference link provided in data.
LAUNCHER – Launcher category puts an activity on the top of stack, whenever application will start, the
activity containing this category will be opened first.
<intent-filter>
<!--Code here-->
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<!--Code here-->
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
Activity Lifecycle:
In Android, an activity is referred to as one screen in an application. It is very similar to a single
window of any desktop application. An Android app consists of one or more screens or activities.
Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when a
new activity starts, the previous one always remains below it. There are four stages of an activity.
1.If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or
running. This is usually the activity that the user is currently interacting with.
2.If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your
activity. In such a case either another activity has a higher position in multi-window mode or the activity
itself is not focusable in the current window mode. Such activity is completely alive.
3.If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the
information, and as its window is hidden thus it will often be killed by the system when memory is needed
elsewhere.
4.The system can destroy the activity from memory by either asking it to finish or simply killing its process.
When it is displayed again to the user, it must be completely restarted and restored to its previous state.
For each stage, android provides us with a set of 7 methods that have their own significance for each stage in
the life cycle. The image shows a path of migration whenever an app switches from one state to another.
Activity Lifecycle:
Method Description
onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the


user.
onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.


onCreate( Whenever an Activity starts running, the first method to get executed
) is onCreate(). This method is executed only once during the lifetime. If
we have any instance variables in the Activity, the initialization of those
variables can be done in this method. After onCreate() method,
the onStart() method is executed.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
onStart() During the execution of onStart() method, the
Activity is not yet rendered on screen but is
about to become visible to the user. In this
method, we can perform any operation related to
UI components.

@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
onResume() When the Activity finally gets rendered on the
screen, onResume() method is invoked. At this
point, the Activity is in the active state and is
interacting with the user.
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
onPause() If the activity loses its focus and is only
partially visible to the user, it enters the
paused state. During this transition,
the onPause() method is invoked. In
the onPause() method, we may commit
database transactions or perform light-weight
processing before the Activity goes to the
background.
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
onStop() From the active state, if we hit the Home key, the Activity goes to the
background and the Home Screen of the device is made visible. During this
event, the Activity enters the stopped state.
Both onPause() and onStop() methods are executed.
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}

onDestroy() When an activity is destroyed by a user or Android


system, onDestroy() function is called.
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.activitylifecycle.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
package example.javatpoint.com.activitylifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
You will not see any output on the emulator or device. You need to open logcat.
Broadcast Receivers:
• Receiver has a limited and defined life cycle.
• Only onReceive() method is called in BroadcastReciver’s life cycle. A BroadcastReciever
life cycle ends (ie stop receiving broadcast) when you unregister it. usually you would do
this in the onPause/onStop method.Source: A broadcast receiver has callback method:
void onReceive(Context curContext, Intent broadcastMsg)
• When a broadcast message arrives for the receiver, Android calls its onReceive() method
and passes it the Intent object containing the message. The broadcast receiver is
considered to be active only while it is executing this method. When onReceive() returns,
it is inactive.
• Broadcast Receivers simply respond to broadcast messages from other applications or from the system
itself. These messages are sometime called events or intents.
• For example, applications can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this is broadcast receiver who will
intercept this communication and will initiate appropriate action.
• There are following two important steps to make BroadcastReceiver works for the system broadcasted
intents −
1. Creating the Broadcast Receiver.
2. Registering Broadcast Receiver
• There are mainly two types of Broadcast Receivers:
1. Static Broadcast Receivers: These types of Receivers are declared in the manifest file and works even
if the app is closed.
2. Dynamic Broadcast Receivers: These types of receivers work only if the app is active or minimized.
• Process associated with Broadcast Receivers have the following life cycle:
• Current process executing Broadcast Receiver is foreground process.It is not killed
by System unless it is under immense scarcity of resources.
• In case of processes ,which are never used by user or the one which is recently not
in use,is Considered an empty process.And an empty process can be killed by
anytime.
• Once onReceive(Context,Intent) returns,broadcast receiver becomes inactive and
hence it has No special priority over the other application components.
1. Creating the Broadcast Receiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the
onReceive() method where each message is received as a Intent object parameter.
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
2. Registering Broadcast Receiver
An application listens for specific broadcast intents by registering a broadcast receiver
in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated
event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has
completed the boot process.
Broadcast-Receiver
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
Now whenever your Android device gets booted, it will be intercepted by
BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be executed.
Sr.No Event Constant & Description
android.intent.action.BATTERY_CHANGED
1 broadcast containing the charging state, level, and other information about the battery.
android.intent.action.BATTERY_LOW
2
Indicates low battery condition on the device.
android.intent.action.BATTERY_OKAY
3 Indicates the battery is now okay after being low.
android.intent.action.BOOT_COMPLETED
4 This is broadcast once, after the system has finished booting.
android.intent.action.BUG_REPORT
5
Show activity for reporting a bug.
android.intent.action.CALL
6 Perform a call to someone specified by the data.
android.intent.action.CALL_BUTTON
7 The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call.
android.intent.action.DATE_CHANGED
8 The date has changed.
android.intent.action.REBOOT
9 Have the device reboot.
Broadcasting Custom Intents:
If you want your application itself should generate and send custom intents then you will have to create and
send those intents by using the sendBroadcast() method inside your activity class. If you use
the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around
after the broadcast is complete.
public void broadcastIntent(View view) {
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent); }
This intent com.tutorialspoint.CUSTOM_INTENT can also be registered in similar way as we have regsitered system
generated intent.
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
Go to the activity_main.xml file and refer to the following code. Below is the code for
the activity_main.xml file.

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
Below is the code for the MainActivity file.

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

AirplaneModeChangeReceiver airplaneModeChangeReceiver = new AirplaneModeChangeReceiver();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airplaneModeChangeReceiver, filter);
}

@Override
protected void onStop() {
super.onStop();
unregisterReceiver(airplaneModeChangeReceiver);
}
}
Go to app > java > your package name(in which the MainActicity is present) > right-click > New > Kotlin
File/Class and name the files as AirplaneModeChangeReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.widget.Toast;

public class AirplaneModeChangeReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {

if (isAirplaneModeOn(context.getApplicationContext())) {
Toast.makeText(context, "AirPlane mode is on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "AirPlane mode is off", Toast.LENGTH_SHORT).show();
}
}
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
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.
Structure of a Content URI: content://authority/optionalPath/optionalID
• Details of different parts of Content URI:
1. content:// – Mandatory part of the URI as it represents that the given URI is a Content URI.
2. authority – Signifies the name of the content provider like contacts, browser, etc. This part must be
unique for every content provider.
3. 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.
4. 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.
Abstract
Method Description

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

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


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

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


update() It returns the number of rows updated.

This method is used to delete the existing rows.


delete() It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail Extension(MIME)


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

As the content provider is created, the android system calls


onCreate() this method immediately to initialise the provider.
Fragments:
• In Android, Fragment is a part of an activity which enable more modular activity design.
• It will not be wrong if we say a fragment is a kind of sub-activity.
• It represents a behaviour or a portion of user interface in an Activity.
• We can combine multiple Fragments in Single Activity to build a multi panel UI and
reuse a Fragment in multiple Activities.
• Fragments simplify the reuse of components in different layouts.
• You can also use fragments also to support different layouts for landscape and portrait
orientation on a smartphone.
• We can create Fragments by extending Fragment class or by inserting a Fragment into
our Activity layout by declaring the Fragment in the activity’s layout file, as
a <fragment> element. We can manipulate each Fragment independently, such as add or
• Need Of Fragments In Android:
Before the introduction of Fragment’s we can only show a single Activity on the screen at one given point of
time so we were not able to divide the screen and control different parts separately. With the help of
Fragment’s we can divide the screens in different parts and controls different parts separately.
By using Fragments we can comprise multiple Fragments in a single Activity. Fragments have their own
events, layouts and complete life cycle. It provide flexibility and also removed the limitation of single Activity
on the screen at a time.
Basic Fragment Code In XML:
<fragment
android:id="@+id/fragments"
android:layout_width="match_parent"
android:layout_height="match_parent" />
• Implementation of Fragment In Android Require Honeycomb (3.0) or Later:
Fragments were added in in Honeycomb version of Android i.e API version 11. There are some primary
classes related to Fragment’s are:
1. FragmentActivity: The base class for all activities using compatibility based Fragment (and loader)
features.
2. Fragment: The base class for all Fragment definitions
3. FragmentManager: The class for interacting with Fragment objects inside an activity
4. FragmentTransaction: The class for performing an atomic set of Fragment operations such as Replace or
Add a Fragment.
Create A Fragment Class In Android Studio:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate
the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}

}
Implementation of Fragment In Android Require Honeycomb (3.0) or Later:
Fragments were added in in Honeycomb version of Android i.e API version 11. There are some primary
classes related to Fragment’s are:
1. FragmentActivity: The base class for all activities using compatibility based Fragment (and loader)
features.
2. Fragment: The base class for all Fragment definitions
3. FragmentManager: The class for interacting with Fragment objects inside an activity
4. FragmentTransaction: The class for performing set of Fragment operations such as Replace or Add a
Fragment.
• Open res -> layout ->activity_main.xml (or) main.xml and add following code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent“
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<!-- display two Button's and a FrameLayout to replace the Fragment's -->
<Button android:id="@+id/firstFragment" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/button_background_color“
android:text="First Fragment"
android:textColor="@color/white"
android:textSize="20sp" />
<Button android:id="@+id/secondFragment"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="@color/button_background_color" android:text="Second
Fragment"
android:textColor="@color/white“
android:textSize="20sp" />
<FrameLayout android:id="@+id/frameLayout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:layout_marginTop="10dp" />
</LinearLayout>
Open src -> package -> MainActivity.java

package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button firstFragment, secondFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // get the reference of Button's
firstFragment = (Button) findViewById(R.id.firstFragment);
secondFragment = (Button) findViewById(R.id.secondFragment);
// perform setOnClickListener event on First Button
firstFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { // load First Fragment
loadFragment(new FirstFragment()); }
});
secondFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { // load Second Fragment loadFragment
(new SecondFragment()); }
});
} private void loadFragment(Fragment fragment) {
FragmentManager fm = getFragmentManager(); // create a FragmentTransaction to begin the
transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction(); // replace the
FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout,fragment); fragmentTransaction.commit(); //
save the changes
}
}
Now we need 2 fragments and 2 xml layouts. So create two fragments by right click on your package folder and create
classes and name them as FirstFragment and SecondFragment and add the following code respectively.
• FirstFragment.class

package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class FirstFragment extends Fragment {
View view;
Button firstButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_first, container, false);
firstButton = (Button) view.findViewById(R.id.firstButton);
firstButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "First Fragment", Toast.LENGTH_LONG).show();
} });
return view;
}
}
SecondFragment.class
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class SecondFragment extends Fragment {
View view;
Button secondButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_second, container, false);
secondButton = (Button) view.findViewById(R.id.secondButton);
secondButton.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Toast.makeText(getActivity(), "Second Fragment", Toast.LENGTH_LONG).show(); }
});
return view;
}}
fragment_first.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.abhiandroid.fragmentexample.FirstFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is First Fragment“
android:textColor="@color/black"
android:textSize="25sp" />
<Button
android:id="@+id/firstButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@color/green"
android:text="First Fragment"
android:textColor="@color/white"
android:textSize="20sp"
android:textStyle="bold" /> </RelativeLayout>
fragment_second.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.abhiandroid.fragmentexample.SecondFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is Second Fragment"
android:textColor="@color/black"
android:textSize="25sp" />
<Button
android:id="@+id/secondButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@color/green" android:text="Second
Fragment" android:textColor="@color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
Open res ->values ->colors.xml
In this step we define the color’s that used in our xml file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- color's used in our project -->
<color name="black">#000</color>
<color name="green">#0f0</color>
<color name="white">#fff</color>
<color name="button_background_color">#925
</color> </resources>
Now run the App and you will two button. Clicking on first button shows First Fragment and on click
of Second Button shows the Second Fragment which is actually replacing layout(FrameLayout).
• 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.
• Android Service Life Cycle:
In android, the life cycle of service will follow two different paths Started or Bound.
 Started Service:
• A service is Started when an application component, such as an activity calls startService() method.
• Once it started, it will run indefinitely in background even if the component that started is destroyed.
• We can stop the Started service by using stopService() method or the service can stop itself by
calling stopSelf() method.
• In android, the Started service component will perform a single operation and it won’t return any
result to the caller.
 Bound Service:
• A service is Bound when another application component calls bindService() method.
• The bound service runs as long as another application component is bound to it.
• We can unbind the service by calling unbindService() method based on our requirements.
• In android, we can bind multiple components to a single service at once, but the service will be
destroyed in case all the components unbind.
Android Services Lifecycle Diagram:
Following diagram shows the lifecycle of Started service, when the service created with startService() and
the lifecycle of Bound service, when the service created with bindService().
Android Service Callback Methods
During the service implementation, following are the callback methods that we need to override in
android application.

onStartCommand()

The system will invoke this method when another component such as an activity requests the
service to be started by calling startService(). When this method executed, the service will start
and run indefinitely in background. If we implement this in our code, it’s our responsibility to stop
the service once code execution is done by calling stopSelf() or stopService() methods. In case, if
we want to provide only binding, then we don’t need to implement this method.
In android, onStartCommand() method must return an integer and the integer is a value that
describes how the system will continue the service in the event that the system kills it.

onBind()

The system will invoke this method when another component wants to bind with the service by
calling bindService(). During implementation of this method, we must need to provide an interface
to the clients to communicate with the service by returning an IBinder object. In android, we must
need to implement this method, in case if we don’t need to allow binding, then we should return
NULL.
onCreate()

The system will invoke this method when the service is created initially
using onStartCommand() or onBind() methods to do one-time setup procedures. In case, if the
service is already running, then this method will not call.

onDestroy()

The system will invoke this method when the service is no longer used and is being destroyed.
This is the final call that the service will receive and we need to implement this method in our
service to clean up any unused resources such as threads, receivers or listeners.

Generally, in android if we start a service by calling startService() method, the service will run
continuously even if the component that started service is destroyed until we stop it by
using stopService() or it stops itself with stopSelf().

Same way, if we create a service by calling bindService() method, the service will runs as long as
the component is bound to it. After the service is unbound from all of its clients, the system will
destroy it.

In android, the service life cycle is having a set of callback methods that need to be implemented
to keep a track of services status and to execute the required things in appropriate-time.
• Android Architecture:
refer 1st chapter
Multimedia Framework:
• Android Multimedia
Architecture:

• Media applications interact with the


Android native multimedia
framework according to the
following architecture.
• Android includes Stagefright, a media playback engine at the native level that has built-in
software-based codecs for popular media formats.
• Stagefright audio and video playback features include integration with OpenMAX codecs,
session management, time-synchronized rendering, transport control, and DRM.
• Stagefright also supports integration with custom hardware codecs provided by you. To set
a hardware path to encode and decode media, you must implement a hardware-based codec
as an OpenMax IL (Integration Layer) component.
• Application Framework
At the application framework level is application code that utilizes android.media APIs to
interact with the multimedia hardware.
• Binder IPC
The Binder IPC proxies facilitate communication over process boundaries. They are
located in the frameworks/av/media/libmedia directory and begin with the letter "I".
• Native Multimedia Framework
At the native level, Android provides a multimedia framework that utilizes the Stagefright
engine for audio and video recording and playback. Stagefright comes with a default list of
supported software codecs and you can implement your own hardware codec by using the
OpenMax integration layer standard. For more implementation details, see the MediaPlayer
and Stagefright components located in frameworks/av/media.
• OpenMAX Integration Layer (IL)
The OpenMAX IL provides a standardized way for Stagefright to recognize and use
custom hardware-based multimedia codecs called components. You must provide an
OpenMAX plugin in the form of a shared library named libstagefrighthw.so. This plugin
links Stagefright with your custom codec components, which must be implemented
according to the OpenMAX IL component standard.
Playing Audio and Video Files:
• 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
• The Android multimedia framework includes support for playing variety of common
media types, so that you can easily integrate audio, video and images into your
applications.
• You can play audio or video from media files stored in your
 application’s resources (raw resources),
 from standalone files in the filesystem,
 or from a data stream arriving over a network connection, all using MediaPlayer APIs.”
• In other words, you can actually use it to play media files such as videos and images.
In Android for recording audio or video, there is a built-in class called MediaRecorder.
This class in Android helps to easily record video and audio files. The Android multimedia
framework provides built-in support for capturing and encoding common audio and video
formats. In android for recording audio, we will use a device microphone along
with MediaRecorder Class and for recording video, we will use the user’s device Camera
and MediaRecorder Class.
Important Methods of MediaRecorder Class

Method Description

setAudioSource() This method will specify the source of the audio to be recorded.

setAudioEncoder() This method is used to specify the audio encoder.

setOutputFormat() This method is used to specify the output format of our audio.

This method is used to specify the path of recorded audio files that are
setOutputFile()
to be stored.

stop() This method is used to stop the recording process.

start() This method is used to start the recording process.

This method is used to release the resource that is associated with the
release()
Media recorder class.
• Playing Audio Files:
• Many apps require the feature to add the audio feature in their application and there so
many audio files that we have to play inside our application. If we will store so many
audio files inside our application, then it will increase the size of the app and this may
reduce the user base due to the huge app size. So the better way to tackle this problem is
to store the audio files in your database and access them from their unique web URL.
Playing video files in Android:
By the help of MediaController and VideoView classes, we can play the video files in android
.
Playing Audio Files
Media Player is the most widely used class for playing media files.
Media Player has been designed to play large audio files and streams also supporting
playback operations like stop, start, pause etc and seeking operations.
It also supports listeners related to the media operations.
Playing of audio and video in MediaPlayer can be done through the following ways:
■ Playing from raw resource.
Playing from file-system.
■ Playing from stream.

Playing Audio from resourse


This is the most common way of playing audio files.
In this case the audio file should be present in the raw or assets folder of the project
https://www.geeksforgeeks.org/how-to-add-audio-files-to-android-app-in-
android-studio/
Playing Audio from file-system
SoundPool Class load (String path, int priority) method is used to load the audio file
from raw folder. If you want to load a sound from the raw resource file "bigwave.mp3",
you would specify "R.raw.bigwave" as the resource ID. This returns the integer
SoundID that can be use to play the sound.
ToneGenerator or Stream
. This class provides methods to play DTMF tones, call supervisory tones and
proprietary tones. . The ToneGenerator object requires an output stream type and
volume. startTone() is used to play the tone. startTone() method starts the playback of a
tone of the specified type for the specified duration.
//Output Stream Type and Volume
ToneGenerator tg=new
ToneGenerator(AudioManager.STREAM_RING, 100);
//Play Tone
tg.startTone (ToneGenerator.TONE_CDMA_ABBR_ALERT);
Playing Video Files
Android provides a specialized view control study.widget.
• Video View that encapsulates initializing the MediaPlayer.
creating and
. The VideoView class can load images from various sources (such as resources or content
providers), and takes care of computing its measurement from the video so that it can be
used in any layout manager, also providing various display options such as scaling and
tinting.
• VideoView can be used to display video files present in SDCard FileSystem or files present
online.
MediaPlayer class provides a different type of methods to control audio and video files based
File: activity_main.xml
<RelativeLayout xmlns:androclass="http://
schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<VideoView
android:id="@+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />

</RelativeLayout>
File: MainActivity.java
package com.example.video1;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {


VideoView videoView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

videoView =findViewById(R.id.videoView1);

//Creating MediaController
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
//specify the location of media file
Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/media/1.mp4");

//Setting MediaController and URI, then starting the videoView


videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}
Eg.2
Add the following code to res/layout/activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="8dp"
tools:context=".MainActivity">
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</VideoView>
</LinearLayout>
Step 3 − Create a new android resource folder(raw) and copy-paste your video file in that folder.
Step 4 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = findViewById(R.id.videoView);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback)); videoView.start();
}}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<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" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

https://www.tutorialspoint.com/how-to-play-videos-in-android-from-assets-folder-or-raw-folder
• Text to Speech:
• Text to speech is becoming an integral part of many content driven mobile APP’s.
If your APP is a tutorial , then it is high time you think about Text-To-Speech (TTS)
feature to it.
• Voice input based command and text to speech is a trend now. In this tutorial, we will
explore how Text-To-Speech (TTS)" feature can be implemented in an Android APP.
• Text to speech (TTS) makes an android device read the text and convert it to audio out
via the speaker. Android TTS supports multiple languages. .
• TTS is a simple but powerful feature.
• It can also be effectively used in mobile Apps dedicated to visually impaired people or
educational app for kids.
• Using TextToSpeech enhances interaction between the user and the mobile application.
• .Android TTS was available from version 1.6.
• It has features to control speed, pitch of speech as well as type of languageTextToSpeech
needs to be initialized first.
• For this, need to implement the TextToSpeech. OnInitListener interface and override the
method : onInit.
Text to Speech App converts the text written on the screen to speech like you have written “Hello World” on the screen
and when you press the button it will speak “Hello World”. Text-to-speech is commonly used as an accessibility feature to
help people who have trouble reading on-screen text, but it’s also convenient for those who want to be read too. This
feature has come out to be a very common and useful feature for the users.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
android:layout_margin="30dp"
tools:context=".MainActivity">

<!--To add text in the app-->


<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Text"
android:layout_marginBottom="20dp"
android:hint="Enter Any Sentence"
android:gravity="center"
android:textSize="16dp"/>
<!--when you press this button it will
convert text into speech-->
<Button
android:layout_width="wrap_content"
android:id="@+id/btnText"
android:layout_height="wrap_content"
android:text="Click Here"
android:layout_gravity="center"/>

<!--To display the name of GeeksForGeeks -->


<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:gravity="center_horizontal"
android:text="GEEKSFORGEEKS"
android:textColor="@android:color/
holo_green_dark"
android:textSize="36sp" />

</LinearLayout>
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

EditText Text;
Button btnText;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Text = findViewById(R.id.Text);
btnText = findViewById(R.id.btnText);
// create an object textToSpeech and adding features into it
textToSpeech = new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {

// if No error is found then only it will run


if(i!=TextToSpeech.ERROR){
// To Choose language of speech
textToSpeech.setLanguage(Locale.UK);
}
}
});

// Adding OnClickListener
btnText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

textToSpeech.speak(Text.getText().toString(),TextToSpeech.QUEUE_FLUSH,null);
}
});

}
}
https://www.geeksforgeeks.org/how-to-convert-text-to-
speech-in-android/
• Sensors:
• 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.
• 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.
• 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:
1.SensorManager Class: Sensor manager is used to accessing various
sensors present in the device.
2.Sensor Class: The sensor class is used to get information about the sensor
such as sensor name, sensor type, sensor resolution, sensor type, etc.
3.SensorEvent class: This class is used to find information about the sensor.
4.SensorEventListener interface: This is used to perform some action when
sensor accuracy changes.

https://www.javatpoint.com/android-sensor-example
• AsyncTasks
• AsyncTask is an abstract class in Android that offers us the freedom to execute
demanding tasks in the background while keeping the UI thread light and the
application responsive.
• When launched, an Android application operates in a single thread. Due to this
single-thread approach, tasks that take a long time to fetch a response may cause the
program to become unresponsive.
• We use Android AsyncTask to perform these heavy tasks in the background on a
separate thread and return the results back to the UI thread in order to prevent this.
• In Android, AsyncTask (Asynchronous Task) allows us to run the instruction in the
background and then synchronize again with our main thread.
• As a result, the UI thread is always responsive when AsyncTask is used in an
Android application.
• AsyncTask is not intended to be a general-purpose threading system; rather, it is
intended to be a helper class for Thread and Handler
AsyncTask (Asynchronous Task) in Android is an abstract class, or rather a
helper class that lets the application perform tedious tasks in the background and
parallelly perform UI changes in the front-end.
Background tasks such as loading images, downloading music, pictures, files, etc
can be performed using AsyncTask.
Need of AsyncTask In Android:
• By default, our application code runs in our main thread and every statement is therefore
execute in a sequence.

• If we need to perform long tasks/operations then our main thread is blocked until the
corresponding operation has finished.
• For providing a good user experience in our application we need to use AsyncTasks
class that runs in a separate thread.
• This class will executes everything in doInBackground() method inside of other thread
which doesn’t have access to the GUI where all the views are present.
• The onPostExecute() method of this class synchronizes itself again with the main UI
thread and allows it to make some updating. This method is called automatically after
the doInBackground method finished its work.
Asynchronous tasks are divided into three generic types: Params, Progress,
& Result and
four steps: onPreExecute, doInBackground, onProgressUpdate, &
onPostExecute. The following lists the three generic types utilized in an
Android AsyncTask class:
•Params: Parameters sent to the task upon execution
•Progress: Progress units shared during the background computation
•Result: Result obtained from the background computation
Method of AsyncTask In Android:
In Android, AsyncTask is executed and goes through four different steps or method.
Here are these four methods of AsyncTasks.
1. onPreExecute() – It invoked on the main UI thread before the task is executed.
This method is mainly used to setup the task for instance by showing a ProgressBar
or ProgressDialog in the UI(user interface).
2. doInBackground(Params) – This method is invoked on the background thread
immediately after onPreExecute() finishes its execution.
Main purpose of this method is to perform the background operations that can take a
long time.
The parameters of the Asynchronous task are passed to this step for execution. The
result of the operations must be returned by this step and it will be passed back to the
last step/method i.e onPostExecutes(). This method can also use
publishProgress(Progress…) to publish one or more units of progress. These values
will be published on the main UI thread in the onProgressUpdate(Progress…)
method.
3. onProgressUpdate(Progress…) – This method is invoked on the main UI thread after a
call to publishProgress(Progress…). Timing of the execution is undefined. This method is
used to display any form of progress in the user interface while the background operations
are executing. We can also update our progress status for good user experience.
4. onPostExecute(Result) – This method is invoked on the main UI thread after the
background operation finishes in the doInBackground method. The result of the
background operation is passed to this step as a parameter and then we can easily update
our UI to show the results.
The following definitions outline the fundamental methods used in an Android
AsyncTask class:
•doInBackground():
•The code that has to be run in the background is contained in the doInBackground()
method. The publishProgress() method in this method allows us to repeatedly deliver
results to the UI thread. We only need to use the return statements to signal that the
background processing has been finished.
•onPreExecute():
•The code that runs prior to the beginning of the background processing is contained in
this function.
•onPostExecute():
•After the doInBackground method has finished processing, the onPostExecute() method
is called. This method receives the output of the doInBackground method as its input.
•onProgressUpdate():
•This method can use the progress updates it receives from the publishProgress method,
which publishes progress updates from the doInBackground function, to update the UI
thread.
Methods of AsyncTask
•onPreExecute() − Before doing background operation we should show something on
screen like progressbar or any animation to user. we can directly comminicate
background operation using on doInBackground() but for the best practice, we should
call all asyncTask methods .
•doInBackground(Params) − In this method we have to do background operation on
background thread. Operations in this method should not touch on any mainthread
activities or fragments.
•onProgressUpdate(Progress…) − While doing background operation, if you want to
update some information on UI, we can use this method.
•onPostExecute(Result) − In this method we can update ui of background operation
result.
Syntax of AsyncTask class:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls)
{
// code that will run in the background
return ;
}
protected void onProgressUpdate(Integer... progress)
{
// receive progress updates from doInBackground
} protected void onPostExecute(Long result)
{
// update the UI after background processes completes
}
}
https://www.tutorialspoint.com/android-asynctask-example-and-explanation
• Camera:
In Android, Camera is a hardware device that allows capturing pictures and videos in your
applications.
The Android framework provides the facility of working with Camera in two ways:
1.By using existing camera application
2.By using Camera Api

#1 Using Camera By Using Camera Application


We can capture pictures without using the instance of Camera class. Here you will use an
intent action type of MediaStore.ACTION_IMAGE_CAPTURE to launch an existing
Camera application on your phone. In Android MediaStore is a type of DataBase which
stores pictures and videos in android.
Intent cameraIntent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
#2 Using Camera By using Camera Api
This class is used for controlling device cameras. It can be used to take pictures when you are
building a camera application.

Camera API works in following ways:


1.Camera Manager: This is used to get all the cameras available in the device like front
camera back camera each having the camera id.
2.CameraDevice: You can get it from Camera Manager class by its id.
3.CaptureRequest: You can create a capture request from camera device to capture images.
4.CameraCaptureSession: To get capture request’s from Camera Device create a
CameraCaptureSession.
5.CameraCaptureSession.CaptureCallback: This is going to provide the Capture session
results.
Camera Permission Declarations In Manifest
First, you should declare the Camera requirement in your Manifest file if Camera is
compulsory for your application and you don’t want your application to be installed on
a device that does not support Camera.
Before you start development on your application you have to make sure that your
Manifest has appropriate declarations in it that will allow you to use Camera feature in
your Application.
<uses-permission android:name="android.permission.CAMERA"/>
Bluetooth
Among many ways, Bluetooth is a way to send or receive data between two different devices. Android
platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data
with other Bluetooth devices.
Android provides Bluetooth API to perform these different operations.
•Scan for other Bluetooth devices
•Get a list of paired devices
•Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling
by calling the static method getDefaultAdapter(). Its syntax is given below.
private BluetoothAdapter BA; BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant
ACTION_REQUEST_ENABLE. Its syntax is.

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);


startActivityForResult(turnOn, 0);

Apart from this constant, there are other constants provided the API , that supports different tasks. They are
listed below.

Sr.No Constant & description


ACTION_REQUEST_DISCOVERABLE
1 This constant is used for turn on discovering of bluetooth

ACTION_STATE_CHANGED
2 This constant will notify that Bluetooth state has been changed

ACTION_FOUND
3 This constant is used for receiving information about each device that is
discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.

private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();

Apart form the parried Devices , there are other methods in the API that gives more
control over Blueetooth. They are listed below.
Sr.N Method & description
o
enable()
1
This method enables the adapter if not enabled
isEnabled()
2
This method returns true if adapter is enabled
disable()
3
This method disables the adapter
getName()
4
This method returns the name of the Bluetooth adapter
setName(String name)
5
This method changes the Bluetooth name
getState()
6 This method returns the current state of the Bluetooth Adapter.
startDiscovery()
7 This method starts the discovery process of the Bluetooth for 120
seconds.
https://www.tutorialspoint.com/android/
android_bluetooth.htm
Audio Recorder
Recording is one of the most useful feature in android mobile phones because with the
use of this feature android application users can easily record their voices as audio notes
and play them whenever they want to.
In android, MediaRecorder class will provide a functionality to record audio or video
files.

The android multimedia framework provides built-in support for capturing and
encoding a variety of common audio and video formats. We have a multiple ways to
record audio or video but by using MediaRecorder class we can easily implement
audio or video rec
Android Set Permissions to Record Audio
To record an audio and save it in device, our app must tell the user that it will access the
device’s audio input and storage, for that we need to set multiple permissions such
as RECORD_AUDIO, STORAGE and WRITE_EXTERNAL_STORAGE in our
manifest file.
Following is the code snippet of defining the permissions in android manifest file to record audio and
save it in device.

<manifest ... >


<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.STORAGE"/>
...
</manifest>
• To use MediaRecord class to record an audio, we need to create an instance of MediaRecorder class
and set the source, output, encoding format and output file to store the recorded audio in device. After
that we need to call prepare(), start(), stop(), etc. to start the audio recording in our application.
• Apart from above methods, MediaRecorder class provides a different type of methods to control audio
and video recording based on requirements.
Method Description
setAudioSource() It is used to specify the source of audio to be recorded.
setVideoSource() It is used to specify the source of the video to be recorded.

setOutputFormat() It is used to specify the audio / video output format.


setAudioEncoder() It is used to specify the audio encoder.
setVideoEncoder() it is used to specify the video encoder.
setOutputFile() It is used to specify the path of a recorded audio/video files to
be stored.
stop() It is used to stop the recording process.
start() it is used to start the recording process.
release() It is used to releases the resources which are associated with
MediaRecorder object.
https://www.tutlane.com/tutorial/android/
android-audio-recorder-with-examples
Animation:
• Animation API was introduced by Google in Android 3.0 which gives us the
flexibility to change object properties over a certain time interval.
• The Animations Framework allows us to create visually attractive animations and
transitions in our apps. Using the animations, one can turn their good looking app into
an excellent and highly usable app.
• Animations are useful when the screen changes state, i.e when the content loads or new
actions become available.
• Animation is the process of creating motion and shape change.
• Animations notify users about what’s going on in your app and improve model of your
app’s interface.
• Android Defines Three Types Of Animations:
• View Animation:
• This is the simplest animation used in Android. It define the properties of our Views
that should be animated using a technique called Tween Animation.
• It take the following parameters i.e. size, time duration , rotation angle, start value ,
end value, and perform the required animation on that object.
• You can execute the animation by specifying transformations on your View. This can
be done in XML resource files or programmatically.
• Android View animation can make animation on any View objects, such as
ImageView, TextView or Button objects.
• View animation can only animate simple properties like position, size, rotation, and
the alpha property that allows you animate the transparency of a View.
• The drawback of this mechanism is that it can only be applied to Views.
Property Animation:
• This animation was introduced in Android 3.0 (API level 11).
• It allows the user to animate anything.
• Property animations are highly customizable, you can specify the duration, the number of repeats, the
type of interpolation, and the frame rate of the animation. The Property Animation system is always
preferred for more complex animations.
• Property animations allow us to animate any property of any object from one value to another over a
specified duration.
• Let us take an example, imagine you wanted to animate the 3d rotation using the rotationX or
rotationY properties that were introduced in API 11. Or maybe you want to animate a color change or
animate the change of a drawable. This is not possible by using View Animations. For this purpose
Property Animation is used .
Property Description
alpha Fade in or out
rotation, rotationX, rotationY Spin or flip
scaleX ,scaleY Grow or shrink
x,y,z Position
translationX, translationY, translationZ (API 21+) Offset from Position
Drawable Animation:
This animation allows the user to load drawable resources and display them one frame
after another. This method of animation is useful when user wants to animate things that
are easier to represent with Drawable resources.

https://abhiandroid.com/materialdesign/animation
SQLite Database:

SQLite is an open-source relational database that is used to perform database operations on


android devices such as storing, manipulating, or retrieving persistent data from the
database.
Android comes in with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you
don't need to establish any kind of connections for it like JDBC, ODBC etc.
SQLite is a open source SQL database that stores data to a text file on a device. Android
comes in with built in SQLite database implementation. SQLite supports all the relational
database features. In order to access this database, you don't need to establish any kind of
connections for it like JDBC,ODBC e.t.c.
• Android SQLite is a very lightweight database which comes with Android OS.
• Android SQLite combines a clean SQL interface with a very small memory footprint and
decent speed.
•SQLite is used as a database for android application development.
Database - Creation
In order to create a database you just need to call this method open Or Create Database
with your database name and mode as a parameter. It returns an instance of SQLite
database which you have to receive in your own object. Its syntax is given below

SQLiteDatabase mydatabase =openOrCreateDatabase ("your database


MODE_PRIVATE,null);

Role of SQLite Database in Android


SQLite is an open source and lightweight database administration system that takes a
small amount of disk storage so it is an excellent choice of developers to develop a new
application for Android. It is the first choice of developers because Zero configuration
database
Don't have server
■ Open source
■ Single file database
Four Major things to understand about SQLite :
1. SQLite is RDBMS
(Relational Database
Management System)
2. SQLite is written in C programming language
3.SQLite is embedded within the Android operating system, so you don't need anything external on
Android to use SQLite.
4. To manipulate data (insert, update, delete) in SQLite database we'll use SQL (Structured Query
Language)
Necessity of SQLite Database
SQLite is an open-source relational database i.e. used to perform database operations on android
devices such as storing, manipulating or retrieving persistent data from the database.
• It is embedded in android by default. So, there is no need to perform any database setup
administration task.
Creation and Connection of the Database:
At a shell or DOS prompt, enter: "sqlite3 test.db". This will create a new database named "test.db".
(You can use a different name if you like.)
Enter SQL commands at the prompt to create and populate the new database.
Opening and Closing Android SQLite Database Connection
• Before performing any database operations like insert, update, delete records in a table, first open the
database by
connection
callinggetWritableDatabase() method. as shown
below:

public DBManager open() throws SOLException {


dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
The dbHelper is an instance of the subclass of SQLiteOpenHelper.
To close a database connection the following method is invoked.
public void close() {
}
dbHelper.close();
• Significance of Database in Android:
• SQLite is an open-source lightweight relational database management system (RDBMS) to
perform database operations, such as storing, updating, retrieving data from the database.
• Generally, in our android applications Shared Preferences, Internal Storage and
External Storage options are useful to store and maintain a small amount of data. In case, if
we want to deal with large amounts of data, then SQLite database is the preferable option to
store and maintain the data in a structured format.
• By default, Android comes with built-in SQLite Database support so we don’t need to do any
configurations.
• Just like we save the files on the device’s internal storage, Android stores our database in a
private disk space that’s associated with our application and the data is secure, because by
default this area is not accessible to other applications.
• The package android.database.sqlite contains all the required APIs to use an SQLite
database in our android applications.

• to create a database and required tables in SQLite and perform CRUD (insert,
update, delete and select) operations in android applications.
• Create Database and Tables using SQLite Helper
• In android, by using SQLiteOpenHelper class we can easily create the required
database and tables for our application. To use SQLiteOpenHelper, we need to
create a subclass that overrides the onCreate() and onUpgrade() call-back
methods.
https://www.tutlane.com/tutorial/android/android-sqlite-database-with-examples
Extracting Value from Cursor
The SQLite Database always presents the results as a Cursor in a table format that resembles
that of a SQL database.
. Cursors are what contain the result set of a query made against a database in Android.
app to
• The Cursor class has an API that allows an app to read (in a type-safe manner) the columns
that were returned from the query as well as iterate over the rows of the result set.
• The basic purpose of a cursor is to point to a single row of the result fetched by the query.
You can think of the data as an array of rows.
• A cursor is a pointer into one row of that structured data. The Cursor class provides methods
for moving the cursor through the data structure, and methods to get the data from the fields in
each row.

The Cursor class has a number of subclasses that implement cursors for specific types of
data.
■ SQLiteCursor exposes results from a query on a SQLiteDatabase. SQLiteCursor is not
internally synchronized, so code using a SQLiteCursor from multiple threads should
perform its own synchronization when using the SQLiteCursor. • MatrixCursor is an all-
rounder, a mutable cursor implementation backed by an array of objects that automatically
expands internal capacity as needed.

Some common operations on cursor are:
getCount() returns the number of rows in the cursor.
getColumnNames() returns a string array holding the names of all of the columns in the
result set in the order in which they were listed in the result.
getPosition() returns the current position of the cursor in the row set.
■Getters are available for specific data types, such as getString(int column) and
getInt(int column).
Operations such as moveToFirst() ,moveToNext() move the cursor.
Database fetching:

https://www.tutorialspoint.com/android/android_sqlite_database.htm#:~:text=The
%20main%20package%20is%20android.database.sqlite%20that%20contains%20the,in%20your
%20own%20object.Its%20syntax%20is%20given%20below
https://www.tutorialspoint.com/how-to-save-data-using-sqlite-in-android

https://www.geeksforgeeks.org/how-to-create-and-add-data-to-sqlite-
database-in-android/
Transaction:
A transaction is a single logical unit of work that accesses and possibly modifies the
contents of a database. Transactions access data using read and write operations.
In order to maintain consistency in a database, before and after the transaction, certain
properties are followed. These are called ACID properties.
Atomicity:
By this, we mean that either the entire transaction takes place at once or doesn’t happen at all. There is no
midway i.e. transactions do not occur partially. Each transaction is considered as one unit and either runs to
completion or is not executed at all.
Consistency:
This means that integrity constraints must be maintained so that the database is consistent before and after the
transaction. It refers to the correctness of a database.
Isolation:
This property ensures that multiple transactions can occur concurrently without leading to the inconsistency
of the database state. Transactions occur independently without interference. Changes occurring in a
particular transaction will not be visible to any other transaction until that particular change in that transaction
is written to memory or has been committed. This property ensures that the execution of transactions
concurrently will result in a state that is equivalent to a state achieved these were executed serially in some
order.
Durability:
This property ensures that once the transaction has completed execution, the updates and modifications to the
database are stored in and written to disk and they persist even if a system failure occurs. These updates now
become permanent and are stored in non-volatile memory. The effects of the transaction, thus, are never lost.

You might also like