0% found this document useful (0 votes)
20 views63 pages

Chapter 5 - Activity and Multimedia With Database

Chapter 5 discusses the use of Intents in Android for communication between application components, detailing explicit and implicit intents. It covers the implementation of these intents in activities, the structure of Intent Filters, and the Activity Lifecycle. Additionally, it explains Broadcast Receivers, including their creation and registration for system events.

Uploaded by

ishikagajbhiye47
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)
20 views63 pages

Chapter 5 - Activity and Multimedia With Database

Chapter 5 discusses the use of Intents in Android for communication between application components, detailing explicit and implicit intents. It covers the implementation of these intents in activities, the structure of Intent Filters, and the Activity Lifecycle. Additionally, it explains Broadcast Receivers, including their creation and registration for system events.

Uploaded by

ishikagajbhiye47
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/ 63

Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach

Solution Pvt Ltd 1

Chapter 5 Activity and Multimedia with Databases


Intent in Android

 Android uses Intent for communicating between the Application


components like Activity, Services, Broadcast Receiver and Content
Provider

 Intent is used for passing the information among Activities in an


Application and from one app to another also.

 Intent also provides the connectivity between two apps.

 By calling, startActivity() method you can perform this task.

Intent intent = new Intent(MainActivity.this, SecondActivity.class);

startActivity(intent);

 In the above example, foreground activity is getting redirected to another activity


i.e. SecondActivity.java.
 Some of the General functions of Intent are:
o Start Service
o Launch Activity
o Display the web page
o Display the contact list
o Message Broadcasting

Types of Intents:

Intent are of two types: Explicit Intent and Implicit Intent

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 2

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.
Explicit Intents

Intent intent = new Intent(MainActivity.this, SecondActivity.class);

startActivity(intent);

Here SecondActivity is the JAVA class name where the activity will now be
navigated.
Implicit Intent

 In Implicit Intents we do need to specify the name of the component. We just specify the
Action which has to be performed and further this action is handled by the component of
another application.
 The basic example of implicit Intent is to open any web page
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(“https://www.mountreachsolutions.com”));
startActivity(intent)
 Unlike Explicit Intent you do not use any class name to pass through Intent().

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 3
Example
 First design the text view displaying basic details of the App
 Second design the two button of Explicit Intent Example and Implicit Intent

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16sp"
android:gravity="center">

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnexplitcit"
android:text="Explicit Example"
android:textSize="32sp"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnimplitcit"
android:text="Implicit Example"
android:textSize="32sp"
android:layout_marginTop="40sp"/>

</LinearLayout>

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 4

Step 2: Implement onClick event for Implicit And Explicit Button inside MainActivity.java
package com.mountreachsolution.madbatch2025;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


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

btnExplicit = findViewById(R.id.btnexplitcit);
btnImplicit = findViewById(R.id.btnimplitcit);

btnExplicit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
});
btnImplicit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 5
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
}
});
}
}

Step 3: activity_second.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Second Activity"
android:textSize="32sp"
android:textStyle="bold"
android:textAlignment="center"
/>
</LinearLayout>

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 6
Second Activity:

package com.mountreachsolution.madbatch2025;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toast.makeText(this, "Second Activity", Toast.LENGTH_SHORT).show();
}
}

Output:

Now run the above program in your Emulator. The App will look like this:

First Click on Explicit Intent Example. The SecondActivity will be open within the App:

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 7

Now go back in Emulator and click on Implicit Intent Example. The


www.google.com homepage will open in Browser (make sure you have internet):

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 8

INTENT FILTER

 Intent filters specify the type of intents that an Activity, service or Broadcast
receiver can respond to.

 Intent Filter are the components which decide the behavior of an intent.

 An Intent Filter declare the capabilities of its parent components i.e Activity,
Service or broadcast receiver.

 We can declare an Intent Filter for an Activity in manifest file.

 The code of Intent Filter is used inside AndroidManifest.xml file for an activity.

Intent filter Attributes:-

icon: This is displayed as icon for activity.

label: The label / title that appears at top in Toolbar of that particular Activity.

priority: This is another important attribute in Intent filter used in broadcasting.

 There are following three elements in an intent filter:


o Action
o Data
o Category
Important Note: Every intent filter must contain action element in it. Data and
category element is optional for it.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 9

Action:
 It represent an activities action, what an activity is going to do.
 An Intent Filter element must contain one or more action element.
 It is declared with the name attribute and prefix android.intent.action as give
