[go: up one dir, main page]

0% found this document useful (0 votes)
328 views103 pages

Unit V - Activity and Multimedia with Databases - Copy

Unit-V of the Mobile Application Development course covers Activity and Multimedia with Databases, focusing on concepts like Intents, Activity Lifecycle, and SQLite Database. It explains Explicit and Implicit Intents, providing examples of how to use them for communication between app components and launching activities. Additionally, it discusses the Android System Architecture, multimedia frameworks, and the creation and management of databases using SQLite.

Uploaded by

sayedshaad02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
328 views103 pages

Unit V - Activity and Multimedia with Databases - Copy

Unit-V of the Mobile Application Development course covers Activity and Multimedia with Databases, focusing on concepts like Intents, Activity Lifecycle, and SQLite Database. It explains Explicit and Implicit Intents, providing examples of how to use them for communication between app components and launching activities. Additionally, it discusses the Android System Architecture, multimedia frameworks, and the creation and management of databases using SQLite.

Uploaded by

sayedshaad02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Mobile Application Development Unit-V: Activity and Multimedia with Databases

Unit - V

Activity and Multimedia with Databases


20 Marks

Syllabus
5.1 Intent, Intent_Filter
5.2 Activity Lifecycle; Broadcast Lifecycle
5.3 Content Provider; Fragments
5.4 Service: Features of service, Android platforms service, Defining new service, Service
Lifecycle, Permission, example of service
5.5 Android System Architecture, Multimedia Framework, Play Audio and Video, Text to
Speech, Sensors, Async tasks
5.6 Audio Capture, Camera
5.7 Bluetooth, Animation
5.8 SQLite Database, necessity of SQLite, Creation and connection of the database, Extracting
value from cursors, Transactions.

Intent:
java.lang.Object
↳ android.content.Intent

In android, Intent is a messaging object which is used to request an action from another app
component such as activities, services, broadcast receivers and content providers.
Generally in android, Intents will help us to maintain the communication between app
components from the same application as well as with the components of other applications.
In android, Intents are the objects of android.content.Intent type and intents are mainly useful
to perform following things:

Computer Department, Jamia Polytechnic, Akkalkuwa 1


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Component Description
Starting an Activity By passing an Intent object to startActivity() method we can start
a new Activity or existing Activity to perform required things.
Starting a Service By passing an Intent object to startService() method we can start a
new Service or send required instructions to an existing
Service.
Delivering a Broadcast By passing an Intent object to sendBroadcast() method we
can deliver our messages to other app broadcast receivers.

For example: Intent facilitate you to redirect your activity to another activity on occurrence of
any event. By calling, startActivity() you can perform this task.
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
In the above example, foreground activity is getting redirected to another activity i.e.
SecondActivity.java. getApplicationContext() returns the context for your foreground activity.

Types of Intents:
Intent are of two types: Explicit Intent and Implicit Intent.

Explicit Intent:
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.

Computer Department, Jamia Polytechnic, Akkalkuwa 2


Mobile Application Development Unit-V: Activity and Multimedia with Databases

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.

Android Explicit Intent Example


Following is the complete example of implementing an explicit intent in android application. Here
we will do addition of two numbers in one activity and sending that information to another
activity to display the result.
Create a new android application using android studio and open an activity_main.xml file from
\src\main\res\layout path.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="First Number"
/>
<EditText
android:id="@+id/firstNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10">
</EditText>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Number"
android:layout_marginLeft="100dp"

Computer Department, Jamia Polytechnic, Akkalkuwa 3


Mobile Application Development Unit-V: Activity and Multimedia with Databases

/>
<EditText
android:id="@+id/secondNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Add" />
</LinearLayout>

Now we will create another layout resource file result.xml in \src\main\res\layout path to get
the first activity (activity_main.xml) details in second activity file for that right click on your layout
folder à Go to New à select Layout Resource File and give name as result.xml.
Once we create a new layout resource file result.xml, open it and write the code like as shown
below:
result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"/>
</LinearLayout>

Now open our main activity file MainActivity.java from \src\main\java\


com.jamiapolytechnic.explicitintent path and write the code like as shown below
MainActivity.java
package com.jamiapolytechnic.explicitintent;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;

Computer Department, Jamia Polytechnic, Akkalkuwa 4


Mobile Application Development Unit-V: Activity and Multimedia with Databases

import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText firstNum = (EditText)findViewById(R.id.firstNum);
final EditText secNum = (EditText)findViewById(R.id.secondNum);
Button btnAdd = (Button)findViewById(R.id.addBtn);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(firstNum.getText().toString());
int num2 = Integer.parseInt(secNum.getText().toString());
Intent intent = new
Intent(MainActivity.this,ResultActivity.class);
intent.putExtra("SUM",num1+" + "+num2+" = "+(num1+num2));
startActivity(intent);
}
});
}
}

Now we will create another activity file ResultActivity.java in \src\main\java\


com.jamiapolytechnic.explicitintent path to get the first activity (MainActivity.java) details in
second activity file for that right click on your application folder -> Go to New -> select Java Class
and give name as ResultActivity.java.
Once we create a new activity file ResultActivity.java, open it and write the code like as shown
below:
ResultActivity.java
package com.jamiapolytechnic.explicitintent;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ResultActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {

Computer Department, Jamia Polytechnic, Akkalkuwa 5


Mobile Application Development Unit-V: Activity and Multimedia with Databases

super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView result = (TextView)findViewById(R.id.resultView);
Intent intent = getIntent();
String addition = (String)intent.getSerializableExtra("SUM");
result.setText(addition);
}
}

Now we need to add this newly created activity in ActivityManifest.xml file in like as shown
below.
ActivityMainfest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamiapolytechnic.explicitintent">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="Explicit Intent - Activity"
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>
<activity android:name=".ResultActivity" android:label="Explicit
Intent - Activity2">
</activity>
</application>
</manifest>

If you observe above example we are performing an addition operation in one activity
(MainActivity.java) and sending those details to another activity (ResultActivity.java) and added
all the activities in AndroidManifest.xml file.

Implicit Intent:
In android, Implicit Intents won’t specify any name of the component to start, instead it declare

Computer Department, Jamia Polytechnic, Akkalkuwa 6


Mobile Application Development Unit-V: Activity and Multimedia with Databases

an action to perform and it allow a component from other app to handle it. For example, by
using implicit intents we can request another app to show the location details of user or etc.
Following is the pictorial representation of how Implicit intents send a request to android system
to start another activity.

If you observe above image Activity A creates an intent with required action and send it to an
android system using startActivity() method. The android system will search for an intent filter
that matches the intent in all apps. Whenever the match found the system starts matching
activity (Activity B) by invoking onCreate() method.
In android when we create an implicit intents, the android system will search for matching
component by comparing the contents of an intent with intent filters which defined in manifest
file of other apps on the device. If matching component found, the system starts that component
and send it to Intent object. In case if multiple intent filters are matched then the system display
a dialog so that user can pick which app to use.
In android, Intent Filter is an expression in app’s manifest file and it is used to specify the type of
intents that the component would like to receive. In case if we create an Intent Filter for activity,
there is a possibility for other apps to start our activity by sending a certain type of intent
otherwise the activity can be started only by an explicit intent.
Following is the simple code snippet of implicit intent in android application.
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://developer.android.com"));

Computer Department, Jamia Polytechnic, Akkalkuwa 7


Mobile Application Development Unit-V: Activity and Multimedia with Databases

startActivity(intent);

If you observe above implicit intent we didn’t defined any specific name of component to start,
instead we defined an action (ACTION_VIEW) to open the defined URL
(http://developer.android.com) in browser within the device.

Android Implicit Intent Example


Following is the complete example of implementing an implicit intent in android application.
Create a new android application using android studio and open an activity_main.xml file from
\src\main\res\layout path.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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.jamiapolytechnic.implicitintentex.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/urlText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:ems="10" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnNavigate"
android:layout_below="@+id/urlText"
android:text="Navigate"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Now open the main activity file MainActivity.java from


\src\main\java\com\jamiapolytechnic\com.jamiapolytechnic.implicitintentex path and write
the following code to open a new browser window on button click to load given url.

Computer Department, Jamia Polytechnic, Akkalkuwa 8


Mobile Application Development Unit-V: Activity and Multimedia with Databases

MainActivity.java
package com.jamiapolytechnic.implicitintentex;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText)findViewById(R.id.urlText);
Button btn = (Button) findViewById(R.id.btnNavigate);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = editText.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
startActivity(intent);
}
});
}
}

IntentFilter:
Intent filter is used to specify the type of intents that an activity, service, or broadcast receiver
can respond to. It declares the capability of its parent component, what an activity or service can
do and what type of broadcasts a receiver can handle.
It opens the component to receiving intents of the advertised type, while filtering out those that
are not meaningful for the component.
Intent filters are very powerful feature of the Android platform. They provide the ability to launch
an activity based not only on an explicit request, but also an implicit one. For example, an explicit
request might tell the system to start “Start the Send Email activity in the Gmail app”.

Computer Department, Jamia Polytechnic, Akkalkuwa 9


Mobile Application Development Unit-V: Activity and Multimedia with Databases

By contrast, an implicit request tells the system to “Start a Send Email screen in any activity that
can do the job”. When the system UI asks a user which app to use to perform a task, that’s an
intent filter at work.
Syntax:
<intent-filter android:icon=”drawable resource”
android:label=”sting resource”
android:priority=”integer”
android:order=”integer”

</intent-filter>
contained in:
<activity>
<activity-alias>
<service>
<receiver>
must contain:
<action>
can contain:
<category>
<data>
Attributes:
android:icon : An icon represents the parent activity, service, or broadcast receiver when that
component is existing to the user as having the potential described by the filter.
The attribute must be set as a reference to drawable resource containing the image definition.
The defaulting value is the icon set by the parent component’s icon attribute. If theparent do not
specify an icon, the default is the icon set by the <application> element.
android:label : A user-readable label for the parent component. This label, rather than the single
set by the parent component, is used when the component is offered to the user as having the
capability described by the filter.

Computer Department, Jamia Polytechnic, Akkalkuwa 10


Mobile Application Development Unit-V: Activity and Multimedia with Databases

The label should be set asa reference to a string resource, so that it can be localized like other
strings in the user interface. However, for convenience while we are just beginning the
application, it can also be set as an unprocessed string. The value is the label set by parent
component. if the parent do not specify a label, the default is the label set by the <application>
element’s label attribute.
android:priority
The priority that should be given to the parent component with regard to handling intents of the
type described by the filter.
android:order
The order in which the filter should be processed when multiple filters match.

Activity:
In Android, Activity represents a single screen with a user interface (UI) of an application and it
will acts an entry point for users to interact with an app.
Generally, the android apps will contain multiple screens and each screen of our application will
be an extension of Activity class. By using activities, we can place all our android application UI
components in a single screen.
From the multiple activities in android app, one activity can be marked as a main activity and
that is the first screen to appear when we launch the application. In android app each activity
can start another activity to perform different actions based on our requirements.
For example, a contacts app which is having a multiple activities, in that the main activity screen
will show a list of contacts and from the main activity screen we can launch other activities that
provides a screens to perform a tasks like add a new contact and search for the contacts. All
these activities in contact app are loosely bound to other activities but will work together to
provide a better user experience.
Generally, in android there is a minimal dependencies between the activities in an app. To use
activities in application we need to register those activities information in our app’s manifest
file (AndroidMainfest.xml) and need to manage activity life cycle properly.

Computer Department, Jamia Polytechnic, Akkalkuwa 11


Mobile Application Development Unit-V: Activity and Multimedia with Databases

To use activities in our application we need to define an activities with required attributes in
manifest file (AndroidMainfest.xml) like as shown below:
<?xml version="1.0" encoding="utf-8"?>
<manifest …..>
<application …..>
<activity android:name=".MainActivity" >
…….
…….
</activity>
…….
</application>
</manifest>

The activity attribute android:name will represent the name of class and we can also add
multiple attributes like icon, label, theme, permissions, etc. to an activity element based on our
requirements.
In android application, activities can be implemented as a subclass of Activity class like as
shown below.
public class MainActivity extends Activity {
//….
}
This is how we can activities in android application based on our requirements.

Android Activity Lifecycle


