0% found this document useful (0 votes)
21 views89 pages

CH 5 0203 PDF

Chapter 5 discusses the Android Activity Lifecycle, Intents (both implicit and explicit), and how to create and manage them. It also covers Broadcast Receivers, Content Providers, Fragments, and Services, detailing their roles, lifecycles, and how to implement them in Android applications. The chapter provides essential code snippets and explanations for each component's functionality and interaction within an Android app.

Uploaded by

Sanket Karade
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)
21 views89 pages

CH 5 0203 PDF

Chapter 5 discusses the Android Activity Lifecycle, Intents (both implicit and explicit), and how to create and manage them. It also covers Broadcast Receivers, Content Providers, Fragments, and Services, detailing their roles, lifecycles, and how to implement them in Android applications. The chapter provides essential code snippets and explanations for each component's functionality and interaction within an Android app.

Uploaded by

Sanket Karade
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/ 89

Institute of Civil and Rural Engineering, Gargoti

Department: Computer Engineering

Chapter – 5
ACTIVITY AND MULTIMEDIA WITH
DATABASES
 Android Activity Lifecycle is controlled by 7 methods of
android.app.Activity class.
 The android Activity is the subclass of ContextThemeWrapper class.
 An activity is the single screen in android. It is like window or frame of Java.
 By the help of activity, you can place all your UI components or widgets in
a single screen.
Intent

 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.
Implicit Intent

 The implicit intent is the intent where instead of defining the exact
components, you define the action that you want to perform for different
activities.
 An Implicit intent specifies an action that can invoke any app on the
device to be able to perform an action.
 Using an Implicit Intent is useful when your app cannot perform the action
but other apps probably can and you’d like the user to pick which app to
use.
 Syntax:
Intent i=new Intent();
i.setAction(Intent.ACTION_SEND);
 Create an Implicit Intent

 You need to make an Intent object. The constructor of the Implicit Intent's
object needs a type of action you want to perform.

 An action is a string that specifies the generic action to be performed. The


action largely determines how the rest of the intent is structured, particularly
the information that is contained as data and extras in the intent object. For
example,

 ACTION_VIEW: This action is used when you have some information that an
activity can show to the user, such as a photo to view in a Gallery app, or an
address to view in a Map app.
 ACTION_SEND: This action is used when you have some data that the user can
share through another app, such as an Email app or some Social Networking
app.
 ACTION_DIAL: Display the phone dialer with the given number filled in.

 Intent i = new Intent(Intent.ACTION_VIEW);


 You need to provide some data for the action to be performed. Data is
typically expressed as a URI(Uniform Resource Identifier) which provides data to
the other app so that any other app which is capable of handling the URI data
can perform the desired action. For example, if you want to open a website
through your app, you can pass the Uri data using setData() method as follows:

i.setData(Uri.parse("http://www.google.co.in"));

 Call startActivity() method in the end with the intent object as the parameter.

startActivity(i);
Explicit Intent

 When you explicitly define which Android component should be opened


on some user action, then you use explicit intents.
 You generally use an explicit intent to start a new component in your own
app, because you know which exact activity or service you want to start.
 For example, you can start a new activity in response to a user action or
start a service to download a file in the background.
 Create an Explicit Intent
 You need to make an Intent object. The constructor of the Explicit Intent's
object needs two parameters as follows:
 Context c: This represents the object of the Activity from where you are calling the
intent.
 Java file name: This represents the name of the java file of the Activity you want to
open.
 Note: You need to mention the java file name with .class extension

Intent i = new Intent(this, MyJavaFile.class);


 Call startActivity() method and pass the intent's object as the parameter. This
method navigates to the java file mentioned in the Intent's object.
startActivity(i);
 If you need to pass some information or data to the new Activity you are
calling, you can do this by calling putExtra() method before the startActivity()
method. This method accepts key-value pair as its parameter.
i.putExtra("key1", "I am value1");
i.putExtra("key2", "I am value2");
startActivity(i);
o Note: To receive the data in the new Activity and use it accordingly, you need
to call the getIntent() method and then getStringExtra() method in the java
class of the Activity you want to open through explicit intent. getStringExtra()
method takes the key as the parameter
String a = getIntent().getStringExtra("key1");
o Doing this, stores the value stored at key1 into the string variable a.
Intent Filter

 Intent Filter is an expression in app’s manifest file (ActivityMainfest.xml)


and it is used to specify the type of intents that the component would like
to receive. In case if we create Intent Filter for an 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.

 Generally, the Intent Filters (<intent-filter>) whatever we define in manifest


