0% found this document useful (0 votes)
14 views77 pages

Mad - UNIT 5-1

Unit 5 covers various aspects of Android development, focusing on Activities, Intents, Broadcast Receivers, and Content Providers. It explains the lifecycle of Activities, the use of Intents for communication between app components, and the implementation of Broadcast Receivers to handle system events. Additionally, it discusses Content Providers as a means to manage and share application data securely among different apps.

Uploaded by

priyabhat530
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views77 pages

Mad - UNIT 5-1

Unit 5 covers various aspects of Android development, focusing on Activities, Intents, Broadcast Receivers, and Content Providers. It explains the lifecycle of Activities, the use of Intents for communication between app components, and the implementation of Broadcast Receivers to handle system events. Additionally, it discusses Content Providers as a means to manage and share application data securely among different apps.

Uploaded by

priyabhat530
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

UNIT 5

Activity And Multimedia


with databases
Content:
5.1 Intent, Intent Filter
5.2 Activity Lifecycle; Broadcast lifecycle
5.3 Content Provider; Fragments
5.4 Service: Features Of service, the Android platform service,
defining new service, Service Lifecycle, Permission, example of
service
5.5 Android System Architecture, Multimedia framework, Play
Audio and Video, Text to speech, Sensors, Async tasks
5.6 Audio Capture, Camera
5.7 Bluetooth, Animation
5.8 SQLite Database, necessity of SQLite, Creation and
connection of the database, extracting value from cursors,
Transactions.
5.1 Intent, Intent Filter

• Android uses Intent for communicating between the


components of an Application and also from one application
to another application.

• Intent are the objects which is used in android for passing


the information among Activities in an Application and from
one app to another also.

• Intent are used for communicating between the Application


components and it also provides the connectivity between
two apps.
• How an implicit intent is delivered through the
system to start another activity:
[1] Activity A creates an Intent with an action
description and passes it to startActivity().

[2] The Android System searches all apps for an intent


filter that matches the intent. When a match is found,

[3] the system starts the matching activity (Activity B)


by invoking its onCreate() method and passing it the
Intent.
Intent Uses In Android:
• Android uses Intents for facilitating communication between
its components like Activities, Services and Broadcast
Receivers.

Intent for an Activity:


• Every screen in Android application represents an activity.
• To start a new activity you need to pass an Intent object to
startActivity() method.
• This Intent object helps to start a new activity and passing
data to the second activity.
Intent for Services:
• Services work in background of an Android application and it
does not require any user Interface.
• Intents could be used to start a Service that performs one-
time task(for example: Downloading some file) or for starting
a Service you need to pass Intent to startService() method.
Intent for Broadcast Receivers:
• There are various message that an app receives, these
messages are called as Broadcast Receivers.
• (For example, to intimate that the file downloading is
completed and ready to use).
• Android system initiates some broadcast message on several
events, such as System Reboot, Low Battery warning message
etc.
• Methods and their Description

Methods Description

Context.startActivity() This is to launch a new activity or get an existing


activity to be action.

Context.startService() This is to start a new service or deliver


instructions for an existing service.

This is to deliver the message to broadcast


Context.sendBroadcast() receivers.
Types of Intent
• Intent are of two types: Explicit Intent and
Implicit Intent
Explicit Intent:
• Explicit Intents are used to connect the application
internally.
• In Explicit we use the name of component which will
be affected by Intent.
• For Example: If we know class name then we can
navigate the app from One Activity to another
activity using Intent. In the similar way we can start a
service to download a file in background process.
• Explicit Intent work internally within an application to
perform navigation and data transfer.
• For example: Intent facilitate you to redirect your
activity to another activity .By calling, startActivity() you
can perform this task.
• 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.
Implicit Intent:

• In Implicit Intents we do not need to specify the


name of the component.
• We just specify the Action which has to be
performed and further this action is handled by the
component of another application.
• The basic example of implicit Intent is to open any
web page.
• Let’s take an example to understand Implicit
Intents more clearly. We have to open a
website using intent in your application.
Intent Filter
• Intent Filters is Filtering the operation and perform
an Action to deliver the target component.
• An Intent filter is used to specify the types of intent
that an activity, service or broadcast receiver can
respond to.
• It declares the capabilities of its parent component
for an activity or services can do and what type of
Broadcast receiver can handle.
• icon: This is displayed as icon for activity. You can
check or save png image of name icon in drawable
folder. i.e. @drawable/image_name.

• label: You can check or edit label name by opening


String XML file present inside Values folder (Values -
> Strings). Replace @string/label to
@string/yourlabel.
Elements In Intent Filter:

• There are following three elements in an


intent filter:
• Action
• Data
• Category
1. Action:
• It represent an activities action, what an activity is
going to do.
• <action android:name = "string" />

• ACTION_VIEW: This is used in an Intent with


startActivity(). This helps when you redirect to see
any website, photos in gallery app or an address to
view in a map app.
• Intent intentObj = new Intent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.android.com"));
startActivity(intentObj);

• There are more actions similar to above like,


ACTION_SEND, ACTION_MAIN,
ACTION_WEB_SEARCH and many more.
2. Data:
• There are two forms in which you can pass the data,
using URI(Uniform Resource Identifiers like scheme,
host, port, path) or MIME type of data.
• The syntax of data attribute is as follows:
<data android:scheme="string"
android:host="string"
android:port="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />
ACTION DATA MEANING

Opens phone application and calls


Intent.ACTION_CALL tel:phone_number
phone number

Opens phone application and dials


Intent.ACTION_DIAL tel:phone_number
(but doesn’t call) phone_number

Opens phone application and dials


Intent.ACTION_DIAL voicemail: (but doesn’t call) the voice mail
number.

Opens the maps Application centered


Intent.ACTION_VIEW geo:lat,long
on (lat, long).

Opens the maps application centered


Intent.ACTION_VIEW geo:0,0?q=address
on the specified address.

http://url Opens the browser application to the


Intent.ACTION_VIEW
https://url specified address.
3. Category:
• This attribute of Intent filter dictates the
behavior or nature of an Intent.
• There is a string which contains some
additional information about the intent which
will be handled by a component.

• <category android:name="string" />


CATEGORY_BROWSABLE, CATEGORY_LAUNCHER.

• BROWSABLE – Activity allows itself to be opened


with web browser to open the reference link
provided in data.

• LAUNCHER – Launcher category puts an activity on


the top of stack, whenever application will start, the
activity containing this category will be opened first.
• Syntax
<intent-filter>
<!--Code here-->
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<!--Code here-->
<category
android:name="android.intent.category.BROWSABLE“
/>
</intent-filter>
5.2.1 Activity
• In Android, an activity is referred to as one screen in
an application.
• An Android app consists of one or more screens or
activities.
• By the help of activity, you can place all your UI
components or widgets in a single screen.
• Each activity goes through various stages or a
lifecycle.
• The 7 lifecycle method of Activity describes how
activity will behave at different states.
The Activity lifecycle consists of 7 methods:

• onCreate() : It is called when an activity is first


created. When a user opens the app then some
Activity is created. Here the initialization of your
application's UI is done.

• onStart(): This method is called when an activity


becomes visible to the user. When all the
initialization is done by the onCreate() method, then
this method is called.
• onResume(): It is called just before the user starts
interacting with the application. Most of the core
functionalities of the app are implemented in this
method.

• onPause(): It is called when the activity is paused


i.e. it is mostly called when you press the back or
home button of your Android device. It is an
indication that the user is leaving the activity and
starting some other activity.
• onStop(): It is called when the activity is no longer
visible to the user. If you are starting a new activity,
or some existing activity is entering into onResume()
state, then the current activity will not be visible to
the user and is stopped.

• onRestart(): It is called when the activity in the


stopped state is about to start again.

• onDestroy(): It is called when the activity is totally


destroyed i.e. when you clear the application stack
then onDestroy() will be called and all the states of
the activity will be destroyed.
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.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast toast = Toast.makeText(getApplicationContext(), "onCreate
Called", Toast.LENGTH_LONG).show();
}
protected void onStart() {
super.onStart();
Toast toast =
Toast.makeText(getApplicationContext(), "onStart
Called", Toast.LENGTH_LONG).show();
}
@Override
protected void onRestart() {
super.onRestart();
Toast toast =
Toast.makeText(getApplicationContext(), "onRestart
Called", Toast.LENGTH_LONG).show();
}
protected void onPause() {
super.onPause();
Toast toast = Toast.makeText(getApplicationContext(),
"onPause Called", Toast.LENGTH_LONG).show();
}
protected void onResume() {
super.onResume();
Toast toast = Toast.makeText(getApplicationContext(),
"onResume Called", Toast.LENGTH_LONG).show();
}
protected void onStop() {
super.onStop();
Toast toast = Toast.makeText(getApplicationContext(),
"onStop Called", Toast.LENGTH_LONG).show();
}

protected void onDestroy() {


super.onDestroy();
Toast toast = Toast.makeText(getApplicationContext(),
"onDestroy Called", Toast.LENGTH_LONG).show();
}
}
5.2.2 Android Broadcast
• Android app can send or receive broadcast messages
from the Android system and other Android apps.

• These broadcast are sent when an event of interest


occurs.
example. When the system boots up or the device
starts charging.
Broadcast Receiver
• Android broadcast receiver is one of the important
component of Android application development.
• Broadcast receiver which is also known as receiver is
a component of Android application.
• when that event occurs Android system will notify
the registered receivers about the execution of event
respectively.
Types of Broadcast
1. Normal broadcast
• These are asynchronous broadcast.
• Receivers of this type of broadcasts may run in any
order.
• This is efficient.
• Receivers cannot use the result.
• These broadcast are sent with
Context.sendBroadcast
2. Ordered broadcast
• These are synchronous broadcasts.
• One broadcast is delivered to one receiver at a time.
• Receiver can use the result. in fact as each receiver
executes result is passed to the next receiver.
• The order of receivers is managed and controlled by
the attribute Android:priority
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

There are two different methods to register a broadcast


receiver.

• Statically (manifest-declared) - This receiver can be


registered via the AndroidManifest.xml file.
• Dynamically (context-registered) - This registers a
receiver dynamically via the Context.registerReceiver()
method.
• 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>
Broadcast receiver lifecycle

• A broadcast receiver has single callback method:


• void onReceive(Context curContext, Intent broadcastMsg)
• When a broadcast message arrives for the receiver, Android
calls its onReceive() method and passes it the Intent object
containing the message.
• The broadcast receiver is considered to be active only while
it is executing this method.
• When onReceive() returns, it is inactive.
• A process with an active broadcast receiver is protected
from being killed.
• But a process with only inactive components can be killed
by the system at any time, when the memory it consumes is
needed by other processes.
Sending Broadcasts

Method Description

This method is used to send


sendOrderedBroadcast(Intent,
broadcasts to one receiver at a
String)
time.

This method is used to send


sendBroadcast(Intent) broadcasts to all receivers in an
undefined order.

This method is used to send


LoadBroadcastManager.sendBroad
broadcasts to receivers that are in
cast
the same app as the sender.
System Broadcasts

• Following are the some of system events available in android


applications.
Event Description

android.intent.action.BOOT_COMPLETED It raise an event, once boot completed.

It is used to trigger an event when power


android.intent.action.POWER_CONNECTED
connected to the device.

android.intent.action.POWER_DISCONNECT It is used to trigger an event when power got


ED disconnected from the device.

It is used to call an event when battery is low


android.intent.action.BATTERY_LOW
on device.

It is used to call an event when battery is OKAY


android.intent.action.BATTERY_OKAY
again.

It call an event when the device rebooted


android.intent.action.REBOOT
again.
5.3 Content Provider
• Content Providers are a very important component
that 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.
Content URI
• Content URI(Uniform Resource Identifier) is the key
concept of Content providers. To access the data from a
content provider, URI is used as a query string.
• Structure of a Content
URI: content://authority/optionalPath/optionalID

• content:// – it represents that the given URI is a Content


URI.
• authority – Signifies the name of the content provider like
contacts, browser, etc.
• optionalPath – Specifies the type of data provided by the
content provider.
• optionalID – It is a numeric value that is used when there is
a need to access a particular record.
Working of the Content Provider
• UI components of android applications
like Activity and Fragments use an
object CursorLoader to send query requests
to ContentResolver.

• The ContentResolver object sends requests (like


create, read, update, and delete) to
the ContentProvider as a client.

• After receiving a request, ContentProvider process it


and returns the desired result.
Creating a Content Provider

• Register the content provider


in AndroidManifest.xml file using <provider> tag.
• To access the content, define a content provider URI
address.
• Create a database to store the application data.
• Implement the six abstract methods of
ContentProvider class.
Abstract Method Description

A method that accepts arguments and fetches the data from the
query()
desired table. Data is retired as a cursor object.

To insert a new row in the database of the content provider.


insert()
It returns the content URI of the inserted row.

This method is used to update the fields of an existing row.


update()
It returns the number of rows updated.

This method is used to delete the existing rows.


delete()
It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail


getType() Extension(MIME)
type of data to the given Content URI.

As the content provider is created, the android system calls


onCreate()
this method immediately to initialise the provider.
• Relationship between content provider and
other component.
• Sharing access to your application data with
other applications.
• Sending data to a widget.
• Returning custom search suggestions for your
application.
• Synchronizing application data with your
server.
• Loading data in your UI using a CursorLoader.
Fragments

• A Fragment is a piece of an activity which enable more


modular activity design.
• A fragment has its own layout and its own behaviour
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.
• 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.
• example of how two UI modules defined by
fragments can be combined into one activity for a
tablet design, but separated for a handset.
• The application can embed two fragments in
Activity A, when running on a tablet-sized
device.
• However, on a handset-sized screen, there's
not enough space for both fragments, so
Activity A includes only the fragment for the
list of articles, and when the user selects an
article, it starts Activity B, which includes the
second fragment to read the article.
Fragment Life Cycle

• The lifecycle of android fragment is like the


activity lifecycle. There are 11 lifecycle
methods for fragment.
• Android Fragment Lifecycle Methods
No Method Description

1) onAttach(Activity) it is called only once when it is


attached with activity.

2) onCreate(Bundle) It is used to initialize the fragment.

3) onCreateView(LayoutInfl creates and returns view hierarchy.


ater, ViewGroup, Bundle)

4) onActivityCreated(Bundl It is invoked after the completion of


e) onCreate() method.
No. Method Description
5) onStart() makes the fragment visible.
6) onResume() makes the fragment interactive.
7) onPause() is called when fragment is no longer
interactive.

8) onStop() is called when fragment is no longer


visible.

9) onDestroyVie allows the fragment to clean up resources.


w()

10) onDestroy() allows the fragment to do final clean up of


fragment state.

11) onDetach() It is called immediately prior to the


fragment no longer being associated with
its activity.
5.4 Service
• A service is a component that runs in the
background to perform long-running
operations.
• It doesn’t provide user interface.
• it works even if application is destroyed.
Types of services
Foreground:
• Foreground service perform some operation that is
noticeable to the user.
• Eg. Audio app would play a Foreground service to
play an audio track.
• Foreground services must display a notification.
Background:
• Background service performs an operations that isn't
directly noticed by the user.
• The process like schedule syncing of data or storing
of data.
Bound
• A service is bound when an application component
binds to it by calling bindService().
• A bound service runs only as long as another
application component is bound to it .
• Multiple components can bind to the service at
once , but when all of them unbind, the service is
destroyed.
Android Platform Service
• The Android platform provides and runs predefined
system services.
• Every Android application can use them, given the
right permissions.
• These can be accessed by getSystemService()
Method.
Declaring a service in mainfest file
Creating a started service
• An application component such as an activity can start
the service by calling startService() and passing
an Intent that specifies the service.
Starting a service
• The Android system calls the
service's onStartCommand() method and passes it
the Intent, which specifies which service to start.
Stopping a service
• A started service must manage its own lifecycle.
• The service must stop itself by calling stopSelf(), or
another component can stop it by calling stopService().
Lifecycle of service
• Lifecycle of service can follow two different paths:
Started/Unbound
• A service is started when an application component,
such as an activity, starts it by calling startService().
• It is stopped by stopService() method.
Bound
• A service is bound when an application component
binds to it by calling bindService() method.
• The client unbind the service by calling the
unbindService() method.
Understanding Started and Bound Service by
background music example

• Suppose, I want to play music in the background, so


call startService() method.
• But I want to get information of the current song
being played, I will bind the service that provides
information about the current song.
Methods Description

The Android service calls this method when a


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

when an application component calls the


bindService() method in order to bind itself with a
onBind() service.

The Android system invokes this method when all


onUnbind() the clients
get disconnected from a particular service interface.
Once all clients are disconnected from the particular
onRebind() interface of service and
there is a need to connect the service with new clients,
the system calls this method.

Whenever a service is created either using


onCreate() onStartCommand() or onBind(),
the android system calls this method.

When a service is no longer in use, the system invokes


onDestroy() this method
just before the service destroys as a final clean up call.

You might also like