Generally, the activities in our android application will go through a different stages in their life
cycle. In android, Activity class have a 7 callback methods like onCreate(), onStart(), onPause(),
onRestart(), onResume(), onStop() and onDestroy() to describe how the activity will behave at
different stages.
By using activity cal-back methods we can define how our activity can behave when the user
enter or leaves our application.
Android Activity Lifecycle Callback Methods
In android, an activity goes through a series of states during its lifetime. By using callback
methods we can get the activity transitions between the states.

Computer Department, Jamia Polytechnic, Akkalkuwa 12


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Android system initiates its program within an Activity starting with a call on onCreate() callback
method. There is a sequence of callback methods that start up an activity and a sequence of
callback methods that tear down an activity.
This section will give you a detailed information about callback methods to handle activity
transitions between states during lifecycle.
onCreate()
This is the first callback method and it fires when the system creates an activity for the first
time. During the activity creation, activity entered into a Created state.
If we have an application start-up logic that needs to perform only once during the life cycle of
an activity, then we can write that logic in onCreate() method.
Following is the example of defining a onCreate() method in android activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Once onCreate() method execution is finished, the activity will enter into Started state and
system calls the onStart() method.
onStart()
The onStart() callback method will invoke when an activity entered into Started State by
completing onCreate() method. The onStart() method will make an activity visible to the user
and this method execution will finish very quickly.
Following is the example of defining a onStart() method in android activity.
@Override
protected void onStart()
{
super.onStart();
}

After completion of onStart() method execution, the activity enters into Resumed state and
system invoke the onResume() method.

Computer Department, Jamia Polytechnic, Akkalkuwa 13


Mobile Application Development Unit-V: Activity and Multimedia with Databases

onResume()
When an activity entered into Resumed state, the system invoke onResume() call back method.
In this state activity start interacting with user that means user can see the functionality and
designing part of an application on the single screen.
Mostly the core functionality of an app is implemented in onResume() method.
The app will stays in this Resumed state until an another activity happens to take focus away
from the app like getting a phone call or screen turned off, etc.
In case if any interruption events happen in Resumed state, the activity will entered into Paused
state and the system will invoke onPause() method.
After an activity returned from Paused state to Resumed state, the system again will call
onResume() method due this we need to implement onResume() method to initialize the
components that we release during onPause() method
Following is the example of defining a onResume() method in android activity.
@Override
protected void onResume() {
super.onResume();
if (mCamera == null) {
initializeCamera();
}
}

If any interruption happen in Resumed state, the activity will entered into Paused state and the
system will invoke onPause() method.
onPause()
Whenever the user leaves an activity or the current activity is being Paused then the system
invoke onPause() method. The onPause() method is used to pause an operations like stop
playing the music when the activity is in paused state or pause an activity while switching from
one app to another app because every time only one app can be focused.
Following is the example of defining a onPause() method in android activity.
@Override
protected void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.release();

Computer Department, Jamia Polytechnic, Akkalkuwa 14


Mobile Application Development Unit-V: Activity and Multimedia with Databases

mCamera = null;
}
}

After completion of onPause() method execution, the next method is either onStop() or
onResume() depending on what happens after an activity entered into Paused state.
onStop()
The system will invoke onStop() callback method when an activity no longer visible to the user,
the activity will enter into Stopped state. This happens due to current activity entered into
Resumed state or newly launched activity covers complete screen or it’s been destroyed.
The onStop() method is useful to release all the app resources which are no longer needed to
the user.
Following is the example of defining a onStop() method in android activity.
@Override
protected void onStop()
{
super.onStop();
}
The next callback method which raised by system is either onRestart(), in case if the activity
coming back to interact with the user or onDestroy(), in case if the activity finished running.
onRestart()
The system will invoke onRestart() method when an activity restarting itself after stopping it.
The onRestart() method will restore the state of activity from the time that is being stopped.
The onRestart() callback method in android activity will always followed by onStart() method.
onDestroy()
The system will invoke onDestroy() method before an activity is destroyed and this is the final
callback method which received by the android activity.
The system will invoke this onDestory() callback method either the activity is finishing or system
destroying the activity to save space.
Following is the example of defining a onDestroy() method in android activity.
@Override
protected void onDestroy()
{
super.onDestroy();

Computer Department, Jamia Polytechnic, Akkalkuwa 15


Mobile Application Development Unit-V: Activity and Multimedia with Databases

The onDestroy() method will release all the resources which are not released by previous
callback onStop() method.

Android Activity Lifecycle Diagram

Computer Department, Jamia Polytechnic, Akkalkuwa 16


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Generally, in android activity class uses different callback methods like onCreate(), onStart(),
onPause(), onRestart(), onResume(), onStop() and onDestroy() to go through a different stages
of activity life cycle.
Above is the pictorial representation of Android Activity Life cycle which shows how Activity will
behave in different stages using callback methods.
Whenever the user trying to leave an activity like switching from one app to another app, the
system will use callback methods to dismantle the activity completely or partially to resume the
activity from where the user left off.
Based on our requirements we can implement the activity in android app using callback method
and it’s not necessary to use all callback methods in each android application.

BroadCast:
Android apps can send or receive broadcast messages from the Android system and other
Android apps, similar to the publish-subscribe design pattern. These broadcasts are sent when
an event of interest occurs. For example, the Android system sends broadcasts when various
system events occur, such as when the system boots up or the device starts charging. Apps can
also send custom broadcasts, for example, to notify other apps of something that they might be
interested in (for example, some new data has been downloaded).
Apps can register to receive specific broadcasts. When a broadcast is sent, the system
automatically routes broadcasts to apps that have subscribed to receive that particular type of
broadcast.
Generally speaking, broadcasts can be used as a messaging system across apps and outside of
the normal user flow.

BroadCast Life Cycle:


A Broadcast receiver is a component that do nothing but receive and react to broadcast
announcements.

Computer Department, Jamia Polytechnic, Akkalkuwa 17


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Many broadcasts originate in system code (eg, "I got mail") but any other application can also
initate broadcasts.
Broadcast receivers do not display a user interface. However, they may perhaps start an activity
in response to the information they receive, or - as services do - they may possibly use the
notification manager to alert the user.
• Register to intent to observe
• Gets notification when intents occur

OR
In Android, Broadcast Receiver is a component which will allow Android system or other apps to
deliver events to the app like sending a low battery message or screen turned off message to the
app. The apps can also initiate broadcasts to let other apps know that required data available in
a device to use it.
Generally, we use Intents to deliver broadcast events to other apps and Broadcast Receivers use
status bar notifications to let user know that broadcast event occurs.
In android, Broadcast Receiver is implemented as a subclass of BroadcastReceiver and each
broadcast is delivered as an Intent object.

Computer Department, Jamia Polytechnic, Akkalkuwa 18


Mobile Application Development Unit-V: Activity and Multimedia with Databases

We can register an app to receive only few broadcast messages based on our requirements.
When a new broadcast received, the system will check for specified broadcasts have subscribed
or not based on that it will routes the broadcasts to the apps.

Receiving Broadcasts
In android, we can receive broadcasts by registering in two ways.
1. Specify the <receiver> element in your app's manifest (AndroidManifest.xml).
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>

The above statement will fire the defined system broadcast event whenever the boot process is
completed.
2. Subclass BroadcastReceiver and implement onReceive(Context, Intent).
public class MyActivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, log, Toast.LENGTH_LONG).show();
}
}

Suppose if we register for ACTION_BOOT_COMPLETED event, whenever the boot process is


completed the broadcast receiver’s method onReceive() method will be invoked.
Sending Broadcasts
In android, we can send a broadcasts in apps using three different ways, those are
Method Description
sendOrderedBroadcast(Intent, String) This method is used to send broadcasts to one
receiver at a time.
sendBroadcast(Intent) This method is used to send broadcasts to all
receivers in an undefined order.
LoadBroadcastManager.sendBroadcast This method is used to send broadcasts to receivers
that are in the same app as the sender.

Computer Department, Jamia Polytechnic, Akkalkuwa 19


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Broadcasting Custom Intents


In android we can create our own custom broadcasts using intents. Following is the simple code
snippet of sending a broadcast by creating an intent using sendBroadcast(Intent) method.
Intent sintent = new Intent();
intent.setAction("com.jamiapolytechnic.broadcastex.MY_NOTIFICATION");
intent.putExtra("data","Welcome to CO Department");
sendBroadcast(intent);

If you observe above code snippet we create a custom Intent “sintent”. We need to register our
intent action in android manifest file like as shown below
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name="
com.jamiapolytechnic.broadcastex.MY_NOTIFICATION" />
</intent-filter>
</receiver>

This is how we can create our own custom broadcasts using Intents in android applications.

System Broadcasts
In android, several system events are defined as final static fields in the Intent class. Following
are the some of system events available in android applications.
Event Description
android.intent.action.BOOT_COMPLETED It raise an event, once boot completed.
android.intent.action.POWER_CONNECTED It is used to trigger an event when power
connected to the device.
android.intent.action.POWER_DISCONNECTED It is used to trigger an event when power
got disconnected from the device.
android.intent.action.BATTERY_LOW It is used to call an event when battery is
low on device.
android.intent.action.BATTERY_OKAY It is used to call an event when battery is
OKAY again.
android.intent.action.REBOOT It call an event when the device rebooted
again.
Likewise we have many system events available in android application.

Computer Department, Jamia Polytechnic, Akkalkuwa 20


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Android BroadcastReceiver Example


To setup a Broadcast Receiver in our android application we need to do following things.
• Create a BroadcastReceiver
• Register a BroadcastReceiver
Create a new android application using android studio and give names as BroadcastReceiver.
Now we need to create our own broadcast content file MyBroadcastReceiver.java in
\src\main\java\com.jamiapolytechnic.broadcastreceiverex path to define our actual provider
and associated methods for that right click on your application folder -> Go to New -> select
Java Class and give name as MyBroadcastReceiver.java.
Once we create a new file MyBroadcastReceiver.java, open it and write the code like as shown
below:
MyBroadcastReceiver.java
package com.jamiapolytechnic.broadcastreceiverex;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent){
CharSequence iData = intent.getCharSequenceExtra("msg");
Toast.makeText(context,"Received Message: " + iData.toString(),
Toast.LENGTH_SHORT).show();
}
}

Now open activity_main.xml file from \src\main\res\layout path and write the following code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Computer Department, Jamia Polytechnic, Akkalkuwa 21


Mobile Application Development Unit-V: Activity and Multimedia with Databases

android:layout_marginLeft="100dp"
android:layout_marginTop="180dp"
android:ems="10"/>
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp"
android:text="Show Broadcast"/>
</LinearLayout>

Now open MainActivity.java file from \java\com.jamiapolytechnic.broadcastreceiver path and


write following to implement custom broadcast intents.
MainActivity.java
package com.jamiapolytechnic.broadcastreceiverex;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


MyBroadcastReceiver receiver = new MyBroadcastReceiver();

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

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


registerReceiver(receiver, new
IntentFilter("CUSTOM_ACTION"),RECEIVER_EXPORTED);
}

Button btn = (Button) findViewById(R.id.btnShow);


btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
EditText st = (EditText)findViewById(R.id.txtMsg);
Intent intent = new Intent("CUSTOM_ACTION");
//intent.setAction("CUSTOM_ACTION");
intent.putExtra("msg",(CharSequence)st.getText().toString());
sendBroadcast(intent);

Computer Department, Jamia Polytechnic, Akkalkuwa 22


Mobile Application Development Unit-V: Activity and Multimedia with Databases

});
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}

Now we need to register our broadcast receiver in android manifest file (AndroidManifest.xml)
using <receiver> attribute like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamiapolytechnic.broadcastreceiverex">

<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>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.jamiapolytechnic.CUSTOM_ACTION">
</action>
</intent-filter>
</receiver>
</application>
</manifest>

Content provider basics


A content provider manages access to a central repository of data. A provider is part of an
Android application, which often provides its own UI for working with the data. However,
content providers are primarily intended to be used by other applications, which access the

Computer Department, Jamia Polytechnic, Akkalkuwa 23


Mobile Application Development Unit-V: Activity and Multimedia with Databases