file can be nested in the corresponding app components and we can
specify the type of intents to accept using these three elements.
<action>

It defines the name of an intent action to be accepted and it must be a literal string
value of an action, not the class constant.

<category>

It defines the name of an intent category to be accepted and it must be the literal
string value of an action, not the class constant.

<data>

It defines the type of data to be accepted and by using one or more attributes we
can specify various aspects of the data URI (scheme, host, port, path) and MIME type.
Broadcast Intent

 Android apps can send or receive broadcast messages from the Android
system and other Android apps.
 For example, the Android system sends broadcasts when various system
events occur, such as when the system boots up or the device starts
charging.
System Broadcast
Broadcast Receiver

 Broadcast Receivers simply respond to broadcast messages from other applications or from the
system itself. These messages are sometime called events or intents.

 There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
 Creating the Broadcast Receiver.
 Registering Broadcast Receiver
 Creating the Broadcast Receiver
 A broadcast receiver is implemented as a subclass of BroadcastReceiver class
and overriding the onReceive() method where each message is received as a
Intent object parameter.

public class MyReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
 Registering Broadcast Receiver
 A BroadcastReceiver can be registered in two ways.
 By defining it in the AndroidManifest.xml file as shown below.
<receiver android:name=".ConnectionReceiver" >
<intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
 By defining it programmatically
Following snippet shows a sample example to register broadcast receiver
programmatically.
IntentFilter filter = new IntentFilter();
intentFilter.addAction(getPackageName() +
"android.net.conn.CONNECTIVITY_CHANGE");
MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);
 To unregister a broadcast receiver in onStop() or onPause() of the activity the following
snippet can be used.
@Override
protected void onPause()
{
unregisterReceiver(myReceiver);
super.onPause();
}

 The following table lists a few important system events.


android.intent.action.BATTERY_CHANGED

android.intent.action.BATTERY_LOW

android.intent.action.BATTERY_OKAY

android.intent.action.BOOT_COMPLETED

android.intent.action.BUG_REPORT

android.intent.action.CALL

android.intent.action.CALL_BUTTON

android.intent.action.DATE_CHANGED

android.intent.action.REBOOT
 Broadcasting Custom Intents
 If you want your application itself should generate and send custom intents
then you will have to create and send those intents by using
the sendBroadcast() method inside your activity class.
 If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning
the Intent you are sending stays around after the broadcast is complete.

 The following snippet is used to send an intent to all the related


BroadcastReceivers.

Intent intent = new Intent();


intent.setAction("com.journaldev.CUSTOM_INTENT");
sendBroadcast(intent);

 Don’t forget to add the above action in the intent filter tag of the manifest or
programmatically.
Content Provider

 Content Provider will act as a central repository to store the applications


data in one place and make that data available for different applications
to access whenever it’s required.
 In android, we can configure Content Providers to allow other
applications securely access and modify our app data based on our
requirements.
 In android, we can use content provider whenever we want to share our
app data with other apps and it allow us to make a modifications to our
application data without effecting other applications which depends on
our app.
 In android, content provider is having different ways to store app data.
 The app data can be stored in a SQLite database or in files or even over a
network based on our requirements.
 By using content providers we can manage data such as audio, video, images
and personal contact information.

 Access Data from Content Provider

 To access a data from content provider, we need to use ContentResolver


object in our application to communicate with the provider as a client.
 The ContentResolver object will communicate with the provider object
(ContentProvider) which is implemented by instance of class.
 Generally, in android to send a request from UI to ContentResolver we have
another object called CursorLoader which is used to run the query
asynchronously in background.
 In android application the UI components such as Activity or Fragment will call
a CursorLoader to query and get a required data from ContentProvider using
ContentResolver.
 The ContentProvider object will receive a data requests from client, performs
the requested actions (create, update, delete, retrieve) and return the result.
 Content URIs
 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
 content:// - The string content:// is always present in the URI and it is used to
represent the given URI is a content URI.
 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.tutlane.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.
 Creating a Content Provider

 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.
 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.
Fragment

 Android Fragment is the part of activity, it is also known as sub-activity. There can be more than
one fragment in an activity. Fragments represent multiple screen inside one activity.
 Android fragment lifecycle is affected by activity lifecycle because fragments are included in
activity.
 Each fragment has its own life cycle methods that is affected by activity life cycle because
fragments are embedded in activity.
 The FragmentManager class is responsible to make interaction between fragment objects