below
Exa mp le : -
<intent- filter>
<action android:name=”android.intent.action.MAIN”/>
</intent-filter>
 Android.intent.action.MAIN means that this activity is the entry point of the
application, When you launch the application this activity is created.

 There are more actions similar to above like ACTION_VIEW,ACTION_SEND,


ACTION_MAIN, ACTION_WEB_SEARCH and many more.
<action android:name=”android.intent.action.VIEW”/>
<action android:name=”android.intent.action.SEND”/>

Data

 There are two forms in which you can pass the data, using URI(Uniform Resource
Identifiers) or MIME type of data.

The syntax of data attribute is as follows:

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 10

The <data> element can have several attributes to filter specific data:
1. android:scheme – Specifies the URI scheme (e.g., http, https, tel, mailto, content, file).
2. android:host – Defines the host part of the URI (e.g., www.example.com).
3. android:port – Specifies the port number.
4. android:path – Defines the exact path in the URI.
5. android:pathPattern – A pattern for matching paths (e.g., /user/*).
6. android:pathPrefix – Matches the beginning of the path (e.g., /user matches /user/123).
7. android:mimeType – Defines the type of data the component can handle (e.g., image/*,
text/plain).

Category:

 Category attribute of Intent filter dictates the behavior or nature of an Intent.

 There is a string which contains some additional information about the intent
which will be handled by a component.

 The syntax of category is as follows:


<intent- filter>
<category android:name=”android.intent.category.LAUNCHER”/>
</intent-filter>

 Category for example: CATEGORY_BROWSABLE, CATEGORY_LAUNCHER.

BROWSABLE – Browsable category, activity allows itself to be opened with


web browser to open the reference link provided in data.

LAUNCHER – Launcher category puts an activity on the top of stack,


whenever application will start, the activity containing this category will be
opened first.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 11

ACTIVITY LIFECYCLE
 Activity is a screen that user interact with.
 Every Activity in android has lifecycle like created, started, resumed, paused, stopped or
restarted,destroyed.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 12
Short description of Activity Lifecycle example:
onCreate() – Called when the activity is first created.
onStart() – Called just after it’s creation or by restart method after onStop().
Here Activity start becoming visible to user
onResume() – Called when Activity is visible to user and user can interact with it
onPause() – : Called once another activity gets into the foreground.Called when
Activity content is not visible because user resume another activity
onStop() – Called when activity is not visible to user because some other activity
takes place of it
onRestart() – Called when user comes on screen or resume the activity which
was stopped
onDestroy – Called when Activity is not in background

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 13

BROADCAST RECEIVERS

 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.
 In android, Broadcast Receiver is implemented as a subclass of
BroadcastReceiver and each broadcast is delivered as an Intent object.

 There are following two important steps to make BroadcastReceiver for the
system broadcasted Intent
1. Creating Broadcast Receiver
2. Registering Broadcast Receiver
Creating Broadcast Receiver
 A broadcast receiver is implemented as a subclass of BroadcastReceiver and
override the onReceive Method where each message is received as Intent object
Parameter
 This Method is triggered when the receiver receive a broadcast.
 You also have an Intent object and Context passed as parameter in the onReceive
callback
public class MyReceiver extends BroadcastReceiver
{
@override
Public void onReceiver(Context context, Intent intent)
{
Toast.makeText(context,”Intent Detect”,Toast.LENGTH_LONG).show();
}
}

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 14

Registering Broadcast Receiver


 An Application listens for specific broadcast intents by registering a broadcast
receiver in AndroidManifest.xml
 Consider we are going to register MyReceiver for system generated event
ACTION_BOOT_COMPLETED which is fired by the system once the Android
system has completed the boot process.

Broadcast Receiver
<application

android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.MADBatch2025">

<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name ="android.intent.action.BOOT_COMPLETED"/>

</intent-filter>
</receiver>
</application>

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 15

Event name and Description

Intent Description Of Event

Indicates low battery


android.intent.action.BATTERY_LOW :
condition on the device.

This is broadcast once after


android.intent.action.BOOT_COMPLETED the system has finished
booting

To perform a call to someone


android.intent.action.CALL
specified by the data

Indicates that the date has


android.intent.action.DATE_CHANGED
changed

Indicates that the device has


android.intent.action.REBOOT
been a reboot

The mobile network or wifi


android.net.conn.CONNECTIVITY_CHANGE connection is changed(or
reset)

This indicates that airplane


android.intent.ACTION_AIRPLANE_MODE_CHANGED mode has been switched on or
off.

activity_main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 16
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</ LinearLayout >

MainActivity.java
import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

AirplaneModeChangeReceiver airplaneModeChangeReceiver = new AirplaneModeChangeReceiver();

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

@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airplaneModeChangeReceiver, filter);
}

@Override
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 17
protected void onStop() {
super.onStop();
unregisterReceiver(airplaneModeChangeReceiver);
}
}

AirplaneModeChangeReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.widget.Toast;

public class AirplaneModeChangeReceiver extends BroadcastReceiver {

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

if (isAirplaneModeOn(context.getApplicationContext())) {
Toast.makeText(context, "AirPlane mode is on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "AirPlane mode is off", Toast.LENGTH_SHORT).show();
}
}

private static boolean isAirplaneModeOn(Context context) {


return Settings.System.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}

FRAGMENT

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 18
 In Android, the fragment is the part of the Activity that represents a portion of the
User Interface(UI) on the screen.

 It is the modular section of the Android activity that is very helpful in creating UI
designs that are flexible in nature and auto-adjustable based on the device screen size.

 <fragment> tag is used to insert the fragment in an android activity layout. By dividing
the activity’s layout multiple fragments can be added in it.

 the fragment is also termed a sub-activity.

Fragment Life Cycle

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 19

1) onAttach(Activity) :- it is called only once when it is attached with activity.


2) onCreate(Bundle):- It is used to initialize the fragment.
3) onCreateView(LayoutInflater, ViewGroup, Bundle):- creates and returns view hierarchy.
4) onActivityCreated(Bundle):- It is invoked after the completion of onCreate() method.
5) onViewStateRestored(Bundle):- t provides information to the fragment that all the saved state
of fragment view hierarchy has been restored.
6) onStart():- makes the fragment visible.
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 20
7) onResume():- makes the fragment interactive.
8) onPause():- is called when fragment is no longer interactive.
9) onStop():- is called when fragment is no longer visible.
10) onDestroyView():- allows the fragment to clean up resources.
11) onDestroy():- allows the fragment to do final clean up of fragment state.
12) onDetach():- It is called immediately prior to the fragment no longer being associated with its
activity.

Example:-
activity_main:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<fragment
android:id="@+id/fragment1"
android:name="com.mountreach.madbatch2025.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>

<fragment
android:id="@+id/fragment2"
android:name="com.mountreach.madbatch2025.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>

</LinearLayout>

fragment_1.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 21
android:layout_width="match_parent"
android:layout_height="match_parent">

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


<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />

</FrameLayout>

fragment_2.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

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


<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />

</FrameLayout>

MainActivity.java
package com.mountreach.madbatch2025;
//package packnamename;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends


AppCompatActivity {

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

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 22
setContentView(R.layout.activity_main);
}
}

Fragment1.java
package com.mountreach.madbatch2025;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

public class Fragment1 extends Fragment {

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

Fragment2.java
package com.mountreach.madbatch2025;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

public class Fragment2 extends Fragment {

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 23
@Override
public View onCreateView(LayoutInflater
inflater, ViewGroup container,
Bundle
savedInstanceState) {
// Inflate the layout for this fragment
return
inflater.inflate(R.layout.fragment_2, container,
false);
}
}

Output:-

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 24
ANDROID SERVICE

Q.Describe the service life cycle with its diagram - 4 M


 Android service is a component that is used to perform long running operations in
background such as playing music, handle network transactions, interacting content
providers etc.
 Service is subclass of ContextWrapper class.

Feature of Service:
 Service is an Android Component without an UI
 Services run indefinitly unless they are explicitly stopped or destroyed
 It can be started by any other application component.
 Components can even infact bind to a service to perform Interprocess- Comminication
 It stops itself by calling stopself() or is stopped by a Android component by calling
stopService().

Android platform service

 The Android platform provides and runs predefined system services and every
Android application can use them, given the right permissions.

 These system services are usually exposed via a specific Manager class.

 Access to them can be gained via the getSystemService() method.

 Example:
 Vibrator Service-
 Location Service
 WiFi Service
 Audio Service
 Notification Service

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 25
Life Cycle of Android Service

 There can be two forms of a service.The lifecycle of service can follow two
different paths: started or bound.

 Started
 Bound

1) Started Service
 A service is started when component (like activity) calls startService() method,
now it runs in the background indefinitely.
 It is stopped by stopService() method.
 The service can stop itself by calling the stopSelf() method.

2) Bound Service
 A service is bound when another component (e.g. client) calls bindService() method
 The client can unbind the service by calling the unbindService() method.
 The service cannot be stopped until all clients unbind the service.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 26
63
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach Solution Pvt Ltd

onCreate()

 This is the first callback which will be invoked when any component starts the service.
 If the same service is called again while it is still running this method wont be invoked.

onStartCommand()

 This callback is invoked when service is started by any component by calling startService().

onBind()

 This is invoked when any component starts the service by calling onBind.

onUnbind()

 This is invoked when all the clients are disconnected from the service.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 27
onRebind()

 This is invoked when new clients are connected to the service. It is called after onUnbind

onDestroy()

 This is a final clean up call from the system. This is invoked just before the service is being
destroyed.

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">

<Button
android:id="@+id/buttonStart”
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service" />

<Button
android:id="@+id/buttonStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service" />

<Button
android:id="@+id/buttonNext "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 28
android:text="Next Page" />
</LinearLayout>

activity_next.xml
It contains only one textview displaying the message Next Page
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 29
66
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach Solution Pvt Ltd

android:layout_height="match_parent" >

<TextView android:id="@+id/textVie w"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NextPage"
/>
</LieanrLayout >

Service class
Now create the service implemenation class by inheriting the Service class and
overridding its callback methods.

MyService.java
Package example.javatpoint.com.androidservice;

import android.app.Service;

import android.content.Intent;

import android.media.MediaPlayer;

import android.os.IBinder; import


android.support.annotation.Nullable;
import android.widget.Toast;

public class MyService extends Service {

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 30

MediaPlayer myPlayer;
@Nullable
@Override
public IBinder onBind(Intent
intent) { return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();

myPlayer = MediaPlayer.create(this, R.raw.sun);


myPlayer.setLooping(false); // Set looping
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
myPlayer.start();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show(); myPlayer.stop();
}
}

Activity class

Now create the MainActivity class to perform event handling. Here, we are
writing the code to start and stop service. Additionally, calling the second
activity on buttonNext.

MainActivity.java
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 31
package example.javatpoint.com.androidservice;

import android.content.Intent;
import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import
android.widget.Button;

public class MainActivity extends AppCompatActivity implements


View.OnClickListener{

Button buttonStart, buttonStop,buttonNext;

@Override
protected void onCreate(Bundle savedInstanceState) {

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

buttonStart = findViewById(R.id.buttonStart);
buttonStop = findViewById(R.id.buttonStop);
buttonNext = findViewById(R.id.buttonNext);

buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
buttonNext.setOnClickListener(th is);

}
public void onClick(View src)
{
switch (src.getId())
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 32
{
case R.id.buttonStart:

startService(new Intent(this, MyService.class));

break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class)); break;
case R.id.buttonNext:
Intent intent=new Intent(this,NextPage.class);
startActivity(intent);
break;
}
}
}

NextPage class
Now, create another activity.
File: NextPage.java

package xample.javatpoint.com.androidservice; import

android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class NextPage extends AppCompatActivity {

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

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 33

Declare the Service in the AndroidManifest.xml file Finally, declare the service in
the manifest file.
File: AndroidManifest.xml

Let's see the complete AndroidManifest.xml file

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.javatpoint.com.androidservice">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launc
her"
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=".NextPage"></activity>
<service

android:name=".MyService "
android:enabled="true" />
</application>
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 34
</manifest
> Output:

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 35

ANDROID MULTIMEDIA FRAMEWORK


 Android multimedia framework is designed to provide a reliable interface for java
service.
 The Android Multimedia framework is a set of APIs for developers which enables
them to create a multimedia application on an android platform.
 This framework provides support for audio, video, and images, which provides a range of
features such as media playback, recording, editing, streaming, etc.
 It is a system that includes multimedia applications, frameworks, an OpenCore engine,
hardware devices for audio/video/ input, output devices.
 It also consist several core dynamic libraries such as libmedia, libmediaplayservices, and so
on.
Example:-
Playing a Video (YouTube App)
When you play a video on YouTube, the following processes take place:
YouTube App (Multimedia Application) -The user opens the app and selects a
video to play.
Android Multimedia Framework - The framework decodes the video and displays
it on the screen.
OpenCore Engine - Handles video streaming, buffering, and processing.
Hardware Devices (GPU, Audio System) - The screen displays the video while the
speakers play the sound.
Core Libraries (libmedia, libmediaplayservices) - These libraries manage video
decoding, audio synchronization, and playback.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 36
A general multimedia framework architecture is shown in Figure

 Java Class call the Native C library Libmedia throught Media 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
Multiplemedia application
 The whole communication between Libmedia and Media Server forms a Client/Server
model.
 In Media Server guard process, it calls OpenCore multimedia engine to realize the
specific multimedia processing functions. And the OpenCore engine refers to the
PVPlayer and PVAuthor.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 37
-
MEDIAPLAYER CLASS
PLAY AUDIO AND VIDEO
 MediaPlayer Class in Android is used to play media files like Audio and Video File
 In Android by using MediaPlayer class we can easily fetch,decode and play both audio
and
Video file with minimal setup
 Android provides many ways to control playback of audio/video files and streams. One
of this way is through a class called MediaPlayer.
 In order to use MediaPlayer, we have to call a static Method create() of this class.
Syntax:-
MediaPlayer mediaplayer = MediaPlayer.create(this, R.raw.song);
o The Second parameter is the name of the song that you want to play

 Once you have created the MediaPlayer object you can call some methods to start or stop
the music
o mediaPlayer.start()
o mediaPlayer.stop()

Methods of MediaPlayer class


There are many methods of MediaPlayer class. Some of them are as follows:
public void start() It starts or resumes the playback.
public void stop() It stops the playback.
public void pause() It pauses the playback.
public boolean isPlaying() Checks if media player is playing.
public void seekTo(int millis) Seeks to specified time in miliseconds.
public void setLooping(boolean looping) Sets the player for looping or non-looping.
public boolean isLooping() Checks if the player is looping or non-
looping.
public void selectTrack(int index) It selects a track for the specified index.
public int getCurrentPosition() Returns the current playback position.
public int getDuration() Returns duration of the file.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 38
public void setVolume(float Sets the volume on this player.
leftVolume,float rightVolume)

Activity class

File: MainActivity.java
package com.example.audiomediaplayer1;

importandroid.media.MediaPlayer;

import android.net.Uri;

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

public class MainActivity extends Activity

{ @Override

protected void onCreate(Bundle savedInstanceState) {


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

MediaPlayer mp=new MediaPlayer();


try{
mp.setDataSource("/sdcard/Music/maine.mp3");//Write your location here
mp.prepare();
mp.start();

}catch(Exception e){e.printStackTrace();}
}
}
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 39

Example :-

main_activity.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:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="Audio and Video Controller using MediaPlayer Class"
android:textAlignment="center"
android:textSize="32sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20sp"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16sp"
android:text="start" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16sp"
android:text="pause" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16sp"
android:text="stop" />
</LinearLayout>
<VideoView
android:id="@+id/videoView1"
android:layout_width="match_parent"
android:layout_height="350sp"
/>
</LinearLayout>

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 40
MainActivity.java
package com.mountreach.madbatch2025;
//package packnamename;

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

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

Button start, pause, stop;


VideoView videoView;
MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
videoView = (VideoView) findViewById(R.id.videoView1);

start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//creating media player
mp = MediaPlayer.create(MainActivity.this, R.raw.meethi_boliyaan);
Toast.makeText(MainActivity.this, "Music Start", Toast.LENGTH_SHORT).show();
if (!mp.isPlaying()) {
mp.start();
String videoPath = "android.resource://" + getPackageName() +
"/raw/meethi_boliyaan_video";
videoView.setVideoPath(videoPath);
videoView.start();
}
}
});

pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Music Pause", Toast.LENGTH_SHORT).show();
if (mp.isPlaying()) {
mp.pause();
videoView.pause();
}
}
});

stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Music Stop", Toast.LENGTH_SHORT).show();
if (mp.isPlaying()) {
mp.stop();
videoView.stopPlayback();

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 41
}

}
});
}
}

 Create raw Directory and Paste your mp3 and mp4 sond inside this

Output:-

TEXT TO SPEECH

 In android, by using TextToSpeech class we can easily convert our text into voice
and it supports different types of speaking languages.

 We can choose the speaking language based on our requirements in the android
application.

 The android TextToSpeech instance can only be used to synthesize text once it
has completed its initialization.

 In order to use this class, you need to instantiate an object of this class

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 42
 also specify the initListener to notify the completion of initialization.

 During the initialization, we can set the audio pitch rate, audio speed, type of
language to speak, etc. based on our requirements.

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

Sr.No Method & description

1 speak()

speak the text.

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 stop()

This method stop the speak.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 43
acitivity_main.xml
Example:-
<?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:layout_margin="30dp">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Text to Speech"
android:textSize="36sp" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Text"
android:layout_marginBottom="20dp"
android:hint="Enter your text"
android:gravity="center"
android:textSize="16dp"
android:layout_marginTop="16sp"/>

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

</LinearLayout>

MainActivity.java
package com.mountreach.madbatch2025;
//package packnamename;

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

public class MainActivity extends AppCompatActivity {


//
// Button start, pause, stop;
// VideoView videoView;
// MediaPlayer mp;

EditText Text;
Button btnText;
TextToSpeech textToSpeech;

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 44
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Text = findViewById(R.id.Text);
btnText = findViewById(R.id.btnText);

textToSpeech = new TextToSpeech(getApplicationContext(), new


TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
if(i!=TextToSpeech.ERROR){
// To Choose language of speech
textToSpeech.setLanguage(Locale.UK);
}
}
});
btnText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

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

Output:-

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 45

ANDROID SENSOR
 List different types of sensors used in android. S-23 2 Marks
 Write a program to display the list of sensors supported by device. S-24 6 Marks

 Sensors can be used to monitor the three-dimensional device movement or


change in the environment of the device.

 Android provides sensor api to work with different types of sensors.

 Most of the android devices have built-in sensors that measure motion,
orientation, and various environmental condition.

 For Example, to report changes in the environment a weather application might


use a temprerature sensor and humadity sensor

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 46

Types of Sensors
Android supports three types of sensors:
o Motion Sensors
 These are used to measure acceleration forces and rotational forces along with
three axes.
 Motion sensors are useful for monitoring device movement such as
tilt,shake,rotation or swing
o Position Sensors
 These are used to measure the physical position of device.
 These sensors are use for applications related to navigation, augmented reality (AR),
and location-based services
o Environmental Sensors
 These are used to measure the environmental changes such as temperature, humidity etc.

 The important classes and interfaces of sensor api are as follows:


SensorManager class
 SensorManager class provides methods to get sensor instance, to access and list
sensors,to register and unregister sensor listeners etc.
 You can get the instance of SensorManager by calling the method getSystemService()
and passing the SENSOR_SERVICE constant in it.
Example:-
SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor class
 The Sensor class provides methods to get information of the sensor such as sensor name,
sensor type, sensor resolution, sensor type etc.

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 47

Example:-
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="16dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List of Sensors in Your Device"
android:textSize="18sp"
android:textStyle="bold"
android:paddingBottom="10dp" />

<ListView
android:id="@+id/sensorListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

MainActivity.xml
package com.mountreach.madbatch2025;
//package packnamename;

import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

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

// Get the ListView reference


ListView sensorListView = findViewById(R.id.sensorListView);

// Get SensorManager instance


SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

// Get the list of sensors


List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);

// Convert sensor list to string list


ArrayList<String> sensorNames = new ArrayList<>();
for (Sensor sensor : sensorList) {
sensorNames.add(sensor.getName());
}

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 48

// Set up the adapter to display the sensor list


ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, sensorNames);
sensorListView.setAdapter(adapter);
}
}

Output:-

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 49

ASYNCTASK

 Android AsyncTask is an abstract class provided by Android which gives us the


liberty to perform heavy tasks in the background

 and keep the UI thread light thus making the application more responsive.

 Android application runs on a single thread when launched.

 Due to this single thread model tasks that take longer time to fetch the response
can make the application non- responsive.

 To avoid this we use android AsyncTask to perform the heavy tasks in


background on a dedicated thread and passing the results back to the UI thread.

 Hence use of AsyncTask in android application keeps the UI thread responsive


at all times.

The three generic types used in an android AsyncTask class are given below: -
 Params : The type of the parameters sent to the task upon execution
 Progress : The type of the progress units published during the background computation
 Result : The type of the result of the background computation

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 50

CAMERA IN ANDROID
Q) Write a program to capture an image using camera and display it. 6 Marks s-22

 In Android, Camera is a hardware device that allows capturing pictures and videos
in your applications.

 Android provides the facility to work on camera by 2 ways:


o By Camera Intent
o By Camera API

1. Using Camera By Using Camera Application


 We can capture pictures without using the instance of Camera class.
 Here you will use an intent action type of
MediaStore.ACTION_IMAGE_CAPTURE to launch an existing Camera
application on your phone.
 In Android MediaStore is a type of DataBase which stores pictures and videos
in android.

Intent cameraIntent = new


Intent(android.provider.MediaStore.ACTION_IMAGE_CAPT
U RE);
2. Using Camera By using Camera Api
 This class is used for controlling device cameras.
 It can be used to take pictures when you are building a camera application.
 Camera API works with Camera Manager, CameraDevice, CaptureRequest,
CameraCaptureSession, CameraCaptureSession.CaptureCallback
 Camera Permission Declarations In Manifest
o <uses-permission android:name="android.permission.CAMERA"/>

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 51

Example
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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CAMERA"
android:textSize="20dp"
android:gravity="center"
android:layout_marginTop="20sp"
/>

<ImageView
android:id="@+id/image"
android:layout_width="250dp"
android:layout_height="250sp"
android:scaleType="fitXY"
android:src="@drawable/captureimage"
android:layout_gravity="center"/>

<Button
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAKE PHOTO"
android:layout_gravity="center"/>
</LinearLayout>

MainActivity.class
package com.mountreach.madbatch2025;
//package packnamename;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


Button b1;
ImageView imageView;
int CAMERA_REQUEST=1;

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

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 52
b1=findViewById(R.id.photo);
imageView=findViewById(R.id.image);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,CAMERA_REQUEST);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA_REQUEST)
{
Bitmap image= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(image);
}
}
}

Output:-

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 53
ANDROID BLUETOOTH
Q) Elaborate the need of permissions in Android. Explain the permissions to set
system functionalitics like SEND-SMS, bluetooth. W-22 4 Marks
Q) Design an android application to show the list of paired devices by Bluetooth. 6 M S-23
Q) Develop a program to TURN ON and OFF bluetooth. Write .java file and permission tags W-23
6 Marks

 Bluetooth is a way to exchange data with other devices wirelessly.


 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 several tasks such as:
o Scan bluetooth devices
o Get a list of paired devices
o Connect to other device throught service discovery
o Connect and transfer data from and to other devices
o Manage multiple connections.
 Android Bluetooth API
The android.bluetooth package provides a lot of interfaces classes to work with bluetooth
such as:
o BluetoothAdapter
o BluetoothDevice
o BluetoothSocket
o BluetoothServerSocket
o BluetoothClass
o BluetoothProfile
o BluetoothHeadset
o BluetoothHealth

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 54

BluetoothAdapter class
 Android Provides BluetoothAdapter class to communicate with Bluetooth.
 By the help of BluetoothAdapter class, we can perform fundamental tasks such as
initiate device discovery, query a list of paired (bonded) devices, create a
BluetoothServerSocket instance to listen for connection requests etc.
 Its Syntax is give below
Private BluetoothAdapter BA
BA = BluetoothAdapter.getDefaultAdapter();

AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
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:gravity="center">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List all Paired devices"
android:onClick="list"
android:id="@+id/button1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView1"
android:textColor="#ff34ff06"
android:textSize="25dp"
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
/>
</LinearLayout>

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 55

MainActivity.class
package com.mountreach.madbatch2025;
//package packnamename;

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

public class MainActivity extends AppCompatActivity {

Button b1;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
ListView lv;

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

b1 = (Button) findViewById(R.id.button1);
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}

public void list(View v){


pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired
Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1, list);

lv.setAdapter(adapter);

}
}

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 56

Output:-

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 57

SQLite
Q) Describe with example, how to create a simple database in SQLite (Assume
suitable data) s- 22 4 marks
Q) Develop an android application for taking student feedback with database
connectivity. S-23 6 Marks
Q) Develop an application to store customer's details like, customer-id, customer-name,
mobile number, address, pin-code and retrieve customer information using customer-id
in SQLite databases.
(Any other relevant logic can be considered) w-22 6 Marks
Q) Write significance of SQLite database in android. S-24 4 Marks

 SQLite is an open source lightweight relational database management(RDBMS)


to perform database operation, such as storing, updating, retrieving data from the
database
 By default, Android comes with build in SQlite Database support so we don’t need to
do any configuration
 Just like we save the files on the device ‘s internal storage , Android stores our
database in a private disk space and data is secure because by default this area is not
accessible to other application
 The Package android.database.sqlite containts all the required APIs to use an SQLite
database in our android application

Creating Database and Tables using SQLiteOpenHelper

 In Android by using SQLiteOpenHelper class we can easily create the required


database and tables for our application.
 To use SQLiteOpenHelper, we need to create a subclass that override the onCreate()
d onUpgrade() call back method.
 First we need to create a constructor of SQLiteOpenHelper
SQLiteOpenHelper(Context context, String name, CursoreFactory factory,int version)

SQLiteDatabase class
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 58
 It Containt method to be performed on SQLite Database such as create, update,
delete,select etc.
 To use these method, we need to instantiaste SQLiteDatabase as follow
SQLiteDatabase db;
Note:- Before you can use this,you must import the android.database.sqlite.SQLiteDatabase
namespace in your application

Method of SQLiteDatabase Class


There are many method in SQLiteDatabase class
1) void execSQL(String sql) :- executes the sql query not select query.

2) long insert() :- inserts a record on the database.


3) int update() :- update the row
4) Cursor query() :- returns a cursor over the resultset.

Example:-
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:gravity="center">

<Button
android:text="Create SQLite Database"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:id="@+id/button" />

</LinearLayout>

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 59

MainActivity.java
package com.mountreach.madbatch2025;
//package packnamename;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

SQLiteDatabase sqLiteDatabaseObj;
Button btnCreatedatabse;

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

btnCreatedatabse = (Button)findViewById(R.id.button);
btnCreatedatabse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
} });
}
}

Output:-

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 60

Example 2:-
Develop an application to store customer's details like, customer-id, customer-name,
mobile number, address, pin-code and retrieve customer information using customer-
id in SQLite databases. (Any other relevant logic can be considered)

<?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:gravity="center">

<TextView
android:text="Insert Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="@+id/textView"
android:gravity="center"
android:textSize="20dp"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="ID"
android:id="@+id/editid"
android:layout_below="@+id/textView"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"
android:layout_below="@+id/editid"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Mobile No."
android:id="@+id/editmobile"
android:layout_below="@+id/editname"/>

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Address"
android:lines="3"
android:id="@+id/editaddress"
android:layout_below="@+id/editmobile"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Pin Code"
android:id="@+id/editpincode"
android:layout_below="@+id/editaddress"/>
<Button
android:text="Insert Data"
MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 61
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editpincode"
android:layout_centerHorizontal="true"
android:id="@+id/button" />
<TextView
android:text="Search Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:id="@+id/textView1"
android:gravity="center"
android:textSize="20dp"
android:layout_below="@+id/button"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter ID"
android:id="@+id/editsearchid"
android:layout_below="@+id/textView1"/>

<Button
android:text="Search Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editsearchid"
android:layout_centerHorizontal="true"
android:id="@+id/button1" />

</LinearLayout>

MainActivity:-
package com.mountreach.madbatch2025;
//package packnamename;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

SQLiteDatabase sqLiteDatabaseObj;
EditText editTextID, editTextName, editMobileNo, editAddress, editPincode,
editSearchid;
String cid, cname, cmobile, caddress, cpincode, sql_query, sid;
Button EnterData, SearchData;

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

EnterData = (Button) findViewById(R.id.button);


MR. NIKHIL SHENDE |
Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 62
SearchData = (Button) findViewById(R.id.button1);
editTextID = (EditText) findViewById(R.id.editid);
editTextName = (EditText) findViewById(R.id.editname);
editMobileNo = (EditText) findViewById(R.id.editmobile);
editAddress = (EditText) findViewById(R.id.editaddress);
editPincode = (EditText) findViewById(R.id.editpincode);
editSearchid = (EditText) findViewById(R.id.editsearchid);
EnterData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS " +
"AndroidJSonTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
" cid VARCHAR, name VARCHAR, mobile VARCHAR, address VARCHAR,
pincode VARCHAR);");
cid = editTextID.getText().toString();
cname = editTextName.getText().toString();
cmobile = editMobileNo.getText().toString();
caddress = editAddress.getText().toString();
cpincode = editPincode.getText().toString();
sql_query = "INSERT INTO AndroidJSonTable (cid, name, mobile, address,
pincode) " +
"VALUES('" + cid + "', '" + cname + "', '" + cmobile + "', '" +
caddress + "', '" + cpincode + "');";
sqLiteDatabaseObj.execSQL(sql_query);
Toast.makeText(getApplicationContext(), "Data Inserted Successfully",
Toast.LENGTH_LONG).show();
}
});
SearchData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sid = editSearchid.getText().toString();
Cursor cursor = sqLiteDatabaseObj.rawQuery("select * from AndroidJSonTable
where cid=" + sid + "", null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()) {
String cid = cursor.getString(1);
String name = cursor.getString(2);
String mob = cursor.getString(3);
String addr = cursor.getString(4);
String pcode = cursor.getString(5);
buffer.append(cid + " " + name + " " + mob + " " + addr + " " + pcode +
"\n");
Toast.makeText(getApplicationContext(), buffer,
Toast.LENGTH_LONG).show();
}
}
});
}
}

MR. NIKHIL SHENDE |


Chapter 5 Activity and Multimedia with Databases by Nikhil Shende – Mountreach
Solution Pvt Ltd 63

Output:-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy