Unit 5
Unit 5
5
Activity and multimedia with
database
Intent
• Android Intent is the message that is passed between components such as activities, content providers,
broadcast receivers, services etc.
• It is generally used with startActivity() method to invoke activity, broadcast receivers etc.
• The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do
action.
2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class to be
invoked.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
Activity Lifecycle:-
• Android Activity Lifecycle is controlled by 7 methods
of android.app.Activity class. The android Activity is
the subclass of ContextThemeWrapper class.
Method Description
onCreate called when activity is first created.
onStart called when activity is becoming visible to the user.
onResume called when activity will start interacting with the user.
onPause called when activity is not visible to the user.
onStop called when activity is no longer visible to the user.
onRestart called after your activity is stopped, prior to start.
onDestroy called before the activity is destroyed.
Method Description
onCreate called when activity is first created.
not visible yet Syntax Of onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //the activity is being created.
}
The Android system controls the life cycle of a broadcast receiver. It starts the receiver when an intent is
broadcast and then kills it once the onReceive() method returns. The system may also kill a receiver if it
has been idle for too long.
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.
• For example, applications can also initiate broadcasts to let other applications know that some
data has been downloaded to the device and is available for them to use, so this is broadcast
receiver who will intercept this communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
● Creating the Broadcast Receiver.
● Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents then you will
have to create and broadcast those intents.
Creating the Broadcast Receiver
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver MyReceiver and
implemented logic inside onReceive() will be executed.
Intent filter
An intent filter declares the capabilities of its parent component — what an activity or service can
do and what types of broadcasts a receiver can handle.
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
Fragments
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.
• A Fragment is a piece of an activity which enable more modular activity design.
• a fragment is a kind of sub-activity.
• A fragment has its own layout and its own behavior with its own life cycle callbacks.
• You can add or remove fragments in an activity while the activity is running.
• You can combine multiple fragments in a single activity to build a multi-pane UI.
• A fragment can be used in multiple activities.
• Fragment life cycle is closely related to the life cycle of its host activity which means when
the activity is paused, all the fragments available in the activity will also be stopped.
• A fragment can implement a behavior that has no user interface component.
• Fragments were added to the Android API in Honeycomb version of Android which API
version 11.
• You create fragments by extending Fragment class and You can insert a fragment into your
activity layout by declaring the fragment in the activity's layout file, as
a <fragment> element.
• The FragmentManager class is responsible to make interaction between fragment objects.
Fragment Life Cycle
● onAttach()The fragment instance is associated with an activity instance.The fragment and the
activity is not fully initialized. Typically you get in this method a reference to the activity which uses
the fragment for further initialization work.
● onCreate() The system calls this method when creating the fragment. You should initialize
essential components of the fragment that you want to retain when the fragment is paused or
stopped, then resumed.
● onCreateView() The system calls this callback when it's time for the fragment to draw its user
interface for the first time. To draw a UI for your fragment, you must return a View component
from this method that is the root of your fragment's layout. You can return null if the fragment does
not provide a UI.
● onActivityCreated() The onActivityCreated() is called after the onCreateView() method when the
host activity is created. Activity and fragment instance have been created as well as the view
hierarchy of the activity. At this point, view can be accessed with the findViewById() method.
example. In this method you can instantiate objects which require a Context object
● onResume()Fragment becomes active.
● onPause() The system calls this method as the first indication that the user is leaving the
fragment. This is usually where you should commit any changes that should be persisted beyond
the current user session.
● onStop()Fragment going to be stopped by calling onStop()
● onDestroyView()Fragment view will destroy after call this method
● onDestroy() onDestroy() called to do final clean up of the fragment's state but Not guaranteed
to be called by the Android platform.
Types of Fragments
● Single frame fragments − Single frame fragments are using for hand hold devices like mobiles,
here we can show only one fragment as a view.
● List fragments − fragments having special list view is called as list fragment
● Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment.
How to use Fragments?
A service is a component that runs in the background to perform long-running operations without
needing to interact with the user and it works even if application is destroyed.
2 Bound
A service is bound when an application component binds to it by calling bindService(). A bound
service offers a client-server interface that allows components to interact with the service, send
requests, get results, and even do so across processes with interprocess communication (IPC).
A service life cycle
To create an service, you create a Java class that extends the Service base class or one of its existing subclasses. The
Service base class defines various callback methods and the most important are given below.
Sr.No. Callback & Description
1 onStartCommand()
The system calls this method when another component, such as an activity, requests that the service be
started, by calling startService(). If you implement this method, it is your responsibility to stop the
service when its work is done, by calling stopSelf() or stopService() methods.
2 onBind()
The system calls this method when another component wants to bind with the service by
calling bindService(). If you implement this method, you must provide an interface that clients use to
communicate with the service, by returning an IBinder object. You must always implement this method,
but if you don't want to allow binding, then you should return null.
3 onUnbind()
The system calls this method when all clients have disconnected from a particular interface published by
the service.
4 onRebind()
The system calls this method when new clients have connected to the service, after it had previously
been notified that all had disconnected in its onUnbind(Intent).
5 onCreate()
The system calls this method when the service is first created using onStartCommand() or onBind(). This
call is required to perform one-time set-up.
6 onDestroy()
The system calls this method when the service is no longer used and is being destroyed. Your service
should implement this to clean up any resources such as threads, registered listeners, receivers, etc.
Camera
The following two ways, in which you can use camera in your application
● Using existing android camera application in our application
● Directly using Camera API provided by android in our application
EXTRA_SIZE_LIMIT:-It is used to specify the size limit of video or image capture size
6
Use the function startActivityForResult() to launch this activity and wait for its result.
Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity.
There are methods defined in the activity class that does the same job , but used when you are not calling from
the activity but from somewhere else. They are listed below
There are methods defined in the activity class that does the same job , but used when you are not calling from the activity
but from somewhere else. They are listed below
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);
Sr.No Constant & description
ACTION_REQUEST_DISCOVERABLE
1
This constant is used for turn on discovering of Bluetooth
ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed
ACTION_FOUND
3
This constant is used for receiving information about each device that is discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It
returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
A part form the parried Devices , there are other methods in the API that gives more control over Blueetooth.
Sr.No Method & description
6 getState() This method returns the current state of the Bluetooth Adapter.
7 startDiscovery() This method starts the discovery process of the Bluetooth for 120 seconds.
Sensor
Most of the android devices have built-in sensors that measure motion, orientation, and various environmental
condition. The android platform supports three broad categories of sensors.
● Motion Sensors
● Environmental sensors
● Position sensors
Some of the sensors are hardware based and some are software based sensors.
Whatever the sensor is, android allows us to get the raw data from these sensors and use it in our application.
For this android provides us with some classes.
1. Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use
sensors, first thing you need to do is to instantiate the object of SensorManager class. It can be achieved as
follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
2. The next thing you need to do is to instantiate the object of Sensor class by calling the getDefaultSensor()
method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
3. Once that sensor is declared , you need to register its listener and override two methods which are
onAccuracyChanged and onSensorChanged. Its syntax is as follows −
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
}
Getting list of sensors supported
You can get a list of sensors supported by your device by calling the getSensorList method, which will return a list
of sensors containing their name and version number and much more information. You can then iterate the list to
get the information.
setDuration(long duration)
2
This method sets the duration of an animation.
getDuration()
3
This method gets the duration which is set by above method
end()
4
This method ends the animation.
cancel()
5
This method cancels the animation.
In order to apply this animation to an object , we will just call the startAnimation() method of the
object. Its syntax is −
ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);
Android Multimedia
MediaPlayer:Audio
VideoView: Video
Recording Media
Android Media Player
• We can play and control the audio files in android by the help of MediaPlayer class.
MediaPlayer class
The android.media.MediaPlayer class is used to control the audio or video files.
Methods of MediaPlayer class
Method Description
public void setDataSource(String path) sets the data source (file path or http url) to use.
public void prepare() prepares the player for playback synchronously.
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.
public void setVolume(float leftVolume,float
rightVolume) sets the volume on this player.
Android Video Player
By the help of MediaController and VideoView classes, we can play the video files in
android.
MediaController class
The android.widget.MediaController is a view that contains media controls like
play/pause, previous, next, fast-forward, rewind etc.
VideoView class
The android.widget.VideoView class provides methods to play and control the video
player.
The commonly used methods of VideoView class are as follows:
Method Description
public void
setMediaController(MediaController sets the media controller to the video view.
controller)
public void setVideoURI (Uri uri) sets the URI of the video file.
public void start() starts the video view.
public void stopPlayback() stops the playback.
public void pause() pauses the playback.
public void suspend() suspends the playback.
public void resume() resumes the playback.
public void seekTo(int millis) seeks to specified time in miliseconds.
Android MediaRecorder
In android, you can convert your text into speech by the help of TextToSpeech
class. After completion of the conversion, you can playback or create the sound
file.
Constructor of TextToSpeech class
TextToSpeech(Context context, TextToSpeech.OnInitListener)
Methods of TextToSpeech class
Method Description
converts the text into speech. Queue Mode may be
int speak (String text, int queueMode, HashMap QUEUE_ADD or QUEUE_FLUSH. Request parameters
params) can be null, KEY_PARAM_STREAM,
KEY_PARAM_VALUME etc.
int setSpeechRate(float speed) it sets the speed for the speech.
int setPitch(float speed) it sets the pitch for the speech.
int setLanguage (Locale loc) it sets the locale specific language for the speech.
void shutdown() it releases the resource set by TextToSpeech Engine.
it interrupts the current utterance (whether played or
int stop() rendered to file) and discards other utterances in the
queue.
TextToSpeech.OnInitListener Interface
Method Description
Called to signal the completion of the
void onInit (int status) TextToSpeech engine initialization. The
status can be SUCCESS or ERROR.
Android SpeechToText
SQLite Database is an open-source database provided in Android which is used to store data
inside the user’s device in the form of a Text file.
We can perform so many operations on this data such as adding new data, updating,
reading, and deleting this data.
SQLite is an offline database that is locally stored in the user’s device and we do not have to
create any connection to connect to this database.
How Data is Being Stored in the SQLite Database?
Method Description
This method is used to get the Array of column names of our SQLite
getColumnNames() table.
getCount() This method will return the number of rows in the cursor.
isClosed() This method returns a Boolean value when our cursor is closed.
getColumnCount() This method returns the total number of columns present in our table.
getColumnName(in This method will return the name of the column when we passed the
t columnIndex) index of our column in it.
getColumnIndex(Str This method will return the index of our column from the name of the
ing columnName) column.
getPosition() This method will return the current position of our cursor in our table.
Database - Package
The main package is android.database.sqlite that contains the classes to manage your own databases
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);
functions available in the database package
Sr.No Method & Description
1 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
Another method that also does the same job but take some additional parameter is given below
5 getCount() This method returns the total number of rows in the cursor
6 getPosition() This method returns the current position of the cursor in the table
7 isClosed() This method returns true if the cursor is closed and return false otherwise
Database - Helper class
For managing all the operations related to the database , an helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and update of the database.
Its syntax is given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db)
{
}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
{
}
}
SQLite - Transactions
Transactional control commands are only used with DML commands INSERT, UPDATE,
and DELETE. They cannot be used while creating tables or dropping them because
these operations are automatically committed in the database.
BEGIN TRANSACTION Command
BEGIN;
or
BEGIN TRANSACTION;
COMMIT Command
COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.
COMMIT;
or
END TRANSACTION;
ROLLBACK Command
ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
ROLLBACK;
AsyncTasks in Android
• AsyncTask is an abstract class in Android that offers us the freedom to execute
demanding tasks in the background while keeping the UI thread light and the
application responsive.
• When launched, an Android application operates in a single thread. Due to this single-
thread approach, tasks that take a long time to fetch a response may cause the
program to become unresponsive.
• Android AsyncTask to perform these heavy tasks in the background on a separate
thread and return the results back to the UI thread in order to prevent this.
• As a result, the UI thread is always responsive when AsyncTask is used in an Android
application.
• The purpose of AsyncTask was to make it possible to use the UI thread correctly and
conveniently.
The three generic types utilized in an Android AsyncTask class:
•Params: Parameters sent to the task upon execution
•Progress: Progress units shared during the background computation
•Result: Result obtained from the background computation
The fundamental methods used in an Android AsyncTask class:
doInBackground():
The code that has to be run in the background is contained in the doInBackground() method.
The publishProgress() method in this method allows us to repeatedly deliver results to the UI
thread. We only need to use the return statements to signal that the background processing
has been finished.
onPreExecute():
The code that runs prior to the beginning of the background processing is contained in this
function.
onPostExecute():
After the doInBackground method has finished processing, the onPostExecute() method is
called. This method receives the output of the doInBackground method as its input.
onProgressUpdate():
This method can use the progress updates it receives from the publishProgress method,.
which publishes progress updates from the doInBackground function, to update the UI thread
Content Provider
Content Provider
• In Android, Content Providers are a very important component that serves the
purpose of a relational database to store the data of applications.
• The role of the content provider in the android system is like a central repository in
which data of the applications are stored, and it facilitates other applications to
securely access and modifies that data based on the user requirements.
• Android system allows the content provider to store the application data in several
ways. Users can manage to store the application data like images, audio, videos, and
personal contact information by storing them in SQLite Database, in files, or even on
a network.
• In order to share the data, content providers have certain permissions that are used
to grant or restrict the rights to other applications to interfere with the data.
• sometimes it is required to share data across applications. This is where
content providers become very useful.
• Content providers let you centralize content in one place and have many
different applications access it as needed.
• A content provider behaves very much like a database where you can query it,
edit its content, as well as add or delete content using insert(), update(), delete(),
and query() methods. In most cases this data is stored in an SQlite database.
• A content provider is implemented as a subclass of ContentProvider class and
must implement a standard set of APIs that enable other applications to perform
transactions.
content:// – Mandatory part of the URI as it represents that the given URI is a Content URI.
authority – Signifies the name of the content provider like contacts, browser, etc. This part
must be unique for every content provider.
optionalPath – Specifies the type of data provided by the content provider. It is essential as
this part helps content providers to support different types of data that are not related to
each other like audio and video files.
optionalID – It is a numeric value that is used when there is a need to access a particular
record. If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-based
URI.
Operations in Content Provider
Four fundamental operations
These operations are often termed as CRUD operations.