The lifecycle of
android
fragment is like
the activity
lifecycle. There
are 12 lifecycle
methods for
fragment.
 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.
 Basic Fragment Code In XML:
<fragment
android:id="@+id/fragments"
android:layout_width="match_parent"
android:layout_height="match_parent" />
 Creating a Fragment in Android
 Extend Fragment class.
 Provide appearance in XML or Java.
 Override onCreateView to link the appearance.
 Use the Fragment in your activity.
 There are three methods, at a minimum, that we need to implement for a
fragment.
 onCreate(): This method is called when the fragment is created by Android System.
 onCreateView(): This method is called when the user interface for the fragment needs
to be drawn for the first time. This method returns a view.
 onPause(): This method is called when the user is leaving the fragment.
Service

 Android service is a component that is used to perform operations


on the background such as playing music, handle network
transactions, interacting content providers etc.
 It doesn't has any UI (user interface).
 The service runs in the background indefinitely even if application is
destroyed.
 Moreover, service can be bounded by a component to perform
interactivity and inter process communication (IPC).
 In android, the life cycle of service will follow two different
paths Started or Bound.
 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

 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.
 Android Services Lifecycle Diagram
 Create a Service
Generally, in android to create a
service we must create a subclass of
Service or use one of existing
subclass. In android the application
component such as an activity can
start the service by calling
startService() which results in calling
the service’s onStartCommand()
method.
 Register a Service in Manifest File
 Once we create a service, we must need to register that in android manifest file
using <service> element like as shown below.
<manifest ... >
...
<application ... >
<service android:name=".SampleService" />
</application>
...
</manifest>
 Start a Service
 In android, the component such as an activity, service or receiver can start the
service using startService() method. Following is the sample code snippet of
starting a service using startService method.
Intent intent = new Intent(this, MyService.class);
startService(intent);
 Android Service Callback Methods
methods
. Description

onStartCommand() • The Android service calls this method when a


component(eg: activity)
• requests to start a service using startService().
Once the service is started,
• it can be stopped explicitly using stopService()
or stopSelf() methods.

onBind() • The system will invoke this method when an


another component wants to bind with the
service by calling bindService().
• During implementation of this method, we must
need to provide an interface to the clients to
communicate with the service by returning an
IBinder object.
• In android, we must need to implement this
method, in case if we don’t need to allow
binding, then we should return NULL
onDestroy()
 The system will invoke this method when the service is no
longer used and is being destroyed. This is the final call that
the service will receive and we need to implement this
method in our service to clean up any unused resources
such as threads, receivers or listeners.
onUnbind()
 The system calls this method when all clients are
disconnected from a particular interface published by the
service.

onRebind()
 Calls this method when new clients are connected to the
service after it had previously been notified that all are
disconnected in onUnbind(Intent).
Multimedia Framework

 The following classes are used to play sound and video in the Android
framework:
MediaPlayer
 This class is the primary API for playing sound and video.
AudioManager
 This class manages audio sources and audio output on a device.
 Manifest declarations:
 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, uses the MediaPlayer.setScreenOnWhilePlaying() or
MediaPlayer.setWakeMode() methods, you must request this permission.
<uses-permission android:name="android.permission.WAKE_LOCK" />
Play Audio

 It supports several different media sources such as:


 Local resources

MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);


mediaPlayer.start(); // no need to call prepare(); create() does that for you
 Internal URIs, such as one you might obtain from a Content Resolver
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();

 External URLs (streaming)


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();
Play Video

 In android, by using VideoView component and MediaController class we can easily


implement the video player in android applications to play the videos with multiple
playback options, such as play, pause, forward, backward, etc.

 Generally, the MediaController class in android will provide a playback options for video
player, such as play, pause, backward, forward, etc.

 The VideoView class in android will provide a functionalities to fetch and play the videos
using video player with minimal setup in android applications.
 Following is the code snippet, to use VideoView and MediaController classes
to implement video player in android application to play videos based on our
requirements.

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


MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video1);
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
 VideoView class provides a different type of methods to control video files based
on requirements.
TextToSpeech

 In android, you can convert your text into speech by the help of TextToSpeech class.
 Constructor of TextToSpeech class
 TextToSpeech(Context context, TextToSpeech.OnInitListener)
 You need to implement TextToSpeech.OnInitListener interface, for performing event handling
on TextToSpeech engine.
 There is only one method in this interface.
Methods of TextToSpeech class
Sensors

 Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device