provider using a provider client object. Together, providers and provider clients offer a
consistent, standard interface to data that also handles inter-process communication and
secure data access.
A content provider presents data to external applications as one or more tables that are similar
to the tables found in a relational database. A row represents an instance of some type of data
the provider collects, and each column in the row represents an individual piece of data
collected for an instance.
A content provider coordinates access to the data storage layer in your application for a
number of different APIs and components as illustrated in figure 1, these include:
• Sharing access to your application data with other applications
• Sending data to a widget
• Returning custom search suggestions for your application through the search framework
using SearchRecentSuggestionsProvider
• Synchronizing application data with your server using an implementation of
AbstractThreadedSyncAdapter
• Loading data in your UI using a CursorLoader
Relationship between content provider and other components.

Computer Department, Jamia Polytechnic, Akkalkuwa 24


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Figure: Relationship between content provider and other components.

Accessing a provider
When you want to access data in a content provider, you use the ContentResolver object in
your application's Context to communicate with the provider as a client. The ContentResolver
object communicates with the provider object, an instance of a class that implements
ContentProvider. The provider object receives data requests from clients, performs the
requested action, and returns the results. This object has methods that call identically-named
methods in the provider object, an instance of one of the concrete subclasses of
ContentProvider. The ContentResolver methods provide the basic "CRUD" (create, retrieve,
update, and delete) functions of persistent storage.
A common pattern for accessing a ContentProvider from your UI uses a CursorLoader to run an
asynchronous query in the background. The Activity or Fragment in your UI call a CursorLoader

Computer Department, Jamia Polytechnic, Akkalkuwa 25


Mobile Application Development Unit-V: Activity and Multimedia with Databases

to the query, which in turn gets the ContentProvider using the ContentResolver. This allows the
UI to continue to be available to the user while the query is running. This pattern involves the
interaction of a number of different objects, as well as the underlying storage mechanism, as
illustrated in figure below.

Content URIs
In android, Content URI is an URI which is used to query a content provider to get the required
data. The Content URIs will contain the name of entire provider (authority) and the name that
points to a table (path).
Generally the format of URI in android applications will be like as shown below
content://authority/path
Following are the details about various parts of an URI in android application.
content:// - The string content:// is always present in the URI and it is used to represent the
given URI is a content URI.

Computer Department, Jamia Polytechnic, Akkalkuwa 26


Mobile Application Development Unit-V: Activity and Multimedia with Databases

authority - It represents the name of content provider, for example phone, contacts, etc. and
we need to use fully qualified name for third party content providers like
com.example.contactprovider
path - It represents the table’s path.
The ContentResolver object use the URI’s authority to find the appropriate provider and send
the query objects to the correct provider. After that ContentProvider uses the path of content
URI to choose the right table to access.
Following is the example of simple example of URI in android applications.
content://contacts_info/users
Here the string content:// is used to represent URI is a content URI, contacts_info string is the
name of provider’s authority and users string is the table’s path.

Creating a Content Provider


To create a content provider in android applications we should follow below steps.
We need to create a content provider class that extends the ContentProvider base class.
We need to define our content provider URI to access the content.
The ContentProvider class defines a six abstract methods (insert(), update(), delete(), query(),
getType()) which we need to implement all these methods as a part of our subclass.
We need to register our content provider in AndroidManifest.xml using <provider> tag.
Following are the list of methods which need to implement as a part of ContentProvider class.

Computer Department, Jamia Polytechnic, Akkalkuwa 27


Mobile Application Development Unit-V: Activity and Multimedia with Databases

query() - It receives a request from the client. By using arguments it will get a data from
requested table and return the data as a Cursor object.
insert() - This method will insert a new row into our content provider and it will return the
content URI for newly inserted row.
update() - This method will update an existing rows in our content provider and it return the
number of rows updated.
delete() - This method will delete the rows in our content provider and it return the number of
rows deleted.
getType() - This method will return the MIME type of data to given content URI.
onCreate() - This method will initialize our provider. The android system will call this method
immediately after it creates our provider.

Content Provider Example


Following is the example of using Content Provider in android applications. Here we will create
our own content provider to insert and access data in android application.
Create a new android application using android studio and give names as ContentProviderEx.
Now we need to create our own content provider file UserProvider.java in

Computer Department, Jamia Polytechnic, Akkalkuwa 28


Mobile Application Development Unit-V: Activity and Multimedia with Databases

\src\main\java\com.jamiapolytechnic.contentproviderex path to define our actual provider and


associated methods for that right click on your application folder -> Go to New -> select Java
Class and give name as UserProvider.java.
Once we create a new file UserProvider.java, open it and write the code like as shown below
package com.jamiapolytechnic.contentproviderex;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import java.util.HashMap;

public class UsersProvider extends ContentProvider {


static final String PROVIDER_NAME =
"com.jamiapolytechnic.contentproviderex.UserProvider";
static final String URL = "content://" + PROVIDER_NAME + "/users";
static final Uri CONTENT_URI = Uri.parse(URL);

static final String id = "id";


static final String name = "name";
static final int uriCode = 1;
static final UriMatcher uriMatcher;
private static HashMap<String, String> values;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "users", uriCode);
uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode);
}

@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case uriCode:
return "vnd.android.cursor.dir/users";
default:
throw new IllegalArgumentException("Unsupported URI: " +
uri);
}
}

Computer Department, Jamia Polytechnic, Akkalkuwa 29


Mobile Application Development Unit-V: Activity and Multimedia with Databases

@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_NAME);

switch (uriMatcher.match(uri)) {
case uriCode:
qb.setProjectionMap(values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == "") {
sortOrder = id;
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = db.insert(TABLE_NAME, "", values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLiteException("Failed to add a record into " + uri);
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.update(TABLE_NAME, values, selection,
selectionArgs);

Computer Department, Jamia Polytechnic, Akkalkuwa 30


Mobile Application Development Unit-V: Activity and Multimedia with Databases

break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.delete(TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
private SQLiteDatabase db;
static final String DATABASE_NAME = "EmpDB";
static final String TABLE_NAME = "Employees";
static final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " name TEXT NOT NULL);";

private static class DatabaseHelper extends SQLiteOpenHelper {


DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DB_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}

Computer Department, Jamia Polytechnic, Akkalkuwa 31


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Now open an activity_main.xml file from \src\main\res\layout path and write the code like as
shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:layout_marginLeft="100dp"
android:layout_marginTop="100dp"/>
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickAddDetails"
android:layout_marginLeft="100dp"
android:text="Add User"/>

<Button
android:id="@+id/btnRetrieve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickShowDetails"
android:layout_marginLeft="100dp"
android:text="Show Users"/>
<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:clickable="false"
android:ems="10"/>
</LinearLayout>

Now open MainActivity.java file and write the code like as shown below:

Computer Department, Jamia Polytechnic, Akkalkuwa 32


Mobile Application Development Unit-V: Activity and Multimedia with Databases

MainActivity.java
package com.jamiapolytechnic.contentproviderex;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
public void onClickAddDetails(View view) {
ContentValues values = new ContentValues();
values.put(UsersProvider.name, ((EditText)
findViewById(R.id.txtName)).getText().toString());
getContentResolver().insert(UsersProvider.CONTENT_URI, values);
Toast.makeText(getBaseContext(), "New Record Inserted",
Toast.LENGTH_LONG).show();
}

public void onClickShowDetails(View view) {


// Retrieve employee records
TextView resultView= (TextView) findViewById(R.id.res);
Cursor cursor =
getContentResolver().query(Uri.parse("content://com.jamiapolytechnic.contentp
roviderex.UserProvider/users"), null, null, null, null);
if(cursor.moveToFirst()) {
StringBuilder strBuild=new StringBuilder();
while (!cursor.isAfterLast()) {

Computer Department, Jamia Polytechnic, Akkalkuwa 33


Mobile Application Development Unit-V: Activity and Multimedia with Databases

strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
resultView.setText(strBuild);
}
else {
resultView.setText("No Records Found");
}
}
}

We need to include this newly created content provider in android manifest file
(ActivityManifest.xml) using <provider> attribute like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamiapolytechnic.contentproviderex">

<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>
<provider
android:authorities="com.jamiapolytechnic.contentproviderex.UserProvider"
android:name=".UsersProvider">
</provider>
</application>

</manifest>

Fragments:
In android, Fragments are the modular section of an activity design and these are used to
represent the behaviour of user interface (UI) in an activity. By using fragments we can create a

Computer Department, Jamia Polytechnic, Akkalkuwa 34


Mobile Application Development Unit-V: Activity and Multimedia with Databases

flexible UI designs that can be adjusted based on the device screen size such as tablets,
smartphones.
We can build multi-pane UI by combining multiple fragments in a single activity and we can
reuse same fragment in multiple activities. The fragment has its own lifecycle call-backs and
accept its own input events.
We can add or remove fragments in an activity while activity is running. In android, the
fragment will act as a sub-activity and we can reuse it in multiple activities.
Generally, in android the fragment must be included in an activity due to that the fragment
lifecycle will always effected by the host activity life cycle. In case if we pause an activity, all the
fragments related to an activity will also be stopped.
In android, we can insert fragment into activity layout by using <fragment> element and by
dividing the layout of an activity into fragments, we can modify the appearance of an app
design at runtime. We can also implement a fragment without having any user interface (UI).
It’s an optional to use fragments into activity but by doing this it will improve the flexibility of
our app UI and make it easier to adjust our app design based on the device size.
Following is the example of defining a multiple fragments in single activity for the tablet design
to display the details of an item which we selected in app, but separated for mobile design.

Computer Department, Jamia Polytechnic, Akkalkuwa 35


Mobile Application Development Unit-V: Activity and Multimedia with Databases

If you observe above example for Tablet we defined an Activity A with two fragments such as
one is to show the list of items and second one is to show the details of item which we selected
in first fragment.
For Handset device, there is no enough space to show both the fragments in single activity, so
the Activity A includes first fragment to show the list of items and the Activity B which includes
another fragment to display the details of an item which is selected in Activity A.
For example, GMAIL app is designed with multiple fragments, so the design of GMAIL app will
be varied based on the size of device such as tablet or mobile device.

Computer Department, Jamia Polytechnic, Akkalkuwa 36


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Android Fragment Life Cycle


Following is pictorial representation of android fragment life cycle while its activity is running.
Following are the list of methods which will perform during the lifecycle of fragment in android
applications.
Method Description
onAttach() It is called when the fragment has been associated with an activity.
onCreate() It is used to initialize the fragment.
onCreteView() It is used to create a view hierarchy associated with the fragment.
onActivityCreated() It is called when the fragment activity has been created and the fragment
view hierarchy instantiated.
onStart() It is used to make the fragment visible.
onResume() It is used to make the fragment visible in an activity.
onPause() It is called when fragment is no longer visible and it indicates that the
user is leaving the fragment.

Computer Department, Jamia Polytechnic, Akkalkuwa 37


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Computer Department, Jamia Polytechnic, Akkalkuwa 38


Mobile Application Development Unit-V: Activity and Multimedia with Databases

onStop() It is called to stop the fragment using onStop() method.


onDestoryView() The view hierarcy which associated with the fragment is being removed
after executing this method.
onDestroy() It is called to perform a final clean up of the fragments state.
onDetach() It is called immediately after the fragment disassociated from the activity.

Android Fragments Examples


Following is the example of creating a two fragments, two buttons and showing the respective
fragment when click on button in android application.
Create a new android application using android studio and give names as FragmentEx.
Now we need to create our own custom fragment layout files (listitems_info.xml,
details_info.xml) in \res\layout path to display those fragments in main layout for that right
click on your layout folder -> Go to New -> select Layout resource file and give name as
listitems_info.xml.
Once we create a new file listitems_info.xml, open it and write the code like as shown below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/list" />
</LinearLayout>

Same way create another file details_info.xml, open it and write the code like as shown below:
details_info.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0079D6">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_marginTop="200px"

Computer Department, Jamia Polytechnic, Akkalkuwa 39


Mobile Application Development Unit-V: Activity and Multimedia with Databases

android:layout_marginLeft="200px"
android:id="@+id/Name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="200px"
android:textColor="#ffffff"
android:id="@+id/Location"/>
</LinearLayout>

Now we need to create our own custom fragment class files (ListMenuFragment.java,
DetailsFragment.java) in \java\com.jamiapolytechnic.fragmentsex path to bind and display data
in fragments for that right click on your application folder -> Go to New -> select Java Class and
give name as DetailsFragment.java.
Once we create a new file DetailsFragment.java, open it and write the code like as shown
below:
DetailsFragment.java
package com.jamiapolytechnic.fragmentex;

//import androidx.fragment.app.Fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class DetailsFragment extends Fragment {


TextView name,location;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_info, container,
false);
name = (TextView)view.findViewById(R.id.Name);
location = (TextView)view.findViewById(R.id.Location);
return view;
}
public void change(String uname, String ulocation){
name.setText(uname);
location.setText(ulocation);
}
}

Computer Department, Jamia Polytechnic, Akkalkuwa 40


Mobile Application Development Unit-V: Activity and Multimedia with Databases

If you observe above code we extended class with Fragment and used LayoutInflater to show
the details of fragment. We defined a function change() to change the text in textview.
Same way create another file ListMenuFragment.java, open it and write the code like as shown
below:
ListMenuFragment.java
package com.jamiapolytechnic.fragmentex;

//import androidx.fragment.app.ListFragment;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListMenuFragment extends ListFragment {


String[] users = new String[] {
"Ahmad","Khan","Shaikh","Patel","Mirza","Ansari" };
String[] location = new String[]{"Akkalkuwa","Molgi","Taloda","Amli
Bari","Dhadgaon","Khapar"};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.listitems_info, container,
false);
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, users);
setListAdapter(adapter);
return view;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
DetailsFragment txt =
(DetailsFragment)getFragmentManager().findFragmentById(R.id.fragment2);
txt.change("Name: "+ users[position],"Location : "+
location[position]);
getListView().setSelector(android.R.color.holo_blue_dark);
}
}

