CH 5 0203 PDF
CH 5 0203 PDF
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
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.
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.
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
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.
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.
Don’t forget to add the above action in the intent filter tag of the manifest or
programmatically.
Content Provider
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
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
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
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.
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
1) SensorManager class
The android.hardware.SensorManager class provides methods :
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
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
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();
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
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];