Types of Sensors

 The Android platform supports three broad categories of sensors:


 Motion sensors : These are used to measure acceleration forces and
rotational forces along with three axes.

 Environmental sensors :These are used to measure the environmental


changes such as temperature, humidity etc.

Position sensors These sensors measure the physical position of a device.
The important classes and interfaces
of sensor api are as follows:

1) SensorManager class
The android.hardware.SensorManager class provides methods :

You can get the instance of SensorManager by calling the method


getSystemService() and passing the SENSOR_SERVICE constant in it
SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
2) Sensor class
The android.hardware.Sensor class provides methods to get
information of the sensor such as sensor name, sensor type, sensor
resolution, sensor type etc.
 The sensors referenced through the Sensor class may be of two types:
 Raw sensors (hardware-based) give raw data from a sensor, and one raw sensor
corresponds to one actual physical component inside the Android device.
Sensor.TYPE_LIGHT
Sensor.TYPE_PROXIMITY
Sensor.TYPE_PRESSURE
Sensor.TYPE_TEMPERATURE (deprecated)
Sensor.TYPE_ACCELEROMETER
Sensor.TYPE_GYROSCOPE
Sensor.TYPE_MAGNETIC_FIELD
Sensor.TYPE_RELATIVE_HUMIDITY
Sensor.TYPE_AMBIENT_TEMPERATURE
 Composite sensors (software-based) provide an abstraction layer between application
code and low-level device components by either combining the raw data of multiple
raw sensors, or by modifying the raw sensor data to make it easier to consume.
Sensor.TYPE_ROTATION_VECTOR
Sensor.TYPE_LINEAR_ACCELERATION
Sensor.TYPE_GRAVITY
Sensor.TYPE_ORIENTATION (deprecated)
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
Sensor
SensorEvent

SensorEventListener : It provides two call back methods to get information


when sensor values (x,y and z) change or sensor accuracy changes

 3) SensorEvent class
 Its instance is created by the system. It provides information about the sensor.
AsyncTask

 Your UI runs on a single thread to interact with the user -- this is the main
thread. Therefore all code will run in this thread which might result in poor
performance if you have a computationally intensive operation that
could be run in another thread; for example, if your code is loading a file
over the Internet you UI is completely blocked.
 The solution to this is simple: If you have computationally demanding
functions or slow running operations the best solution if to run
those tasks asynchronously from the UI threads
 There are two way to do background processing in android
usingASyncTask or using loader framework
 AsyncTask is an abstract class, which means you must subclass it in order to use it. In
this example the AsyncTask performs a very simple background task.
 An AsyncTask subclass has the following methods for performing work off of the main
thread:
 onPreExecute(): This method runs on the UI thread, and is used for setting up your task
(like showing a progress bar).
 doInBackground(Params)This is where you implement the code to execute the work
that is to be performed on the separate thread.
 onProgressUpdate(Progress…) This is invoked on the UI thread and used for updating
progress in the UI (such as filling up a progress bar)
 onPostExecute(Result) Again on the UI thread, this is used for updating the results to the
UI once the AsyncTask has finished loading.
 When you create an AsyncTask subclass, you may need to give it information about
the work which it is to perform, whether and how to report its progress, and in what
form to return the result.
 When you create an AsyncTask subclass, you can configure it using these parameters:

1. Params: The data type of the parameters sent to the task upon executing the
doInBackground() override method.
2. Progress: The data type of the progress units published using the onProgressUpdated()
override method.
3. Result: The data type of the result delivered by the onPostExecute() override method.
 Android AsyncTask Example
 To start an AsyncTask the following snippet must be present in the MainActivity class :
MyTask myTask = new MyTask();
myTask.execute();
 In the above snippet we’ve used a sample classname that extends AsyncTask and execute
method is used to start the background thread.
class DoSomeTask extends AsyncTask{
protected void onPreExecute() {
//Setup precondition to execute some task
}
protected String doInBackground(String... params) {
//Do some task
}
protected void onProgressUpdate(Integer... values) {
//Update the progress of current task
}
protected void onPostExecute(String s) {
//Show the result obtained from doInBackground
}
}
Bluetooth

 Bluetooth is a communication network protocol, which allow a devices to


connect wirelessly to exchange the data with other Bluetooth devices.
 By using android Bluetooth API’s in android applications, we can perform
following functionalities.
Scan for the available Bluetooth devices within the range
Use local Bluetooth adapter for paired Bluetooth devices
Connect to other devices through service discovery
Transfer data to and from other devices
Manage multiple connections
 To transfer the data between two Bluetooth devices, first they must establish a