If you observe above code we extended our class using ListFragment and we defined two array

Computer Department, Jamia Polytechnic, Akkalkuwa 41


Mobile Application Development Unit-V: Activity and Multimedia with Databases

of strings users, location which contains names and locations. We defined onListItemClick event
to update the name and location in DetailsFragment based on the list item which we clicked.
Now we need to display our fragments horizontally side by side in main layout for that open
activity_main.xml file and write code like as shown below:
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:orientation="horizontal"
tools:context="com.jamiapolytechnic.fragmentex.MainActivity">

<fragment
android:layout_height="match_parent"
android:layout_width="350px"
android:name="com.jamiapolytechnic.fragmentex.ListMenuFragment"
android:id="@+id/fragment"/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name ="com.jamiapolytechnic.fragmentex.DetailsFragment"
android:id="@+id/fragment2"/>
</LinearLayout>

We are not going to make any modifications for our main activity file (MainActivity.java) and
manifest file (AndroidMainfest.xml).

OR

activity_main.xml
<?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="fill_parent"
android:layout_height="fill_parent"
tools:context="com.jamiapolytechnic.fragmentex.MainActivity">

<fragment
android:id="@+id/fragment1"

Computer Department, Jamia Polytechnic, Akkalkuwa 42


Mobile Application Development Unit-V: Activity and Multimedia with Databases

android:name="com.jamiapolytechnic.fragmentex.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/fragment2"
android:name="com.jamiapolytechnic.fragmentex.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>

MainActivity.java
package com.jamiapolytechnic.fragmentex;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

frag1_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="#F5F5DC"
tools:context="com.jamiapolytechnic.fragmentex.Fragment1">

<!-- TODO: Update blank fragment layout -->


<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text=" This is Fragment 1" />

</FrameLayout>

Computer Department, Jamia Polytechnic, Akkalkuwa 43


Mobile Application Development Unit-V: Activity and Multimedia with Databases

frag2_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="#F0FFFF"
tools:context="com.jamiapolytechnic.fragmentex.Fragment2">

<!-- TODO: Update blank fragment layout -->


<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text=" This is Fragment 2" />

</FrameLayout>

Fragment1.java
package com.jamiapolytechnic.fragmentex;

import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.frag1_layout, container, false);
}
}

Fragment2.java
package com.jamiapolytechnic.fragmentex;

import androidx.fragment.app.Fragment;
import android.os.Bundle;

Computer Department, Jamia Polytechnic, Akkalkuwa 44


Mobile Application Development Unit-V: Activity and Multimedia with Databases

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
// View inflate(int resource, ViewGroup root, boolean attachToRoot)
// Inflate a new view hierarchy from the specified xml resource.
return inflater.inflate(R.layout.frag2_layout, container, false);
}
}

Service
A Service is an application component that can perform long-running operations in the
background. It does not provide a user interface. Once started, a service might continue
running for some time, even after the user switches to another application. Additionally, a
component can bind to a service to interact with it and even perform interprocess
communication (IPC). For example, a service can handle network transactions, play music,
perform file I/O, or interact with a content provider, all from the background.

Service features:
I. Services perform long running operations in the background.
2. It does not contain a user interface.
3. It is useful for things like playing music, network operations, etc.
4. Services are run independently of the component that created it.
5. It can be bound to by other application components if allowed.

Computer Department, Jamia Polytechnic, Akkalkuwa 45


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Types of Services
These are the three different types of services:
Foreground
A foreground service performs some operation that is noticeable to the user. For example, an
audio app would use a foreground service to play an audio track. Foreground services must
display a Notification. Foreground services continue running even when the user isn't
interacting with the app.
When you use a foreground service, you must display a notification so that users are actively
aware that the service is running. This notification cannot be dismissed unless the service is
either stopped or removed from the foreground.
Background
A background service performs an operation that isn't directly noticed by the user. For
example, if an app used a service to compact its storage, that would usually be a background
service.
Bound
A service is bound when an application component binds to it by calling bindService(). A bound
service offers a client-server interface that allows components to interact with the service, send
requests, receive results, and even do so across processes with interprocess communication
(IPC). A bound service runs only as long as another application component is bound to it.
Multiple components can bind to the service at once, but when all of them unbind, the service
is destroyed.
Generally services are either started or bound, your service can work both ways—it can be
started (to run indefinitely) and also allow binding. It's simply a matter of whether you
implement a couple of callback methods: onStartCommand() to allow components to start it
and onBind() to allow binding.
Regardless of whether your service is started, bound, or both, any application component can
use the service (even from a separate application) in the same way that any component can use

Computer Department, Jamia Polytechnic, Akkalkuwa 46


Mobile Application Development Unit-V: Activity and Multimedia with Databases

an activity—by starting it with an Intent. However, you can declare the service as private in the
manifest file and block access from other applications.

The basics
To create a service, you must create a subclass of Service or use one of its existing subclasses. In
your implementation, you must override some callback methods that handle key aspects of the
service lifecycle and provide a mechanism that allows the components to bind to the service, if
appropriate. These are the most important callback methods that you should override:
onStartCommand()
The system invokes this method by calling startService() when another component (such as an
activity) requests that the service be started. When this method executes, the service is started
and can run in the background indefinitely. If you implement this, it is your responsibility to
stop the service when its work is complete by calling stopSelf() or stopService(). If you only
want to provide binding, you don't need to implement this method.
onBind()
The system invokes this method by calling bindService() when another component wants to
bind with the service (such as to perform RPC). In your implementation of this method, you
must provide an interface that clients use to communicate with the service by returning an
IBinder. You must always implement this method; however, if you don't want to allow binding,
you should return null.
onCreate()
The system invokes this method to perform one-time setup procedures when the service is
initially created (before it calls either onStartCommand() or onBind()). If the service is already
running, this method is not called.
onDestroy()
The system invokes this method when the service is no longer used and is being destroyed.
Your service should implement this to clean up any resources such as threads, registered
listeners, or receivers. This is the last call that the service receives.

Computer Department, Jamia Polytechnic, Akkalkuwa 47


Mobile Application Development Unit-V: Activity and Multimedia with Databases

If a component starts the service by calling startService() (which results in a call to


onStartCommand()), the service continues to run until it stops itself with stopSelf() or another
component stops it by calling stopService().
If a component calls bindService() to create the service and onStartCommand() is not called, the
service runs only as long as the component is bound to it. After the service is unbound from all
of its clients, the system destroys it.

The Android system stops a service only when memory is low and it must recover system
resources for the activity that has user focus. If the service is bound to an activity that has user
focus, it's less likely to be killed; if the service is declared to run in the foreground, it's rarely
killed.
In the following sections, you'll see how you can create the startService() and bindService()
service methods, as well as how to use them from other application components.

Declaring a service in the manifest


You must declare all services in your application's manifest file, just as you do for activities and
other components.
To declare your service, add a <service> element as a child of the <application> element. Here is
an example:
<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>

There are other attributes that you can include in the <service> element to define properties
such as the permissions that are required to start the service and the process in which the
service should run. The android:name attribute is the only required attribute—it specifies the

Computer Department, Jamia Polytechnic, Akkalkuwa 48


Mobile Application Development Unit-V: Activity and Multimedia with Databases

class name of the service. After you publish your application, leave this name unchanged to
avoid the risk of breaking code due to dependence on explicit intents to start or bind the
service.
You can ensure that your service is available to only your app by including the android:exported
attribute and setting it to false. This effectively stops other apps from starting your service,
even when using an explicit intent.

Creating a started service


A started service is one that another component starts by calling startService(), which results in
a call to the service's onStartCommand() method.
When a service is started, it has a lifecycle that's independent of the component that started it.
The service can run in the background indefinitely, even if the component that started it is
destroyed. As such, the service should stop itself when its job is complete by calling stopSelf(),
or another component can stop it by calling stopService().
An application component such as an activity can start the service by calling startService() and
passing an Intent that specifies the service and includes any data for the service to use. The
service receives this Intent in the onStartCommand() method.
For instance, suppose an activity needs to save some data to an online database. The activity
can start a companion service and deliver it the data to save by passing an intent to
startService(). The service receives the intent in onStartCommand(), connects to the Internet,
and performs the database transaction. When the transaction is complete, the service stops
itself and is destroyed.
The Service class is the base class for all services. When you extend this class, it's important to
create a new thread in which the service can complete all of its work; the service uses your
application's main thread by default, which can slow the performance of any activity that your
application is running.
The following sections describe how you can implement your own custom service.
Extending the Service class
You can extend the Service class to handle each incoming intent.

Computer Department, Jamia Polytechnic, Akkalkuwa 49


Mobile Application Development Unit-V: Activity and Multimedia with Databases

public class MyService extends Service {



}

Starting a service
You can start a service from an activity or other application component by passing an Intent to
startService() or startForegroundService(). The Android system calls the service's
onStartCommand() method and passes it the Intent, which specifies which service to start.
For example, an activity can start the example service in the previous section (HelloService)
using an explicit intent with startService(), as shown here:
startService(new Intent(this, MyService.class));
The startService() method returns immediately, and the Android system calls the service's
onStartCommand() method. If the service isn't already running, the system first calls
onCreate(), and then it calls onStartCommand().
If the service doesn't also provide binding, the intent that is delivered with startService() is the
only mode of communication between the application component and the service. However, if
you want the service to send a result back, the client that starts the service can create a
PendingIntent for a broadcast (with getBroadcast()) and deliver it to the service in the Intent
that starts the service. The service can then use the broadcast to deliver a result.
Multiple requests to start the service result in multiple corresponding calls to the service's
onStartCommand(). However, only one request to stop the service (with stopSelf() or
stopService()) is required to stop it.

Stopping a service
A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the
service unless it must recover system memory and the service continues to run after
onStartCommand() returns. The service must stop itself by calling stopSelf(), or another
component can stop it by calling stopService().
Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon
as possible.

Computer Department, Jamia Polytechnic, Akkalkuwa 50


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Creating a bound service


A bound service is one that allows application components to bind to it by calling bindService()
to create a long-standing connection. It generally doesn't allow components to start it by calling
startService().
Create a bound service when you want to interact with the service from activities and other
components in your application or to expose some of your application's functionality to other
applications through interprocess communication (IPC).
To create a bound service, implement the onBind() callback method to return an IBinder that
defines the interface for communication with the service. Other application components can
then call bindService() to retrieve the interface and begin calling methods on the service. The
service lives only to serve the application component that is bound to it, so when there are no
components bound to the service, the system destroys it. You do not need to stop a bound
service in the same way that you must when the service is started through onStartCommand().
To create a bound service, you must define the interface that specifies how a client can
communicate with the service. This interface between the service and a client must be an
implementation of IBinder and is what your service must return from the onBind() callback
method. After the client receives the IBinder, it can begin interacting with the service through
that interface.
Multiple clients can bind to the service simultaneously. When a client is done interacting with
the service, it calls unbindService() to unbind. When there are no clients bound to the service,
the system destroys the service.
There are multiple ways to implement a bound service, and the implementation is more
complicated than a started service. For these reasons, the bound service discussion appears in a
separate document about Bound Services.

Sending notifications to the user


When a service is running, it can notify the user of events using snackbar notifications or status
bar notifications.
A snackbar notification is a message that appears on the surface of the current window for only

Computer Department, Jamia Polytechnic, Akkalkuwa 51


Mobile Application Development Unit-V: Activity and Multimedia with Databases

a moment before disappearing. A status bar notification provides an icon in the status bar with
a message, which the user can select in order to take an action (such as start an activity).
Usually, a status bar notification is the best technique to use when background work such as a
file download has completed, and the user can now act on it. When the user selects the
notification from the expanded view, the notification can start an activity (such as to display the
downloaded file).

Managing the lifecycle of a service

The lifecycle of a service is much simpler than that of an activity. However, it's even more
important that you pay close attention to how your service is created and destroyed because a
service can run in the background without the user being aware.

Computer Department, Jamia Polytechnic, Akkalkuwa 52


Mobile Application Development Unit-V: Activity and Multimedia with Databases

The service lifecycle—from when it's created to when it's destroyed—can follow either of these
two paths:
A started service
The service is created when another component calls startService(). The service then runs
indefinitely and must stop itself by calling stopSelf(). Another component can also stop the
service by calling stopService(). When the service is stopped, the system destroys it.
A bound service
The service is created when another component (a client) calls bindService(). The client then
communicates with the service through an IBinder interface. The client can close the
connection by calling unbindService(). Multiple clients can bind to the same service and when
all of them unbind, the system destroys the service. The service does not need to stop itself.
These two paths aren't entirely separate. You can bind to a service that is already started with
startService(). For example, you can start a background music service by calling startService()
with an Intent that identifies the music to play. Later, possibly when the user wants to exercise
some control over the player or get information about the current song, an activity can bind to
the service by calling bindService(). In cases such as this, stopService() or stopSelf() doesn't
actually stop the service until all of the clients unbind.
Figure illustrates the typical callback methods for a service. Although the figure separates
services that are created by startService() from those created by bindService(), keep in mind
that any service, no matter how it's started, can potentially allow clients to bind to it. A service
that was initially started with onStartCommand() (by a client calling startService()) can still
receive a call to onBind() (when a client calls bindService()).
By implementing these methods, you can monitor these two nested loops of the service's
lifecycle:
The entire lifetime of a service occurs between the time that onCreate() is called and the time
that onDestroy() returns. Like an activity, a service does its initial setup in onCreate() and
releases all remaining resources in onDestroy(). For example, a music playback service can
create the thread where the music is played in onCreate(), and then it can stop the thread in
onDestroy().

Computer Department, Jamia Polytechnic, Akkalkuwa 53


Mobile Application Development Unit-V: Activity and Multimedia with Databases

The active lifetime of a service begins with a call to either onStartCommand() or onBind(). Each
method is handed the Intent that was passed to either startService() or bindService().
If the service is started, the active lifetime ends at the same time that the entire lifetime ends
(the service is still active even after onStartCommand() returns). If the service is bound, the
active lifetime ends when onUnbind() returns.

Example of service:
In this example, we create four buttons to start, stop, bind, and unbind to the service. When we
click on the particular button the corresponding service method will call and a toast message
will appear.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startService"
android:layout_marginLeft="130dp"
android:layout_marginTop="150dp"
android:text="Start Service"/>
<Button
android:id="@+id/btnstop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="stopService"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Stop Service"/>
</LinearLayout>

MainActivity.java
package com.jamiapolytechnic.serviceexample;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

Computer Department, Jamia Polytechnic, Akkalkuwa 54


Mobile Application Development Unit-V: Activity and Multimedia with Databases

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Start the service
public void startService(View view) {
startService(new Intent(this, MyService.class));
}
// Stop the service
public void stopService(View view) {
stopService(new Intent(this, MyService.class));
}
}

MyService.java
package com.jamiapolytechnic.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;

public class MyService extends Service {


private MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service was Created",
Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this,
Settings.System.DEFAULT_RINGTONE_URI);
// This will play the ringtone continuously until we stop the
service.
player.setLooping(true);
// It will start the player
player.start();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

Computer Department, Jamia Polytechnic, Akkalkuwa 55


Mobile Application Development Unit-V: Activity and Multimedia with Databases

return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// Stopping the player when service is destroyed
player.stop();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamiapolytechnic.serviceexample">

<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>
<service android:name=".MyService" />
</application>

</manifest>

Multimedia Framework
The Android multimedia system includes multimedia applications, multimedia framework,
OpenCore engine and hardware abstract for audio/video input/output devices. And the goal of
the android multimedia framework is to provide a consistent interface for Java services. The
multimedia framework consists of several core dynamic libraries such as libmediajni, libmedia,
libmediaplayservice and so on.
A general multimedia framework architecture is shown in figure below.

Computer Department, Jamia Polytechnic, Akkalkuwa 56


Mobile Application Development Unit-V: Activity and Multimedia with Databases

From figure, we can see that, Java classes call the Native C library Libmedia through Java JNI (Java
Native Interface). Libmedia library communicates with Media Server guard process through
Android’s Binder IPC (inter process communication) mechanism. Media Server process creates
the corresponding multimedia service according to the Java multimedia applications. The whole
communication between Libmedia and Media Server forms a Client/Server model.
From figure below, we can see that the typical video/audio data stream works in Android as
follows. Specially, Java applications first set the URI of the media (from file or network) to
PVPlayer through Java framework, JNI and Native C. In this process, there are no data stream
flows. Then PVPlayer processes the media data stream with the following steps: demux the media
data to sperate video/audio data stream, decode video/audio data, sync video/audio
time, send the decoded data out.

Computer Department, Jamia Polytechnic, Akkalkuwa 57


Mobile Application Development Unit-V: Activity and Multimedia with Databases

The below is the description of media codec/format, container and networkprotocol supported
by Android platform:
A. Container: The audio file format is a file for storing digital audio data on a system. This data
can be manipulated to reduce the size or change the quality of the audio. It is a kind of
container to store audio information.
B. Audio Format: any format orcodec can be used including the ones provided by Android or
those which are specific to devices. However, it is recommended ot use the specified file
formats as per devices.
C. Network protocols: The following network protocols are supported for audio and video
playback:
• RTSP (RTP, SDP) - Real Time Streaming Protocol (Real-time Transport Protocol, Session
Description Protocol)
• HTTP/HTTPS progressive streaming
• HTTP/HTTPS live streaming draft protocol:

Computer Department, Jamia Polytechnic, Akkalkuwa 58


Mobile Application Development Unit-V: Activity and Multimedia with Databases

o MPEG-2 TS media files only


o Protocol version 3 (Android 4.0 and above)
o Protocol version 2 (Android 3.x)
o Not supported before Android 3.0
Note: HTTPS is not supported before Android 3.1.

Play Audio and Video


Play Audio
There are two types of classes which are used to play audio and video in Android.
1. MediaPlayer: This class is the primary API for playing sound and video.
2. AudioManager: This class manages audio sources and audio output on a device.
Android offers a lot of options in terms of playing audio. Most devices come with speaker,
headphone ports, and some might have Bluetooth connectivity and an additional support for
A2DP audio.
MediaPlayer methods:
Sr.No Method & description
1 isPlaying()
This method just returns true/false indicating the song is playing or not
2 seekTo(position)
This method takes an integer, and move song to that particular position millisecond
3 getCurrentPosition()
This method returns the current position of song in milliseconds
4 getDuration()
This method returns the total time duration of song in milliseconds
5 reset()
This method resets the media player
6 release()
This method releases any resource attached with MediaPlayer object
7 setVolume(float leftVolume, float rightVolume)

Computer Department, Jamia Polytechnic, Akkalkuwa 59


Mobile Application Development Unit-V: Activity and Multimedia with Databases

This method sets the up down volume for this player


8 setDataSource(FileDescriptor fd)
This method sets the data source of audio/video file
9 selectTrack(int index)
This method takes an integer, and select the track from the list on that particular index
10 getTrackInfo()
This method returns an array of track information

Manifest Declarations
Before starting development on your application using MediaPlayer, make sure your manifest
has the appropriate declarations to allow use of related features.
Internet Permission - If you are using MediaPlayer to stream network-based content, your
application must request network access.
<uses-permission android:name="android.permission.INTERNET" />
Wake Lock Permission - If your player application needs to keep the screen from dimming or
the processor from sleeping, or uses the MediaPlayer.setScreenOnWhilePlaying() or
MediaPlayer.setWakeMode() methods, you must request this permission.
<uses-permission android:name="android.permission.WAKE_LOCK" />

Using MediaPlayer
One of the most important components of the media framework is the MediaPlayer class. An
object of this class can fetch, decode, and play both audio and video with minimal setup. It
supports several different media sources such as:
• Local resources
• Internal URIs, such as one you might obtain from a Content Resolver
• External URLs (streaming)
Here is an example of how to play audio that's available as a local raw resource (saved in your
application's res/raw/ directory):
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start(); // no need to call prepare(); create() does that for you

Computer Department, Jamia Polytechnic, Akkalkuwa 60


Mobile Application Development Unit-V: Activity and Multimedia with Databases

In this case, a "raw" resource is a file that the system does not try to parse in any particular
way. However, the content of this resource should not be raw audio. It should be a properly
encoded and formatted media file in one of the supported formats.
And here is how you might play from a URI available locally in the system (that you obtained
through a Content Resolver, for instance):
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();

Playing from a remote URL via HTTP streaming looks like this:
String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();

Media Player Example:


avtivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="@+id/txtVw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Now Playing: "
android:layout_marginTop="30dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/txtSname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Computer Department, Jamia Polytechnic, Akkalkuwa 61


Mobile Application Development Unit-V: Activity and Multimedia with Databases

android:layout_alignBaseline="@+id/txtVw1"
android:text="TextView" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:src="@android:drawable/ic_media_play" />
<ImageButton
android:id="@+id/btnPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:src="@android:drawable/ic_media_pause" />
</LinearLayout>
</LinearLayout>

MainActivity.java
package com.jamiapolytechnic.mediaplayerexample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private ImageButton pausebtn, playbtn;
private MediaPlayer mPlayer;
private TextView fileName;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playbtn = (ImageButton)findViewById(R.id.btnPlay);
pausebtn = (ImageButton)findViewById(R.id.btnPause);
fileName = (TextView)findViewById(R.id.txtSname);
fileName.setText("Ad-Duha");
mPlayer = MediaPlayer.create(this, R.raw.ad_duha);

playbtn.setOnClickListener(new View.OnClickListener() {

Computer Department, Jamia Polytechnic, Akkalkuwa 62


Mobile Application Development Unit-V: Activity and Multimedia with Databases

@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Playing Audio",
Toast.LENGTH_SHORT).show();
mPlayer.start();
pausebtn.setEnabled(true);
playbtn.setEnabled(false);
}
});
pausebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPlayer.pause();
pausebtn.setEnabled(false);
playbtn.setEnabled(true);
Toast.makeText(getApplicationContext(),"Pausing Audio",
Toast.LENGTH_SHORT).show();
}
});

}
}

OR
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Now Playing: " />
<TextView
android:id="@+id/txtfileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Now Playing: " />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

Computer Department, Jamia Polytechnic, Akkalkuwa 63


Mobile Application Development Unit-V: Activity and Multimedia with Databases

<Button
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:onClick="playAudio"/>
<Button
android:id="@+id/btnPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause"
android:onClick="pauseAudio"/>
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:onClick="stopAudio"/>
</LinearLayout>
</LinearLayout>

MainActivity.java
package com.jamiapolytechnic.audioplayerex;

import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


MediaPlayer mp;
Button btnPlay, btnPause, btnStop;
TextView audioName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnPlay = (Button) findViewById(R.id.btnPlay);


