Mobile Application Development
UNIT-5 Activity and Multimedia with Database
● Intent
Intent in 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.
• Intents are the objects of android.content. Intent types and intents are mainly useful to
perform the following things-
1. Starting an Activity:- By sending an Intent object to startActivity method we can start a new
Activity or existing Activity to perform required things.
2. Starting a Service:- By sending an Intent object to startService method we can start a new
Service or send required instructions to an existing Service.
3. Delivering a Broadcast:- By sending an Intent object to sendBroadcast method we can
deliver our messages to other app broadcast receivers.
Android intents are mainly used to:
1. Start the service
2. Launch an activity
3. Display a web page
4. Display a list of contacts
5. Broadcast a message
6. Dial a phone call etc.
Intent Types
There are two types of intents:
1. Explicit Intent
2. Implicit Intent
Explicit intents:- It specify which component of which application will satisfy the intent,
by specifying a full ComponentName.
- You'll typically use an explicit intent to start a component in your own app, because you know
the class name of the activity or service you want to start.
- For example, you might start a new activity within your app in response to a user action, or start
a service to download a file in the background.
- 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);
Implicit intents:- do not name a specific component, but instead declare a general action
to perform, which allows a component from another app to handle it.
- For example, if you want to show the user a location on a map, you can use an implicit intent to
request that another capable app show a specified location on a map.
- For example, you may write the following code to view the webpage.
Intent intent = new Intent(Intent ACTION_VIEW);
intent.setData(Uriparse("http://www.Google.com"));
startActivity(intent);
Intent Filter
- In Android, an Intent Filter is a component used to declare the capabilities of a particular
component (e.g., Activity, Service, or BroadcastReceiver) in your app.
- It allows your app to specify which types of intents it can handle, and it also defines the
conditions under which the component can be activated to respond to incoming intents from
other apps or system events.
- Intent filters are specified in the AndroidManifest.xml file of your app and play a crucial role in
enabling communication between different components and apps.
- The intent filter consists of one or more <action>, <category>, and <data>elements. Each
element serves a specific purpose:
1. <action>: Describes the action that the component can perform. For example, an activity
may have an intent filter with the action "android.intent.action.VIEW," indicating that it can
handle view intents to display specific data.
2. <category>: Describes the category of the component. For example, an activity may
declare the "android.intent.category.DEFAULT" category, indicating that it can respond to a
default action for the specified data type.
3. <data>: Describes the data type and schema that the component can handle. For
example, an activity may specify that it can handle "image/*" data type to open and display
images.
●Activity LifeCycle
-Android Activity:- If you have worked with C, C++ or Java programming language then you must
have seen that your program starts from main function.
• Very similar way, Android system initiates its program with in an Activity starting with a call on
onCreate( ) callback method.
• An activity represents a single screen with a user interface just like window or frame of Java.
Android activity is the subclass of ContextTheme Wrapper class.
- An activity is the single screen in android. It is like window or frame of Java.
Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class.
• By the help of activity, you can place all your UI components or widgets in a single screen.
- The 7 lifecycle method of Activity describes how activity will behave at different states.
Android Activity Lifecycle methods:
1. onCreate()- called when activity is first created.
2. onStart()- called when activity is becoming visible to the user.
3. onResume()- called when activity will start interacting with the user.
4. onPause()- called when activity is not visible to the user.
5. onStop()- called when activity is no longer visible to the user.
6. onRestart()- called after your activity is stopped, prior to start.
7. onDestroy()- called before the activity is destroyed.
Different States of Activity Lifecycle
1. Active State
• When an Activity is in active state, it means it is active and running.
• It is visible to the user and the user is able to interact with it.
Android Runtime treats the Activity in this state with the highest priority and never tries to kill it.
2. Paused State
• An activity being in this state means that the user can still see the Activity in the background
such as behind a transparent window or a dialog box i.e it is partially visible.
•The user cannot interact with the Activity until he/she is done with the current view.
Android Runtime usually does not kill an Activity in this state but may do so in an extreme case of
resource crunch.
3. Stopped State
• When a new Activity is started on top of the current one or when a user hits the Home key, the
activity is brought to Stopped state.
• The activity in this state is invisible, but it is not destroyed.
• Android Runtime may kill such an Activity in case of resource crunch.
4. Destroyed State
• When a user hits a Back key or Android Runtime decides to reclaim the memory allocated to
an Activity i.e in the paused or stopped state, It goes into the Destroyed state.
• The Activity is out of the memory and it is invisible to the user.
●Broadcast Lifecycle
- Broadcast in android is the system-wide events that can occur when the device starts, when a
message is received on the device or when incoming calls are received, or when a device goes to
an airplane mode, etc.
- Broadcast Receivers are used to respond to these system-wide events.
- Broadcast Receivers allow us to register for the system and application events, and when that
event happens, then the register receivers get notified.
- There are mainly two types of Broadcast Receivers:
1. Static Broadcast Receivers: These types of Receivers are declared in the manifest file and
works even if the app is closed.
2. Dynamic Broadcast Receivers: These types of receivers work only if the app is active or
minimized.
*Ways to Register Android Broadlast Receiver
• Static way in which the broadcast receiver is registered in an android application via
AndroidManifest.xml file.
• Another way of registering the boradcast receiver is dynamic, which is done using
Context.registerReceiver () method.
- Dynamically registered broadcast receivers can be unregistered using
Context.unregisterReceiver() method.
● Content Provider in Android
• A content provider component supplies data from one application to others on request.
• Such requests are handled by the methods of the ContentResolver class.
• A content provider can use different ways to store its data and the data can be stored in a
database, in files, or even over a network.
• 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.
public class My Application extends ContentProvider {
}
Content URIs
• To query a content provider, you specify the query string in the form of a URI which has
following format -
‹ prefix>://<authority>/<data_type>/<id>
The list of methods which you need to override in Content Provider class to have your Content
Provider working -
1. on Create() - This method is called when the provider is started.
2. query() -This method receives a request from a client. The result is returned as a
Cursor object.
3. insert()- This method inserts a new record into the content provider.
4. delete()- This method deletes an existing record from the content provider.
5. update()- This method updates an existing record from the content provider.
6. get Type() -his method returns the MIME type of the data at the given URI.
●Fragments
Fragments in android.
• 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.
Fragment Lifecycle methods:
1)on Attach(Activity)- it is called only once when it is attached with activity.
2)onCreate(Bundle)- It is used to initialize the fragment.
3)onStart()-makes the fragment visible.
4)onResume()- makes the fragment interactive.
5)onPause()- called when fragment is no longer interactive.
6)onStop()- is called when fragment is no longer visible.
7)onDestroy View()- allows the fragment to clean up resources.
8)onDestroy()-allows the fragment to do final clean up of fragment state.
9)onDetach()-It is called immediately prior to the fragment no longer being associated with its
activity.
●Service in Android
Services in android.
• 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.
Types of Android Services :
There are four different types of Android services:
•Bound Service - A bound service is a service that has some other component (typically an
Activity) bound to it.
• IntentService -An IntentService is meant to handle individual autonomous calls.
- Started Service - A started service is a service that has been started by some other Android
component (such as an Activity) and is run continuously in the background until something
explicitly tells the service to stop.
•Hybrid Service - A hybrid service is a service that has the characteristics of a started service and
a bound service.
Which type of service to use is very dependent on application requirements.
As a rule of thumb, an IntentService or a bound service are sufficient for most tasks that an
Android application must perform, so preference should be given to one of those two types of
services.
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.
1.Started
2.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 stopSelfO 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.
Callback methods of Android Service Class:
1. onStartCommand() :The system calls this method when another component, such as an
activity, requests that the service be started, by calling startService.
2. onBind() : The system calls this method when another component wants to bind with the
service by calling bindService.
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.
● Multimedia framework.
Components of Multimedia
Following are the common components of multimedia:
• Text-All multimedia productions contain some amount of text.
• Graphics- Graphics make the multimedia application attractive. There are two types of
Graphics:
• Bitmap images- Bitmap images are real images that can be captured from devices such as
digital cameras or scanners.
• Vector Graphics- Vector graphics are drawn on the computer and only require a small amount
of memory..
• Audio- A multimedia application may require the use of speech, music and sound effects.
These are called audio or sound element of multimedia.
• Video- The term video refers to the moving picture, accompanied by sound such as a picture in
television.
• Animation- Animation is a process of making a static image look like it is moving. An animation
is just a continuous series of still images that are displayed in a sequence.
●Android Audio / Media Player :
- In android, by using MediaPlayer class we can easily fetch, decode and play both audio and
video files with minimal setup.
- The android media framework provides built-in support for playing a variety of common media
types, such as audio or video.
- We have multiple ways to play audio or video but the most important component of media
framework is MediaPlayer class.
Android MediaPlayer Class
- In android, by using MediaPlayer class we can access audio or video files from application (raw)
resources, standalone files in file system or from a data stream arriving over a network
connection and play audio or video files with the multiple playback options such as play, pause,
forward, backward, etc.
MediaPlayer mPlayer = MediaPlayer create(this, R.raw.abc_etc);
mPlayer.start();
- Callback methods of multimedia freamwork:
1. get CurrentPosition()- It is used to get the current position of the song in milliseconds.
2. getDuration()- It is used to get the total time duration of the song in milliseconds.
3. isPlayingO- It returns true / false to indicate whether song playing or not.
4. pause()- It is used to pause the song playing.
5. setAudioStreamType()- it is used to specify the audio streaming type.
6. setDataSource()- It is used to specify the path of audio / video file to play.
7. set Volume()- It is used to adjust media player volume either up / down.
8. get TrackInfo()- It returns an array of track information.
9. start()- It is used to start playing the audio/video.
10. stop()- It is used to stop playing the audio/video.
11. reset()- It is used to reset the MediaPlayer object.
12. release()- It is used to releases the resources which are associated with MediaPlayer object.
● Sensors
- 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.
- Types of Sensors
Android supports three types of sensors:
1) Motion Sensors -These are used to measure acceleration forces and rotational
forces along with three axes.
2) Position Sensors -These are used to measure the physical position of device.
3) Environmental Sensors - These are used to measure the environmental changes
such as temperature, humidity etc.
●Android Sensor API
Android sensor api provides many classes and interface. The important classes and interfaces of
sensor api are as follows:
1) SensorManager class
The android.hardware.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.
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.
3) SensorEvent class
Its instance is created by the system. It provides information about the sensor.
4) SensorEventListener interface
It provides two call back methods to get information when sensor values (x,y and z) change or
sensor accuracy changes.
● Camera in android.
• In android, Camera is useful to capture the photos and videos in our applications. By using
camera API we can control the functionalities of camera based on our requirements.
• The android framework provides a two ways such as android hardware.camera2 API and
camera intent to capture the images and videos in our application.
• android.hardware.camera2 It's a primary API for controlling the device cameras. By using this
we can take the pictures or videos from our application using camera.
1. Camera by using Intent
- By using intent action types MediaStore.ACTION IMAGE CAPTURE or MediaStore.ACTION VIDEO
CAPTURE we can capture the photos or videos without directly using the Camera object.
- In android. By using startActivityForResultO method with intent action MediaStore ACTION_
IMAGE_CAPTURE, we can take the pictures from our android applications.
Intent cInt = new Intent(MediaStore ACTION_IMAGE_CAPTURE;
startActivityForResult(cInt, Image_Capture_Code);
- we used 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.
- XML Layout file for Camera Application:
activity_main.xml
‹RelativeLayout
android layout_width="match parent" android layout_ height="match _parent">
‹Button
android:id="@+id/btnTakePicture"
android layout_width="wrap_content"
android layout _height="wrap_content" android:text="Take a Photo"/
< Image View
android layout_width="fill _parent"
android: layout _height= "fill_ parent"
android id="@+id/capturedImage"
android: layout_above="@+id/btnTakePicture"/>
</RelativeLayout>
- JAVA file for camera application:
MainActivity.java
private Button binCapture;
private ImageView imgCapture;
private static final int Image_Capture_Code = 1;
btnCapture =(Button) find ViewById(R.id.btnTakePicture);
imgCapture = (Image View) findViewById(R.id.capturedImage);
btnCapture setOnClickListener(new View.OnClickListener)
{
public void onClick(View v) {
Intent cInt = new Intent(MediaStore ACTION _IMAGE_CAPTURE);
startActivityForResult(cInt, Image_Capture_Code);
}
● Bluetooth
• Bluetooth is a way to exchange data with other devices wirelessly.
Android provides Bluetooth API to perform several tasks such as:
1. scan bluetooth devices
2. connect and transfer data from and to other devices
3. manage multiple connections etc.
- BluetoothAdapter class
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.
• BluetoothAdapter class provides many constants. Some of them are as follows:
1. String ACTION REQUEST ENABLE
2. String ACTION_REQUEST DISCOVERABLE
3. String ACTION_DISCOVERY_ STARTED
4. String ACTION_DISCOVERY_FINISHED
- Commonly used methods of BluetoothAdapter class are as follows:
- static synchronized BluetoothAdapter getDefaultAdapter() returns the instance of
BluetoothAdapter.
• boolean enable() -enables the bluetooth adapter if it is disabled.
• boolean isEnabled( )- returns true it the bluetooth adapter is enabled
• boolean disable() -disables the bluetooth adapter if it is enabled.
• String getName() -returns the name of the bluetooth adapter.
• boolean setName(String name) - changes the bluetooth name.
• int getState() -returns the current state of the local bluetooth adapter.
• Set<BluetoothDevice> getBondedDevices) returns a set of paired (bonded) BluetoothDevice
objects.
• boolean startDiscovery()- starts the discovery process.
● Animation
-Android provides a large number of classes and interface for the animation development.
Most of the classes and interfaces are given in android animation package.
- Android Animation enables you to change the object property and behavior at run time. There
are various ways to do animation in android.
- The AnimationDrawable class provides methods to start and end the animation.
Even, you can use time based animation.
- In order to perform animation in android, we are going to call a static function load Animation)
of the class AnimationUtils.
We are going to receive the result in an instance of Animation Object.
Its syntax is as follows -
Animation animation = AnimationUtils. loadAnimation(getApplicationContext(),
R.anim.myanimation);
Note the second parameter. It is the name of the our animation xml file. You have to create a new
folder called anim under res directory and make an xml file under anim folder.
- In order to apply this animation to an object, we will just call the startAnimation) method of the
object.
Its syntax is -
ImageView imagel = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);
• This animation class has many useful functions which are listed below -
1. start()- This method starts the animation.
2. setDuration(long duration)- This method sets the duration of an animation.
3. getDuration()- This method gets the duration which is set by above method
4. end()- This method ends the animation.
5. cancel()- This method cancels the animation.
● SQLite Database
• SQLite is an open-source relational database i.e. used to perform database operations on
android devices such as storing, manipulating or retrieving persistent data from the database.
• It is embedded in android by default. So, there is no need to perform any database setup or
administration task.
• Data is displayed in the logeat. For displaying data on the spinner or listview, move to the next
page.
• SQLiteOpenHelper class provides the functionality to use the SQLite database.
●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
Constructor-
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int
version) - creates an object for creating, opening and managing the database.
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int
version,DatabaseErrorHandler errorHandler)- creates an object for creating, opening and
managing the database. It specifies the error handler.
Methods of SQLiteOpenHelper class:
1. public abstract void onCreate(SQLiteDatabase db)- called only once when database is
created for the first time.
2. public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)-
called when database needs to be upgraded.
3. public synchronized void close ()- closes the database object.
4. public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion)-
called when database needs to be downgraded.
• Methods of SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete, select etc.
1. void execSQL(String sql)- executes the sql query not select query.
2. long insert(String table, Stringnull ColumnHack, ContentValues values)- inserts a record on
the database. The table specifies the table name, nullColumnHack doesn't allow completely null
values. If second argument is null, android will store null values if values are empty.
The third argument specifies the values to be stored.
3. int update(String table, ContentValues values, String whereClause, String[] WhereArgs)-
updates a row.
4. Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String
groupBy, String having, String orderBy)- returns a cursor over the resultset.