communication channel using pairing process.
 The devices which we are going to pair must be discoverable and should accept the
incoming connection requests.
 Generally, the devices will find the discoverable devices using a service discovery
process. Once the device accepts the pairing request, the two devices will exchange
a security keys to complete the bonding process and the devices will cache these
security keys for later use.
 Once the pairing and bonding process completes, the devices are ready to
exchange the required information.
 When the session is complete, the device that initiated the pairing request will release
the channel that linked to the discoverable device.
 The two devices remain bonded, so they can reconnect automatically during a future
session as long as they're in the range of each other.
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.

 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>
v Android provides BluetoothAdapter class to communicate with Bluetooth.
Create an object of this calling by calling the static method
getDefaultAdapter().
Syntax: private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
v 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);

BluetoothAdapter class provides many constants. Some of them are as follows:

String ACTION_REQUEST_ENABLE-
String ACTION_REQUEST_DISCOVERABLE-This constant is used for turn on discovering of bluetooth
String ACTION_DISCOVERY_STARTED
String ACTION_DISCOVERY_FINISHED
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();

 Commonly used methods of BluetoothAdapter class are as follows:


1. boolean enable()- enables the bluetooth adapter if it is disabled.
2. boolean isEnabled() returns true if the bluetooth adapter is enabled.
3. boolean disable() disables the bluetooth adapter if it is enabled.
4. String getName() returns the name of the bluetooth adapter.
5. boolean setName(String name) changes the bluetooth name.
6. int getState() returns the current state of the local bluetooth adapter.
7. Set<BluetoothDevice> getBondedDevices() returns a set of paired (bonded) BluetoothDevice
objects.
8. boolean startDiscovery() starts the discovery process.
Audio Capture

 In android, MediaRecorder class will provide a functionality to record audio or video files.

 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();
 other methods listed in the MediaRecorder class

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

 The Android framework supports capturing images and video through the
android.hardware.camera2 API or camera Intent.
 Here are the relevant classes:
 android.hardware.camera2: This package is the primary API for controlling device cameras. It
can be used to take pictures or videos when you are building a camera application.
 Camera: This class is the older deprecated API for controlling device cameras.
 MediaRecorder: This class is used to record video from the camera.
 Intent: An intent action type of MediaStore.ACTION_IMAGE_CAPTURE or
MediaStore.ACTION_VIDEO_CAPTURE can be used to capture images or videos without directly
using the Camera object.
 Following is the code snippet to capture the pictures using intent object with action
parameter MediaStore.ACTION_IMAGE_CAPTURE in android applications.
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
 The startActivityForResult() method with MediaStore.ACTION_IMAGE_CAPTURE intent
action parameter to capture the photos. The second parameter Image_Capture_Code
is a locally defined integer that must be greater than 0.
 Manifest declarations
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 Following is the code snippet to capture the pictures using intent object with action
parameter MediaStore.ACTION_IMAGE_CAPTURE in android applications.
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
 The startActivityForResult() method with MediaStore.ACTION_IMAGE_CAPTURE intent
action parameter to capture the photos. The second parameter Image_Capture_Code
is a locally defined integer that must be greater than 0.
 Manifest declarations
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
SQLite Database

 Android SQLite is a very lightweight database which comes with Android OS.
 Once a database is created successfully its located in data/data//databases/ accessible from
Android File Explorer.
 SQLite is a typical relational database, containing tables (which consists of rows and columns),
indexes etc.
 We can create our own tables to hold the data accordingly. This structure is referred to as
a schema.
 The package android.database.sqlite contains all the required API’s to use SQLite database in
our android applications.
SQLiteOpenHelper class

 The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version


management.
 For performing any database operation, you have to provide the implementation of onCreate()
and onUpgrade() methods of SQLiteOpenHelper class.
 Constructors of SQLiteOpenHelper class
 Methods of SQLiteOpenHelper class
SQLiteDatabase class
 It contains methods to be performed on sqlite database such as create, update, delete,
select etc.
 Methods of SQLiteDatabase class
 Database – Creation
 In order to create a database you just need to call this method openOrCreateDatabase
with your database name and mode as a parameter.
 It returns an instance of SQLite database which you have to receive in your own object.
 Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
 Apart from this , there are other functions available in the database package , that does
this job.
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler
errorHandler)
This method only opens the existing database with the appropriate flag mode. The common flags
mode could be OPEN_READWRITE OPEN_READONLY
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
It is similar to the above method as it also opens the existing database but it does not define any
handler to handle the errors of databases
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method is equivalent to openDatabase
method.
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
This method is similar to above method but it takes the File object as a path rather then a string. It is
equivalent to file.getPath()
 Opening and Closing Android SQLite Database Connection
 Before performing any database operations like insert, update, delete records in a table,
first open the database connection by calling getWritableDatabase() method as shown
below:
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
 The dbHelper is an instance of the subclass of SQLiteOpenHelper. To close a database
connection the following method is invoked.
dbHelper.close();
 Database - Insertion
 To 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 TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
 The following code snippet shows how to insert a new record in the android
SQLite database.
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
}

Content Values creates an empty set of values using the given initial size
 Updating Record in Android SQLite database table
 SQLite UPDATE Query is used to modify the existing records in a table. You can use WHERE
clause with UPDATE query to update selected rows, otherwise all the rows would be
updated.
 Following is the basic syntax of UPDATE query with WHERE clause.
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

 You can combine N number of conditions using AND or OR operators.


 The following snippet shows how to update a single record.
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID +
" = " + _id, null);
return i;
}
 SQLite DELETE Query is used to delete the existing records from a table. You can use
WHERE clause with DELETE query to delete the selected rows, otherwise all the
records would be deleted.
 Following is the basic syntax of DELETE query with WHERE clause.
DELETE FROM table_name
WHERE [condition];
 Just need to pass the id of the record to be deleted as shown below.
public void delete(long _id)
{
database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
}
 Cursor Class
 Cursors are what contain the result set of a query made against a database in Android.
 Once a cursor has been returned from a database query, an app needs to iterate over
the result set and read the column data from the cursor.
 Internally, the cursor stores the rows of data returned by the query along with a position
that points to the current row of data in the result set.
 When a cursor is returned from a query() method, its position points to the spot before the
first row of data. This means that before any rows of data can be read from the cursor,
the position must be moved to point to a valid row of data.
 The Cursor class provides the following methods to manipulate its internal position:
 boolean Cursor.move(int offset): Moves the position by the given offset
 boolean Cursor.moveToFirst(): Moves the position to the first row
 boolean Cursor.moveToLast(): Moves the position to the last row
 boolean Cursor.moveToNext(): Moves the cursor to the next row relative to the current
position
 boolean Cursor.moveToPosition(int position): Moves the cursor to the specified position
 Cursor.moveToPrevious(): Moves the cursor to the previous row relative to the current
position
 There are other functions available in the Cursor class that allows us to
effectively retrieve the data. That includes
getColumnCount():This method return the total number of columns of the table.
getColumnIndex(String columnName): This method returns the index number of a
column by specifying the name of the column
getColumnName(int columnIndex):This method returns the name of the column by
specifying the index of the column
getColumnNames():This method returns the array of all the column names of the table.
getCount(): This method returns the total number of rows in the cursor
getPosition():This method returns the current position of the cursor in the table
isClosed(): This method returns true if the cursor is closed and return false otherwise
 Database – Fetching
 To 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 TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
Transactions
 A transaction is a unit of work that is performed against a database. Transactions are
units or sequences of work accomplished in a logical order, whether in a manual fashion
by a user or automatically by some sort of a database program.
 A transaction is the propagation of one or more changes to the database.
 Properties of Transactions
 Transactions have the following four standard properties, usually referred to by the
acronym ACID.
 Atomicity − Ensures that all operations within the work unit are completed successfully;
otherwise, the transaction is aborted at the point of failure and previous operations are
rolled back to their former state.
 Consistency − Ensures that the database properly changes states upon a successfully
committed transaction.
 Isolation − Enables transactions to operate independently of and transparent to each
other.
 Durability − Ensures that the result or effect of a committed transaction persists in case of
a system failure.
 Transaction Control
 Following are the commands used to control transactions:
BEGIN TRANSACTION − To start a transaction.
COMMIT − To save the changes, alternatively you can use END TRANSACTION command.
ROLLBACK − To rollback the changes.

 In Android, the SQLiteDatabase class contains the following methods to support


transaction processing:
void beginTransaction(): Begins a transaction
void setTransactionSuccessful(): Indicates that the transaction should be committed
void endTransaction(): Ends the transaction causing a commit if
setTransactionSuccessful() has been called
 Transaction Example
SQLiteDatabase db = getDatabase();
db.beginTransaction();
try {
// insert/update/delete
// insert/update/delete
// insert/update/delete
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}

You might also like