btnPause = (Button) findViewById(R.id.btnPause);
btnStop = (Button) findViewById(R.id.btnStop);
mp = MediaPlayer.create(this,R.raw.ad_duha);
audioName = (TextView)findViewById(R.id.txtfileName);
audioName.setText("Ad-Duha");
}
public void playAudio(View v){

Computer Department, Jamia Polytechnic, Akkalkuwa 64


Mobile Application Development Unit-V: Activity and Multimedia with Databases

mp.start();
btnPlay.setEnabled(false);
btnPause.setEnabled(true);
}
public void pauseAudio(View v){
mp.pause();
btnPause.setEnabled(false);
btnPlay.setEnabled(true);
}
public void stopAudio(View v){
mp.stop();
mp.release();
mp = null;
System.exit(0);
}
}

Play Video
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<VideoView
android:id="@+id/vdVw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
</RelativeLayout>

MainActivity.java
package com.jamiapolytechnic.videoplayerex;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.net.Uri;
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);

Computer Department, Jamia Polytechnic, Akkalkuwa 65


Mobile Application Development Unit-V: Activity and Multimedia with Databases

VideoView videoView =(VideoView)findViewById(R.id.vdVw);


//Set MediaController to enable play, pause, forward, etc options.
MediaController mediaController= new MediaController(this,true);
mediaController.setAnchorView(videoView);
//Location of Media File
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" +
R.raw.tom_n_jerry);
//Starting VideView By Setting MediaController and URI
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
}
}

Text To Speech
Android allows you convert your text into voice. Not only you can convert it but it also allows
you to speak text in variety of different languages.
Android provides TextToSpeech class for this purpose. In order to use this class, you need to
instantiate an object of this class and also specify the initListener. Its syntax is given below −
private EditText write;
ttobj=new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
}
});

In this listener, you have to specify the properties for TextToSpeech object , such as its
language, pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given
below −
ttobj.setLanguage(Locale.US);

The method setLanguage takes an Locale object as parameter. The list of some of the locales
available are given below −
Sr.No Locale

Computer Department, Jamia Polytechnic, Akkalkuwa 66


Mobile Application Development Unit-V: Activity and Multimedia with Databases

1 US
2 CANADA_FRENCH
3 GERMANY
4 ITALY
5 JAPAN
6 CHINA

Once you have set the language, you can call speak method of the class to speak the text. Its
syntax is given below −
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);

Apart from the speak method, there are some other methods available in the TextToSpeech
class. They are listed below −

Sr.No Method & description


1 addSpeech(String text, String filename)
This method adds a mapping between a string of text and a sound file.
2 getLanguage()
This method returns a Locale instance describing the language.
3 isSpeaking()
This method checks whether the TextToSpeech engine is busy speaking.
4 setPitch(float pitch)
This method sets the speech pitch for the TextToSpeech engine.
5 setSpeechRate(float speechRate)
This method sets the speech rate.
6 shutdown()
This method releases the resources used by the TextToSpeech engine.
7 stop()
This method stop the speak.

Computer Department, Jamia Polytechnic, Akkalkuwa 67


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Example
The below example demonstrates the use of TextToSpeech class. It crates a basic application
that allows you to set write text and speak it.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:text="Text to Speech Example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview" />
<EditText
android:ems="20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text to Speech"
android:id="@+id/button" />
</LinearLayout>

MainActivity.java
package com.jamiapolytechnic.ttsexample;

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;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


TextToSpeech t1;
EditText ed1;
Button b1;

@Override
protected void onCreate(Bundle savedInstanceState) {

Computer Department, Jamia Polytechnic, Akkalkuwa 68


Mobile Application Development Unit-V: Activity and Multimedia with Databases

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1 = (EditText) findViewById(R.id.editText);
b1 = (Button) findViewById(R.id.button);

t1 = new TextToSpeech(getApplicationContext(), new


TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setPitch(0.25f);
t1.setSpeechRate(1f);
t1.setLanguage(Locale.US);
}
}
});

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak,
Toast.LENGTH_SHORT).show();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
}

public void onDestroy() {


if (t1 != null) {
t1.stop();
t1.shutdown();
}
super.onDestroy();
}
}

Sensors
Most Android-powered devices have built-in sensors that measure motion, orientation, and
various environmental conditions. These sensors are capable of providing raw data with high
precision and accuracy, and are useful if you want to monitor three-dimensional device
movement or positioning, or you want to monitor changes in the ambient environment near a
device.
The Android platform supports three broad categories of sensors:

Computer Department, Jamia Polytechnic, Akkalkuwa 69


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Motion sensors
These sensors measure acceleration forces and rotational forces along three axes. This category
includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
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.
Position sensors
These sensors measure the physical position of a device. This category includes orientation
sensors and magnetometers.
You can access sensors available on the device and acquire raw sensor data by using the
Android sensor framework. The sensor framework provides several classes and interfaces that
help you perform a wide variety of sensor-related tasks. For example, you can use the sensor
framework to do the following:
• Determine which sensors are available on a device.
• Determine an individual sensor's capabilities, such as its maximum range, manufacturer,
power requirements, and resolution.
• Acquire raw sensor data and define the minimum rate at which you acquire sensor data.
• Register and unregister sensor event listeners that monitor sensor changes.
The Android sensor framework lets you access many types of sensors. Some of these sensors
are hardware-based and some are software-based. Hardware-based sensors are physical
components built into a handset or tablet device. Software-based sensors are not physical
devices, although they mimic hardware-based sensors. Software-based sensors derive their
data from one or more of the hardware-based sensors and are sometimes called virtual sensors
or synthetic sensors.

Sensor types supported by the Android platform


Common
Sensor Type Description
Uses

Computer Department, Jamia Polytechnic, Akkalkuwa 70


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Measures the acceleration force


Motion
in m/s2 that is applied to a
detection
TYPE_ACCELEROMETER Hardware device on all three physical axes
(shake, tilt,
(x, y, and z), including the force
etc.).
of gravity.

Measures the ambient room Monitoring


TYPE_AMBIENT_TEMPERATURE Hardware temperature in degrees Celsius air
(°C). See note below. temperatures.

Measures the force of gravity in Motion


Software
m/s2 that is applied to a device detection
TYPE_GRAVITY or
on all three physical axes (x, y, (shake, tilt,
Hardware
z). etc.).
Measures a device's rate of Rotation
rotation in rad/s around each of detection
TYPE_GYROSCOPE Hardware
the three physical axes (x, y, and (spin, turn,
z). etc.).
Controlling
Measures the ambient light level
TYPE_LIGHT Hardware screen
(illumination) in lx.
brightness.
Measures the acceleration force
Monitoring
Software in m/s2 that is applied to a
acceleration
TYPE_LINEAR_ACCELERATION or device on all three physical axes
along a single
Hardware (x, y, and z), excluding the force
axis.
of gravity.
Measures the ambient
Creating a
TYPE_MAGNETIC_FIELD Hardware geomagnetic field for all three
compass.
physical axes (x, y, z) in μT.
Measures degrees of rotation
that a device makes around all
three physical axes (x, y, z). As of
API level 3 you can obtain the
Determining
inclination matrix and rotation
TYPE_ORIENTATION Software device
matrix for a device by using the
position.
gravity sensor and the
geomagnetic field sensor in
conjunction with
the getRotationMatrix() method.
Monitoring
Measures the ambient air
TYPE_PRESSURE Hardware air pressure
pressure in hPa or mbar.
changes.

Computer Department, Jamia Polytechnic, Akkalkuwa 71


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Common
Sensor Type Description
Uses

Measures the proximity of an object in cm


relative to the view screen of a device. Phone
TYPE_PROXIMITY Hardware This sensor is typically used to determine position
whether a handset is being held up to a during a call.
person's ear.

Monitoring
dewpoint,
Measures the relative ambient humidity in
TYPE_RELATIVE_HUMIDITY Hardware absolute, and
percent (%).
relative
humidity.
Motion
Software Measures the orientation of a device by
detection and
TYPE_ROTATION_VECTOR or providing the three elements of the
rotation
Hardware device's rotation vector.
detection.

Measures the temperature of the device


in degrees Celsius (°C). This sensor
implementation varies across devices and Monitoring
TYPE_TEMPERATURE Hardware
this sensor was replaced with temperatures.
the TYPE_AMBIENT_TEMPERATURE sensor
in API Level 14

Sensor Framework
You can access these sensors and acquire raw sensor data by using the Android sensor
framework. The sensor framework is part of the android.hardware package and includes the
following classes and interfaces:
SensorManager
You can use this class to create an instance of the sensor service. This class provides various
methods for accessing and listing sensors, registering and unregistering sensor event listeners,
and acquiring orientation information. This class also provides several sensor constants that are
used to report sensor accuracy, set data acquisition rates, and calibrate sensors.

Sensor
You can use this class to create an instance of a specific sensor. This class provides various

Computer Department, Jamia Polytechnic, Akkalkuwa 72


Mobile Application Development Unit-V: Activity and Multimedia with Databases

methods that let you determine a sensor's capabilities.


SensorEvent
The system uses this class to create a sensor event object, which provides information about a
sensor event. A sensor event object includes the following information: the raw sensor data, the
type of sensor that generated the event, the accuracy of the data, and the timestamp for the
event.
SensorEventListener
You can use this interface to create two callback methods that receive notifications (sensor
events) when sensor values change or when sensor accuracy changes.

Identifying Sensors on device


To identify the sensors that are on a device you first need to get a reference to the sensor service.
To do this, you create an instance of the SensorManager class by calling the getSystemService()
method and passing in the SENSOR_SERVICE argument. For example:
private SensorManager sensorManager;
...
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

Next, you can get a listing of every sensor on a device by calling the getSensorList() method and
using the TYPE_ALL constant. For example:
List<Sensor> deviceSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);

You can also determine whether a specific type of sensor exists on a device by using the
getDefaultSensor() method and passing in the type constant for a specific sensor. If a device has
more than one sensor of a given type, one of the sensors must be designated as the default
sensor. If a default sensor does not exist for a given type of sensor, the method call returns null,
which means the device does not have that type of sensor. For example, the following code
checks whether there's a magnetometer on a device:
private SensorManager sensorManager;
...
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){

Computer Department, Jamia Polytechnic, Akkalkuwa 73


Mobile Application Development Unit-V: Activity and Multimedia with Databases

// Success! There's a magnetometer.


} else {
// Failure! No magnetometer.
}

Android Sensors Example


Following is the example of identifying the sensors and list all the available sensors on a device
using android sensor framework.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="@+id/sensorslist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="Sensors"
android:textSize="20dp"
android:textStyle="bold"
android:layout_gravity="center"
android:visibility="gone"/>
</LinearLayout>

MainActivity.java
package com.jamiapolytechnic.sensorlist;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.view.View;
import android.widget.TextView;
import java.util.List;

public class MainActivity extends AppCompatActivity {


private SensorManager mgr;
private TextView txtList;
@Override
protected void onCreate(Bundle savedInstanceState) {

Computer Department, Jamia Polytechnic, Akkalkuwa 74


Mobile Application Development Unit-V: Activity and Multimedia with Databases

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
txtList = (TextView)findViewById(R.id.sensorslist);
List<Sensor> sensorList = mgr.getSensorList(Sensor.TYPE_ALL);
StringBuilder strBuilder = new StringBuilder();
for(Sensor s: sensorList){
strBuilder.append(s.getName()+"\n");
}
txtList.setVisibility(View.VISIBLE);
txtList.setText(strBuilder);
}
}

Async Task
In Android, AsyncTask (Asynchronous Task) allows us to run the instruction in the background
and then synchronize again with our main thread. This class will override at least one method i.e
doInBackground(Params) and most often will override second method onPostExecute(Result).

AsyncTask class is used to do background operations that will update the UI(user interface).
Mainly we use it for short operations that will not effect on our main thread.

Computer Department, Jamia Polytechnic, Akkalkuwa 75


Mobile Application Development Unit-V: Activity and Multimedia with Databases

AsyncTask class is firstly executed using execute() method. In the first step AsyncTask is called
onPreExecute() then onPreExecute() calls doInBackground() for background processes and then
doInBackground() calls onPostExecute() method to update the UI.

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.
Syntax of AsyncTask In Android:
To use AsyncTask you must subclass it. The parameters are the following AsyncTask
<TypeOfVarArgParams, ProgressValue, ResultValue>. Here is the
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
}
}

Executions of AsyncTask class from main thread:


Here is the Syntax for execution of AsyncTasks classs.
new DownloadFilesTask().execute(url1, url2, url3);

Computer Department, Jamia Polytechnic, Akkalkuwa 76


Mobile Application Development Unit-V: Activity and Multimedia with Databases

AsyncTask’s generic types In Android:


The three types used by Asynchronous task are the following:
AsyncTask <TypeOfVarArgParams, ProgressValue, ResultValue>
1. TypeOfVarArgParams: Params is the type of the parameters sent to the task upon execution.
2. ProgressValue: Progress is the type of the progress units published during the background
computation.
3. ResultValue: ResultValue is the type of the result of 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.

Computer Department, Jamia Polytechnic, Akkalkuwa 77


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Rules of AsyncTask:
There are a few threading rules that must be followed for this class to work properly:
1. This class must be loaded on the UI thread. This is done automatically as from JELLY_BEAN.
2. The task instance must be created on the UI thread.
3. execute(Params…) method that executes it, must be invoked on the UI thread.
4. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params…),
onProgressUpdate(Progress…) manually, just executes the class and then will call automatically
for good user experience.

Audio Capture:
Android has a built in microphone through which you can capture audio and store it , or play it in
your phone. There are many ways to do that but the most common way is through
MediaRecorder class.
Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder
class ,you will first create an instance of MediaRecorder class. Its syntax is given below.
MediaRecorder myAudioRecorder = new MediaRecorder();
Now you will set the source , output and encoding format and output file. Their syntax is given
below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
After specifying the audio source and format and its output file, we can then call the two basic
methods prepare and start to start recording the audio.
myAudioRecorder.prepare();
myAudioRecorder.start();
Apart from these methods , there are other methods listed in the MediaRecorder class that
allows you more control over audio and video recording.
Sr.No. Method & description
1 setAudioSource()

Computer Department, Jamia Polytechnic, Akkalkuwa 78


Mobile Application Development Unit-V: Activity and Multimedia with Databases

This method specifies the source of audio to be recorded


2 setVideoSource()
This method specifies the source of video to be recorded
3 setOutputFormat()
This method specifies the audio format in which audio to be stored
4 setAudioEncoder()
This method specifies the audio encoder to be used
5 setOutputFile()
This method configures the path to the file into which the recorded audio is to
be stored
6 stop()
This method stops the recording process.
7 release()
This method should be called when the recorder instance is needed.

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>

Camera:
These are the following two ways, in which you can use camera in your application

Computer Department, Jamia Polytechnic, Akkalkuwa 79


Mobile Application Development Unit-V: Activity and Multimedia with Databases

• Using existing android camera application in our application


• Directly using Camera API provided by android in our application

Using existing android camera application in our application


You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application
installed on your phone. Its syntax is given below:
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Apart from the above, there are other available Intents provided by MediaStore. They are listed
as follows:
Sr.No. Intent type and description
1 ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured
2 ACTION_VIDEO_CAPTURE
It calls the existing video application in android to capture video
3 EXTRA_SCREEN_ORIENTATION
It is used to set the orientation of the screen to vertical or landscape
4 EXTRA_FULL_SCREEN
It is used to control the user interface of the ViewImage
5 INTENT_ACTION_VIDEO_CAMERA
This intent is used to launch the camera in the video mode
6 EXTRA_SIZE_LIMIT
It is used to specify the size limit of video or image capture size

Now you will use the function startActivityForResult() to launch this activity and wait for its
result. Its syntax is given below:
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity. There
are methods defined in the activity class that does the same job , but used when you are not
calling from the activity but from somewhere else. They are listed below:

Computer Department, Jamia Polytechnic, Akkalkuwa 80


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Sr.No. Activity function description


1 startActivityForResult(Intent intent, int requestCode, Bundle options)
It starts an activity , but can take extra bundle of options with it
2 startActivityFromChild(Activity child, Intent intent, int requestCode)
It launch the activity when your activity is child of any other activity
3 startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle
options)
It work same as above , but it can take extra values in the shape of bundle with it
4 startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)
It launches activity from the fragment you are currently inside
5 startActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
Bundle options)
It not only launches the activity from the fragment , but can take extra values
with it

No matter which function you used to launch the activity , they all return the result. The result
can be obtained by overriding the function onActivityResult.

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;

Computer Department, Jamia Polytechnic, Akkalkuwa 81


Mobile Application Development Unit-V: Activity and Multimedia with Databases

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


1 ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth
2 ACTION_STATE_CHANGED
This constant will notify that Bluetooth state has been changed
3 ACTION_FOUND
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.No. Method & description
1 enable()
This method enables the adapter if not enabled
2 isEnabled()
This method returns true if adapter is enabled
3 disable()
This method disables the adapter

Computer Department, Jamia Polytechnic, Akkalkuwa 82


Mobile Application Development Unit-V: Activity and Multimedia with Databases

4 getName()
This method returns the name of the Bluetooth adapter
5 setName(String name)
This method changes the Bluetooth name
6 getState()
This method returns the current state of the Bluetooth Adapter.
7 startDiscovery()
This method starts the discovery process of the Bluetooth for 120 seconds.

Android Set Bluetooth Permissions


To use Bluetooth features in our android applications, we must need to add multiple permissions,
such as BLUETOOTH and ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION in our
manifest file.
Permission Description
BLUETOOTH We need this permission to perform any Bluetooth communication, such
as requesting a connection, accepting a connection, and transferring
data.
LOCATION We need this permission because the Bluetooth scans can be used to
gather the information about the location of user.
In case, if we want to discover the available Bluetooth devices or manipulate Bluetooth settings
from our app, we need to define BLUETOOTH_ADMIN permission.
Following is the example of defining the Bluetooth permissions in android manifest file.
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>

Android List Bluetooth Paired Devices Example

Computer Department, Jamia Polytechnic, Akkalkuwa 83


Mobile Application Development Unit-V: Activity and Multimedia with Databases

Create a new android application using android studio and give names as
BluetoothListPairedDevicesExample.
Once we create an application, open activity_main.xml file from \res\layout folder path and write
the code like as shown below:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnGet"
android:text="Get Paired Devices"
android:layout_marginLeft="130dp"
android:layout_marginTop="200dp" />
<ListView
android:id="@+id/deviceList"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

Now open your main activity file MainActivity.java from \java\com.example.bluetoothexample


path and write the code like as shown below
MainActivity.java
package com.jamiapolytechnic.bluetoothexample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {


private ListView lstvw;

Computer Department, Jamia Polytechnic, Akkalkuwa 84


Mobile Application Development Unit-V: Activity and Multimedia with Databases

private ArrayAdapter aAdapter;


private BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btnGet);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(bAdapter==null){
Toast.makeText(getApplicationContext(),"Bluetooth Not
Supported",Toast.LENGTH_SHORT).show();
}
else{
Set<BluetoothDevice> pairedDevices =
bAdapter.getBondedDevices();
ArrayList list = new ArrayList();
if(pairedDevices.size()>0){
for(BluetoothDevice device: pairedDevices){
String devicename = device.getName();
String macAddress = device.getAddress();
list.add("Name: "+devicename+"MAC Address:
"+macAddress);
}
lstvw = (ListView) findViewById(R.id.deviceList);
aAdapter = new ArrayAdapter(getApplicationContext(),
android.R.layout.simple_list_item_1, list);
lstvw.setAdapter(aAdapter);
}
}
}
});
}
}

We need to set Bluetooth permissions in android manifest file (AndroidManifest.xml) to access


Bluetooth features in android applications. Now open android manifest file
(AndroidManifest.xml) and write the code like as shown below
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamiapolytechnic.bluetoothexample">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application

Computer Department, Jamia Polytechnic, Akkalkuwa 85


Mobile Application Development Unit-V: Activity and Multimedia with Databases

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>

Animation
“Animation is the process of creating motion and shape change”
Animation in android is possible from many ways. We will discuss one easy and widely used
way of making animation called tweened animation. We have four kinds tween animation:
Alpha (fade), Rotate, Translate, Scale (zoom).
Tween Animation
Tween Animation takes some parameters such as start value , end value, size , time duration ,
rotation angle etc. and perform the required animation on that object. It can be applied to any
type of object. So in order to use this , android has provided us a class called Animation.
In order to perform animation in android , we are going to call a static function loadAnimation()
of the class AnimationUtils. We are going to receive the result in an instance of Animation
Object. Its syntax is as follows −
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
Note the second parameter. It is the name of the our animation xml file. You have to create a
new folder called anim under res directory and make an xml file under anim folder.
This animation class has many useful functions which are listed below −

Sr.No. Method & Description

Computer Department, Jamia Polytechnic, Akkalkuwa 86


Mobile Application Development Unit-V: Activity and Multimedia with Databases

1 start()
This method starts the animation.
2 setDuration(long duration)
This method sets the duration of an animation.
3 getDuration()
This method gets the duration which is set by above method
4 end()
This method ends the animation.
5 cancel()
This method cancels the animation.

In order to apply this animation to an object , we will just call the startAnimation() method of
the object. Its syntax is −
ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);

The following are some of the important animation attributes that will help us to change the
behavior of animation in our application.
Attributes Description
android:duration It is used to define the duration of the animation to complete.
android:startOffset It is used to define the waiting time before the animation starts.
android:interpolator It is used to define the rate of change in animation.
android:repeatMode It is useful when we want to repeat our animation.
android:repeatCount It is used to define the number of times the animation repeats. In case if
we set infinite, the animation will repeat infinite times.
android:fillAfter It is used to define whether to apply animation transformation after the
animation completes or not.

Different Types of Android Animations

Computer Department, Jamia Polytechnic, Akkalkuwa 87


Mobile Application Development Unit-V: Activity and Multimedia with Databases

In android, we have different types of animations such as Fade In / Fade Out, Zoom In / Zoom
Out, Slide Up / Slide Down, Rotate in Clockwise or Anti-Clockwise, etc.
Now we will see how to create each animation with required properties in the android
application.
Android Fade In / Out Animation
To use Fade In or Fade Out animations in our android applications, we need to define a new
XML file with <alpha> tag like as shown below.
For Fade In animation, we need to increase the alpha value from 0 to 1 like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<alpha
android:duration="2000"
android:fromAlpha="0.1"
android:toAlpha="1.0">
</alpha>
</set>

For Fade Out animation, we need to decrease the alpha value from 1 to 0 like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<alpha
android:duration="2000"
android:fromAlpha="1.0"
android:toAlpha="0.1" >
</alpha>
</set>

Android Slide Up / Down Animation


To use Slide Up or Slide Down animations in our android applications, we need to define a new
XML file with <scale> tag like as shown below.
For Slide Up animation, we need to set android:fromYScale="1.0" and android:toYScale="0.0"
like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<scale

Computer Department, Jamia Polytechnic, Akkalkuwa 88


Mobile Application Development Unit-V: Activity and Multimedia with Databases

android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>

For Slide Down animation, we need to set android:fromYScale="0.0" and


android:toYScale="1.0" like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>

Android Zoom In / Out Animation


To use Zoom In or Zoom Out animations in our android applications, we need to define a new
XML file with <scale> tag like as shown below.
For Zoom In animation, we need to set android:pivotX="50%" and android:pivotY="50%" to
perform the zoom from the centre of the element. Also, we need to use fromXScale,
fromYScale attributes to define the scaling of an object and we need keep these values lesser
than toXScale, toYScale like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="2"
android:fromYScale="2"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="4"
android:toYScale="4" >
</scale>
</set>

Computer Department, Jamia Polytechnic, Akkalkuwa 89


Mobile Application Development Unit-V: Activity and Multimedia with Databases

In android, Zoom Out animation is same as Zoom In animation but fromXScale, fromYScale
attribute values must be greater than toXScale, toYScale like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:duration="2500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale=".2"
android:toYScale=".2" />
</set>

Android Rotate Clockwise / Anti Clockwise Animation


To use Rotate animation in our android applications, we need to define a new XML file with
<rotate> tag like as shown below.
To Rotate animation in Clockwise, we need to set android:fromDegrees and android:toDegrees
property values and these will define a rotation angles like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/cycle_interpolator">
<rotate android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" />
</set>

To Rotate animation in Anti Clockwise, we need to set android:fromDegrees and


android:toDegrees property values and these will define a rotation angles like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/cycle_interpolator">
<rotate android:fromDegrees="360"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" />
</set>

Computer Department, Jamia Polytechnic, Akkalkuwa 90


Mobile Application Development Unit-V: Activity and Multimedia with Databases

SQLite Database
SQLite is a opensource 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 etc.

Necessity of SQLite
Serverless: SQLite does not require a server process or system to run
Zero-configuration: SQLite does not require any setup or administration. SQLite uses no
configuration files,
Cross-platform: The SQLite file format is cross-platform. A database file written on one machine
can be copied to and used on a different machine with a different architecture. Big-endian or
little-endian, 32-bit or 64-bit does not matter.
Less-memory (Compact): When optimized for size, the whole SQLite library with everything
enabled is less than 500KiB in size. Unneeded features can be disabled at compile-time to
further reduce the size of the library to under 300KiB if desired.
Self-Contained: SQLite has no external dependencies.
Transactional: All transactions in SQLite are fully ACID-compliant. It means all queries and
changes are Atomic, Consistent, Isolated, and Durable.
In other words, all changes within a transaction take place completely or not at all even when
an unexpected situation like application crash, power failure, or operating system crash occurs.
Single Database File: An SQLite database is a single ordinary disk file that can be located
anywhere in the directory hierarchy. If SQLite can read the disk file then it can read anything in
the database. If the disk file and its directory are writable, then SQLite can change anything in
the database. Database files can easily be copied onto a USB memory stick or emailed for
sharing.

Creation and Connection of the Database

Computer Department, Jamia Polytechnic, Akkalkuwa 91


Mobile Application Development Unit-V: Activity and Multimedia with Databases

1. The package imported into the application is android.database.sqlite.SQLiteDatabase.


2. Here the class used is SQLiteDatabase.
3. The method used to create the database or connect to the database is
openOrCreateDatabase() method.

Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS USERS(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO USERS VALUES('admin','admin');");

This will insert some values into our table in our database.
Another way to insert values is by using ContentValues class instance. Its put() method can be
used to hold values. Later insert() method of SQLiteDatabase class can be called to insert values
in the table.
The syntax of put() is as follows:
public void put (String key, String value)
where
key is String: the name of the value (table column name) to put
value is String: the data for the value (table column name) to put i.e. value for column
Note: Second parameter data type will be changed according to column values e.g.
Short, Long, Double, Integer, Float, Boolean, Byte
The syntax of insert is as follows:
public long insert (String table, String nullColumnHack, ContentValues values)
where
table is String: the table name into which row will be inserted
nullColumnHack is String: optional; may be null
values is an object of ContentValues
e.g.

Computer Department, Jamia Polytechnic, Akkalkuwa 92


Mobile Application Development Unit-V: Activity and Multimedia with Databases

ContentValues c = new ContentValues();


c.put(“Username”, ”User1”);
c.put(“Password”, ”Password1”);
db.insert(“USERS”, null, c);

where USERS is table name and db is an instance of SQLiteDatabase class.

Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to
the table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from USERS",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);

There are other functions available in the Cursor class that allows us to effectively retrieve the
data. That includes

Sr.No Method & Description


1 getColumnCount()
This method return the total number of columns of the table.
2 getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the
column
3 getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the
column
4 getColumnNames()
This method returns the array of all the column names of the table.

Computer Department, Jamia Polytechnic, Akkalkuwa 93


Mobile Application Development Unit-V: Activity and Multimedia with Databases

5 getCount()
This method returns the total number of rows in the cursor
6 getPosition()
This method returns the current position of the cursor in the table
7 isClosed()
This method returns true if the cursor is closed and return false otherwise

Android SQLiteOpenHelper
Android has features available to handle changing database schemas, which mostly depend on
using the SQLiteOpenHelper class.
SQLiteOpenHelper is designed to get rid of two very common problems.
1. When the application runs the first time – At this point, we do not yet have a database. So
we will have to create the tables, indexes, starter data, and so on.
2. When the application is upgraded to a newer schema – Our database will still be on the old
schema from the older edition of the app. We will have option to alter the database schema to
match the needs of the rest of the app.
SQLiteOpenHelper wraps up these logic to create and upgrade a database as per our
specifications. For that we’ll need to create a custom subclass of SQLiteOpenHelper
implementing at least the following three methods.
• Constructor
• onCreate(SQLiteDatabase db)
• onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

Extracting values from a Cursor


• Cursors store query result records in rows and grant meaning methods to access and
iterate through the records

Computer Department, Jamia Polytechnic, Akkalkuwa 94


Mobile Application Development Unit-V: Activity and Multimedia with Databases

• Cursors should be closed when no longer used, and can be deactivated with a call to
Cursor.deactivate() statement when the application pauses or exits.
• On resume the Cursor.requery() statement is executed to re-enable the Cursor with
fresh data. These functions can be managed by the parent Activity by calling
startManagingCursor().

Iterating through records:


The cursor class provides methods to iterate through Cursor data easily.
Methods:
abstract boolean move(int offset)
Move the cursor by a relative amount, forward or backward, from the current position.
abstract boolean moveToFirst()
Move the cursor to the first row.
abstract boolean moveToLast()
Move the cursor to the last row.
abstract boolean moveToNext()
Move the cursor to the next row.
abstract boolean moveToPosition(int position)
Move the cursor to an absolute position.
abstract boolean moveToPrevious()
Move the cursor to the previous row.

To find the position of Cursor following methods can be used:


abstract boolean isAfterLast()
Returns whether the cursor is pointing to the position after the last row.
abstract boolean isBeforeFirst()
Returns whether the cursor is pointing to the position before the first row.
abstract boolean isFirst()
Returns whether the cursor is pointing to the first row.

Computer Department, Jamia Polytechnic, Akkalkuwa 95


Mobile Application Development Unit-V: Activity and Multimedia with Databases

abstract boolean isLast()


Returns whether the cursor is pointing to the last row.

The getXxx(int columnIndex) methods can be used to get the value of requested column index.
e.g.
abstract float getFloat(int columnIndex)
Returns the value of the requested column as a float.
abstract int getInt(int columnIndex)
Returns the value of the requested column as an int.
abstract long getLong(int columnIndex)
and so on for each supported data type.

Transactions
When we want to execute a series of queries that either all complete or all fail, at that situation
we use transactions which is supported by SQLite.
When a SQLite transaction fails, an exception will be thrown.
There are three methods available in transaction for all part of the database object.
a. beginTransaction(): Start a transaction
b. setTransactionSuccessful(): Execute the queries and call we want to commit the transaction
c. endTransaction(): Complete the transaction

Program for SQLite using SQLiteOpenHelper:


Following program adds and displays student data.
MainActivity.java
This activity displays two buttons to add and show records in the database using
activity_main.xml file.
package com.jamiapolytechnic.databaseexample;

import androidx.appcompat.app.AppCompatActivity;

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

Computer Department, Jamia Polytechnic, Akkalkuwa 96


Mobile Application Development Unit-V: Activity and Multimedia with Databases

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


private Button addButton;
private Button showButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addButton = (Button) findViewById(R.id.add_record);
showButton = (Button) findViewById(R.id.show_record);

addButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent addIntent = new Intent(MainActivity.this,
AddStudentActivity.class);
startActivity(addIntent);
}
});
showButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent showIntent = new Intent(MainActivity.this,
ShowStudentActivity.class);
startActivity(showIntent);
}
});
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" >

<Button
android:id="@+id/add_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Add Record" />

<Button
android:id="@+id/show_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Computer Department, Jamia Polytechnic, Akkalkuwa 97


Mobile Application Development Unit-V: Activity and Multimedia with Databases

android:layout_gravity="center"
android:text="Show Record" />

</LinearLayout>

AddStudentActivity.java
This activity displays two edit text views to accept two values from user, it has one button to
save data. Its layout file is add_layout.xml.
package com.jamiapolytechnic.databaseexample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddStudentActivity extends AppCompatActivity {

private Button saveButton;


private EditText nameEditText;
private EditText yearEditText;

private DBManager dbManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Add Record");
setContentView(R.layout.add_layout);

nameEditText = findViewById(R.id.name_edittext);
yearEditText = findViewById(R.id.year_edittext);
saveButton = findViewById(R.id.save_record);

dbManager = new DBManager(this);


dbManager.open();
saveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
final String sname = nameEditText.getText().toString();
final String syear = yearEditText.getText().toString();
if(sname.equals("")||syear.equals("")){
Toast.makeText(getApplicationContext(),"Please enter both
values",Toast.LENGTH_LONG).show();

}
dbManager.insert(sname, syear);
Toast.makeText(getApplicationContext(),"Record
Saved",Toast.LENGTH_SHORT).show();
nameEditText.setText("");
yearEditText.setText("");

Computer Department, Jamia Polytechnic, Akkalkuwa 98


Mobile Application Development Unit-V: Activity and Multimedia with Databases

}
});
}
@Override
protected void onStop(){
super.onStop();
dbManager.close();
}

add_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" >

<EditText
android:id="@+id/name_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Name" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/year_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Year e.g. FYCO" >
</EditText>

<Button
android:id="@+id/save_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Save" />

</LinearLayout>

ShowStudentActivity.java
This activity displays one text view to display the data from table. Its layout file is
show_layout.xml.

Computer Department, Jamia Polytechnic, Akkalkuwa 99


Mobile Application Development Unit-V: Activity and Multimedia with Databases

package com.jamiapolytechnic.databaseexample;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.os.Bundle;
import android.widget.TextView;

public class ShowStudentActivity extends AppCompatActivity {

private TextView tv;


private DBManager dbManager;
String str="Name\t\t\t\tYear";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Show Record");
setContentView(R.layout.show_layout);

tv = (TextView) findViewById(R.id.empty);

dbManager = new DBManager(this);


dbManager.open();
Cursor cursor = dbManager.fetch();
while(cursor.isAfterLast()==false){
str = str + "\n" + cursor.getString(0) + "\t\t\t\t\t\t" +
cursor.getString(1);
cursor.moveToNext();
}
tv.setText(str);
}
@Override
protected void onStop(){
super.onStop();
dbManager.close();
}
}

show_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical">
<TextView
android:id="@+id/empty"

Computer Department, Jamia Polytechnic, Akkalkuwa 100


Mobile Application Development Unit-V: Activity and Multimedia with Databases

android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No Records" />
</ScrollView>

</LinearLayout>

DatabaseHelper.java
This is sub-class of SQLiteOpenHelper, used to create database and table.
package com.jamiapolytechnic.databaseexample;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {


// Table Name
public static final String TABLE_NAME = "STUDENTS";
// Table columns
public static final String SNAME = "sname";
public static final String SYEAR = "syear";
// Database Information
static final String DB_NAME = "Database.DB";
// database version
static final int DB_VERSION = 2;
// Creating table query
private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" +
SNAME + " TEXT NOT NULL, " + SYEAR + " TEXT);";

public DatabaseHelper(Context context) {


super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}

DBManager.java
This class is used to insert the record in database table and create a Cursor to retrieve data
from database table.

Computer Department, Jamia Polytechnic, Akkalkuwa 101


Mobile Application Development Unit-V: Activity and Multimedia with Databases

package com.jamiapolytechnic.databaseexample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DBManager {


private DatabaseHelper dbHelper;
private Context context;
private SQLiteDatabase database;

public DBManager(Context c) {
context = c;
}

public DBManager open() throws SQLException {


dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}

public void close() {


dbHelper.close();
}

public void insert(String sname, String syear) {


ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SNAME, sname);
contentValue.put(DatabaseHelper.SYEAR, syear);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
}

public Cursor fetch() {


String[] columns = new String[] { DatabaseHelper.SNAME, DatabaseHelper.SYEAR
};
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null,
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}

AndroidManifest.xml
In this file, add the details of two more activities created i.e. AddStudentActivity and
ShowStudentActivity.

Computer Department, Jamia Polytechnic, Akkalkuwa 102


Mobile Application Development Unit-V: Activity and Multimedia with Databases

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamiapolytechnic.databaseexample">

<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>
<activity android:name=".AddStudentActivity" android:label="Add New Student">
</activity>
<activity android:name=".ShowStudentActivity" android:label="Show Records">
</activity>
</application>

</manifest>

.oOo. End of Unit V .oOo.

Computer Department, Jamia Polytechnic, Akkalkuwa 103

You might also like