SlideShare a Scribd company logo
1 of 79
Mobile Application
Development
Subject Code: 22617
Unit V
20M
Activity and multimedia with database
Intents :
An intent is to perform an action on the screen.
Android intents are mainly used to:
 Start the service
 Launch an activity
 Display a web page
 Display a list of contacts
 Broadcast a message
 Dial a phone call etc.
It is mostly used to start activity, send broadcast receiver, start
services and send message between two activities.
Types of intents :
There are two types of intents available in android as Implicit
Intents and Explicit Intents.
Implicit Intent doesn't specify the component. In such case,
intent provides information of available components provided by
the system that is to be invoked. Many a times it is used to call
built in applications.
For example, you may write the following code to view the
webpage.
Intent intent=new Intent(Intent.ACTION_VIEW);
Intent.setData(Uri.parse("http://www.mysite.com"));
startActivity(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);
Actions and Extras for intents
:
Main Actions which can be taken in intent are
 ACTION_VIEW
 ACTION_SEND
Extras (mostly used with Explicit intent)
This will be in key-value pairs for additional
information that should be delivered to the
component handling the intent. The extras can be set
and read using the putExtras() and getExtras()
methods respectively.
To send values from one activity we can use putExtra() as :
Intent i= new Intent(getApplicationContext(),ActivityTwo.class)
i.putExtra(“First”,”Android”);
i.putExtra(“Second”,”1234”);
startActivity(i);
In the other activity the values can be collected by getExtras() as:
// Get bundle object at appropriate place in your code
Bundle extras = getIntent().getExtras();
// Extract data using passed keys
String value1 = extras.getString(“First");
String value2 = extras.getString(“Second");
startActivityForResult()
 startActivityForResult() method can be used to get
result from another activity.
 With the help of android startActivityForResult()
method, we can send information from one activity to
another and vice-versa.
 In this case, we need to override the onActivityResult()
method that is invoked automatically when second
activity returns result.
It can be used as :
 public void startActivityForResult (Intent intent, int
requestCode)
 requestCode can be matched in onActivityResult()
menthod and then data can be extracted by
getStringExtra() method.
 Other activity which sends the data should use the
same requestCode.
 Intent can be started by
setResult(requestCode,intent) method and then
can be finished by finish() method.
Examples
 Create an activity to browse a web
page (implicit intent example)
 Create an application containing two
activities. On a click on a button of first
activity open second activity. (Explicit
intent example)
Intent filters :
 Used in AndroidManifest.xml
 It is used to specify the type of intents that the
component would like to receive.
 Tag to be used is <intent-filter>
 Elements to be used : action, category, data.
Example
<activity android:name=".ResultActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAU
LT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
Activity :
Activities however are what defines
every major stage of your application.
It wouldn't be possible to build an
application without Activities. You will
have a main Activity class and this will
indeed be defined with 'extends
Activity'.
What is an Activity?
 An Activity is an application
component that provides a screen with
which users can interact in order to do
something.
 Almost all activities interact with the
user, so the Activity class takes care of
creating a window for you in which
you can place your UI.
Life cycle of an Activity
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.
Broadcast Receiver :
 Broadcast Receivers simply respond to
broadcast messages from other applications or
from the system itself.
 Because broadcast receivers are another well-
defined entry into the app, the system can deliver
broadcasts even to apps that aren't currently
running.
 Eg , an app can schedule an alarm to post a
notification to tell the user about an upcoming
event... and by delivering that alarm to a Broadcast
Receiver of the app, there is no need for the app to
remain running until the alarm goes off.
 Broadcast receivers don't display a user
interface, they may create a status bar notification
to alert the user when a broadcast event occurs
Sr.No Event Constant & Description
1
android.intent.action.BATTERY_CHANGED
Sticky broadcast containing the charging state, level, and other
information about the battery.
2
android.intent.action.BATTERY_LOW
Indicates low battery condition on the device.
3
android.intent.action.BATTERY_OKAY
Indicates the battery is now okay after being low.
4
android.intent.action.BOOT_COMPLETED
This is broadcast once, after the system has finished booting.
5
android.intent.action. AIRPLANE_MODE
Show if aeroplane mode on/off
6
android.intent.action.CALL
Perform a call to someone specified by the data.
7
android.intent.action.CALL_BUTTON
The user pressed the "call" button to go to the dialer or other
appropriate UI for placing a call.
8
android.intent.action.DATE_CHANGED
The date has changed.
9
android.intent.action.REBOOT
Have the device reboot.
10.
android.net.conn.CONNECTIVITY_CHANGE : The mobile network
or wifi connection is changed(or reset)
Steps to use Broadcast receiver :
1. Create a subclass of Broadcast receiver
2. Override onReceive() method and take action to broadcast the message to system
3. Create appropriate intent filter in onStart() of MainActivity.java for the proper action.
IntentFilter filter=new IntentFilter("android.intent.action.AIRPLANE_MODE");
4. Create an object on extended BroadcastReceiver subclass and register it with the
intent filter object with registerReceiver() method.
5. Receiver can be unregisterd by unregisterReceiver() in onStop).
6. You may also require to add <receiver> entry in AndroidManifest.xml as follows:
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action. AIRPLANE_MODE"/>
</intent-filter> </receiver>
Files to be created :
 activity_main.xml – for layout
 MainActivity.java – for code behind
 One more java class which is subclass
of Broadcast Receiver.
 <receiver> tag in AndroidManifest.xml
Create an android app using
broadcast Receiver to display
appropriate messages if
Aeroplane mode is on/off
Service :
 Android Services are the application
components that run in the background.
 We can understand it as a process that
doesn’t need any direct user interaction.
 As they perform long-running processes
without user intervention, they have no
User Interface.
 They can be connected to other components
and do inter-process communication
(IPC).
Types of Services :
1. Foreground Services
Foreground services are those services that are visible to the users.
The users can interact with them at ease and track what’s
happening. These services continue to run even when users are
using other applications.
The perfect example of this is Music Player and Downloading.
2. Background Services
These services run in the background, such that the user can’t see
or can’t access them. These are the tasks that don’t need the user to
know them.
Syncing and Storing data can be the best example.
3. Bound Services
Bound service runs as long as some other application
component is bound to it. Many components can bind to one
service at a time, but once they all unbind, the service will
destroy.
Lifecycle of Android Services
Android services life-cycle can have two
forms of services and they follow two
paths, that are:
 Started Service
 Bounded Service
Started service Bound service
1. Started Service :
A service becomes started only when an
application component calls startService().
It performs a single operation and doesn’t
return any result to the caller.
Once this service starts, it runs in the
background even if the component that
created it destroys.
This service can be stopped only in one of
the two cases:
By using the stopService() method.
By stopping itself using the stopSelf()
method.
2. Bound Service :
 A service is bound only if an application
component binds to it
using bindService(). It gives a client-
server relation that lets the components
interact with the service. The
components can send requests to
services and get results.
 This service runs in the background as
long as another application is bound to it.
Or it can be unbound according to our
requirement by using
the unbindService() method.
 When a component wants to bind with the
service by calling bindService(), we must
provide an interface for clients to
communicate with the service. For
interprocess communication, we use
the IBinder object.
 It is a must to implement this method. If in
case binding is not required, we should
return null as implementation is mandatory.
System Services :
 Some predefined system services can be made on by
getSystemService() method.
 Some of the Constants are
NOTIFICATION_SERVICE,
NETWORK_STATS_SERVICE, POWER_SERVICE,
USB_SERVICE, VIBRATOR_SERVICE,
WIFI_SERVICE, WINDOW_SERVICE which can be
qualified by Context class as follows:
getApplicationContext().getSystemService(Context.servicename);
Eg
getApplicationContext.getSystemService(Context.WIFI_SERVICE);
1. Write a program to start a Wi-Fi using
service.
2. Write a program to display the
following output :
Content Provider
• A content provider component supplies data from one application to others on
request.
• 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.
• 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. They handle the access to the central repository
and supply data from one application to another on request.
• 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.
Following are some of the examples for
content providers :
 The Gallery that contains images.
 Contact lists that contain Contact
details.
 A dictionary that has collections of all
the words that are used.
 The music playlist has a list of songs.
 Call logs contain the call details.
How and where content provider
is needed in android?
Content provider lets us collect the data centrally and provide
them to applications.
Content providers act the same as database and also we can
query it to add, delete, insert or update the data.
Content providers are not limited to texts, but also contains
images and videos as well.
Operations of content
Provider:
 Content providers provide the following
four basic operations. These are also
known as CRUD operations, where
 Create: It is used for the creation of data
in content providers.
 Read: It reads the data stored in the
content provider.
 Update: It lets the editing in existing data
in content providers.
 Delete: It deletes the existing data stored
in its Storage.
How is it working as a central
repository?
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.
• 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
{
………
}
• To query a content provider, you specify the query string in the
form of a content URI which has following format −
content://<authority>/<path>/<optional_id>
Content URI −
Content URIs are the uniform resource identifiers that identify the data in the content
providers. A content URI includes two things: Authority that is the symbolic name of
the Provider and a Path that is a name that points towards the data. Every content
provider methods have an argument which is URI.
content://<authority>/<path>/<optional_id>
• content:// – It’s always present, and is the scheme portion of the URI.
• authority – It is the unique name of the content provider, like photos, contacts. It’s a
string that can identify the whole content provider.
• path – It is often used to identify some or the other data of the provider. The path is
mostly used to identify individual tables.
• optional_id – id is used to access a single particular record of a file. We use this
only in cases where we need to access only a particular record and not the complete
file. It’s a numeric identifier to access a particular row of the data table. For
example, if you are looking for contact number 5 in the Contacts content provider
then URI would look like this content://contacts/people/5
STEPS TO CREATE YOUR OWN CONTENT PROVIDER:
• First of all you need to create a Content Provider class that extends
the ContentProvider baseclass.
• Second, you need to define your content provider URI address which
will be used to access the content.
• Next you will need to create your own database to keep the content.
Usually, Android uses SQLite database and framework needs to
override onCreate() method which will use SQLite Open Helper method
to create or open the provider's database. When your application is
launched, the onCreate() handler of each of its Content Providers is
called on the main application thread.
• Next you will have to implement Content Provider queries to perform
different database specific operations.
• Finally register your Content Provider in your activity file using
<provider> tag in AndroidManifest.xml
METHODS WHICH YOU NEED TO OVERRIDE
IN CONTENT PROVIDER CLASS TO HAVE
YOUR CONTENT PROVIDER WORKING
• onCreate() This method is called when the provider is started.
• query() This method receives a request from a client. The
result is returned as a Cursor object.
• insert()This method inserts a new record into the content
provider.
• delete() This method deletes an existing record from the
content provider.
• update() This method updates an existing record from the
content provider.
• getType() This method returns the MIME type of the data at
the given URI.
• Design an app to add and retrieve data from SQLite db using
content provider
Fragments :
 In Android, Fragment is a part of an
activity which enables more modular
activity design.
 we can say a fragment is a kind of sub-
activity.
 We can combine multiple Fragments in
Single Activity to build a multi panel UI
and reuse a Fragment in multiple
Activities.
 Fragments were added in Honeycomb
version of Android i.e API version 11.
 Fragments has its own layout and its
own behavior with its own life cycle
callbacks.
 Fragments have their own events,
layouts and complete life cycle.
 Basic tag :
<fragment
android:id="@+id/fragments"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
There are some primary classes related
to Fragment’s are:
 FragmentActivity: The base class for all activities
using compatibility based Fragment (and loader)
features.
 Fragment: The base class for all Fragment
definitions
 FragmentManager: The class for interacting with
Fragment objects inside an activity
 FragmentTransaction: The class for performing
an set of Fragment operations such as Replace
or Add a Fragment.
Lets try this example :
TextToSpeech :
 Android allows you convert your text into voice.
 Not only you can convert it but it also allows you to
speak text in variety of different languages.
 Android provides TextToSpeech class for this purpose.
In order to use this class, you need to instantiate an
object of this class and also specify the initListener.
 Its syntax is given below −
Eg :
EditText write;
ttobj=new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
..
..
} });
 In this listener, you have to specify the properties
for TextToSpeechobject , such as its language
,pitch e.t.c. Language can be set by calling
setLanguage() method. Its syntax is given below
−
ttobj.setLanguage(Locale.UK);
 The method setLanguage takes an Locale object
as parameter. Locale can take values as US,
CANADA, FRENCH,GERMANY, ITALY, JAPAN,
CHINA.
 Constructor of TextToSpeech class :
TextToSpeech(Context context,TextToSpeech.
OnInitListener)
 TextToSpeech.OnInitListener Interface
You need to implement
TextToSpeech.OnInitListener interface, for
performing event handling in TextToSpeech engine.
There is only one method in this interface.
Called to signal the completion of the TextToSpeech
engine initialization.
The status can be SUCCESS or ERROR.
void onInit (int status) `
Sensors :
 In Android devices, there are various built-in sensors that
can be used to measure the orientation, motions, and
various other kinds of environmental conditions. In
general, there are two types of sensors in Android
devices:
 Hardware Sensors: Hardware sensors are physical
components that are present in Android devices. They
can directly measure various properties like field
strength, acceleration, etc according to the types of the
sensors and after measuring the environment properties
they can send the data to Software Sensors.
 Software Sensors: Software sensors, also known as
virtual sensors are those sensors that take the help of
one or more Hardware sensors and based on the data
collected by various Hardware sensors, they can derive
 It is not necessary that all Android devices must have all the
sensors. Some devices may have all sensors and some may
lack one or two of them.
 To express data values or to collect data, the sensors in
Android devices uses a 3-axis coordinate system i.e. you will
be having X, Y, and Z-axis. The following figure depicts the
position of various axis used in sensors.
 In default orientation, the horizontal axis is represented by X-
axis, the vertical axis is represented by Y-axis and the Z-axis
points towards the outside of the screen face i.e towards the
user.
Categories of Sensors:
The three broad categories of sensors are :
1. Motion Sensors: The sensors that are responsible for
measuring or identifying the shakes and tilts of your
Android devices are called Motion sensors. These
sensors measure the rotational forces along the three-
axis. Gravity sensors, accelerometers, etc are some of
the examples of Motion sensors.
2. Position Sensors: As the name suggests, the
Position sensors are used to determine the position of
an Android device. Magnetometers, Proximity sensors
are some of the examples of Position sensors.
3. Environmental Sensors: These sensors are useful to
measure various environmental parameters, such as
ambient air temperature and pressure, illumination,
and humidity. This category includes barometers,
photometers, and thermometers.
classes required to access device sensors
Class Description
SensorManager By using this class we can create an instance of
sensor service and this class provides a various
methods for accessing and listing sensors,
registering and unregistering sensor event listeners
and acquiring orientation information.
Sensor By using this class we can create an instance of a
specific sensor and this class provides a various
methods that let you determine the sensor's
capabilities.
SensorEvent The system uses this class to create a sensor event
object and it provides the raw sensor data, type of
sensor that generated the event, accuracy of the
data, and the timestamp for the event.
SensorEventListener We can use this interface to create two callback
methods that receive notifications (sensor events)
when sensor values change or when sensor
accuracy changes.
Different sensor examples are
: TYPE_ACCELEROMETER
 TYPE_AMBIENT_TEMPERATURE
 TYPE_GRAVITY
 TYPE_GYROSCOPE
 TYPE_LIGHT
 TYPE_LINEAR_ACCELERATION
 TYPE_MAGNETIC_FIELD
 TYPE_ORIENTATION
 TYPE_PRESSURE
 TYPE_PROXIMITY
 TYPE_RELATIVE_HUMIDITY
 TYPE_ROTATION_VECTOR
 TYPE_TEMPERATURE
Media player in android :
 By 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.
 We can play audio or video files with the multiple
playback options such as play, pause, forward,
backward, etc.
 All audio/video files have to be stored in raw folder
under res.
We can create object of MediaPlayer class and associate the
audio file with it which can be played by start() method of the
same as:
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.samplemusic);
mPlayer.start();
The second parameter in create() method is the name of the audio file that we
want to play from our application resource directory (res/raw). In case
if raw folder not exists in your application, create a new raw folder
under res directory and add a properly encoded and formatted media files in it.
Or if it’s a file from outside resource …
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(Envrionment.getExternalStorageDirectory().getPath()”+filepath
);
Filepath can be any such as ‘/Music/one.mp3’
Method Description
getCurrentPosition() It is used to get the current position of song in milliseconds.
getDuration() It is used to get the total time duration of song in milliseconds.
isPlaying() It returns true / false to indicate whether song playing or not.
pause() It is used to pause the song playing.
setAudioStreamType() it is used to specify the audio streaming type.
setDataSource() It is used to specify the path of audio / video file to play.
setVolume() It is used to adjust media player volume either up / down.
seekTo(position) It is used to move song to particular position in milliseconds.
getTrackInfo() It returns an array of track information.
start() It is used to start playing the audio / video.
stop() It is used to stop playing the audio / video.
reset() It is used to reset the MediaPlayer object.
Playing video :
 By using VideoView component
and MediaController class we can easily
implement the video player in android
applications.
 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.
Some of the methods :
Method Description
setMediaController() It is used to set the media controller to videoview.
setVideoURI() It is used to set the path of video file.
pause() It is used to pause the video playing.
stopPlayback() it is used to stop the video playing.
seekTo(position) It is used to move video to particular position in
milliseconds.
resume() It is used to resume the video playing.
start() It is used to start playing the audio / video.
Camera :
 Camera is mainly used to capture
picture and video. We can control the
camera by using methods of Camera
api.
 Android provides the facility to work on
camera by 2 ways:
I. By Camera Intent
II. By Camera API
 By the help of 2 constants
of MediaStore class, we can capture picture
and video without using the instance of
Camera class.
ACTION_IMAGE_CAPTURE
ACTION_VIDEO_CAPTURE
 MediaRecorder : It is used to record video
using camera. It can also be used to record
audio files as we have seen in the previous
example of media framework.
Some of the actions associated
with camera intent :
 ACTION_IMAGE_CAPTURE_SECURE
 It returns the image captured from the camera , when the device
is secured
 ACTION_VIDEO_CAPTURE
 It calls the existing video application in android to capture video
 EXTRA_SCREEN_ORIENTATION
 It is used to set the orientation of the screen to vertical or
landscape
 EXTRA_FULL_SCREEN
 It is used to control the user interface of the ViewImage
 INTENT_ACTION_VIDEO_CAMERA
 This intent is used to launch the camera in the video mode
 EXTRA_SIZE_LIMIT
 It is used to specify the size limit of video or image capture size
Bluetooth:
 Bluetooth is a way to send or receive data between two different
devices.
 Android platform includes support for the Bluetooth framework
that allows a device to wirelessly exchange data with other
Bluetooth devices.
 Android provides Bluetooth API to perform these different
operations.
 Android provides BluetoothAdapter class to communicate with
Bluetooth. Its object can be created as :
BluetoothAdapter BA= BluetoothAdapter.getDefaultAdapter();
Then an intent can be created with proper action as :
Intent turnOn = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
There are some more intent actions as:
 ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of
bluetooth
 ACTION_STATE_CHANGED
This constant will notify that Bluetooth state has been
changed.
Once you enable the Bluetooth , you can get a list of
paired devices by calling getBondedDevices()
method. It returns a set of bluetooth devices as :
Set
<BluetoothDevice>pairedDevices =
BA.getBondedDevices();
Some of methods are enable(), disable(), getState(),
getName() to manage bluetooth activities.
AsyncTask :
 Android application runs on a single thread
when launched called as UI thread.
 Due to this single thread model tasks that
take longer time to fetch the response can
make the application non-responsive.
 To avoid this we use android AsyncTask to
perform the heavy tasks in background on
a dedicated thread and passing the results
back to the UI thread.
 Hence use of AsyncTask in android
application keeps the UI thread responsive
at all times.
Following methods are used in an android AsyncTask class :
 onPreExecute() : This method contains the code which is executed
before the background processing starts.
 doInBackground() : This method contains the code which needs to
be executed in background. In this method we can send results
multiple times to the UI thread by publishProgress() method. To notify
that the background processing has been completed we just need to
use the return statements.
 onProgressUpdate() : This method receives progress updates from
doInBackground() method, which is published via publishProgress()
method, and this method can use this progress update to update the
UI thread
 onPostExecute() : This method is called after doInBackground()
method completes processing. Result from doInBackground() is
passed to this method
The three generic types used in an android AsyncTask class are
given below :
Params : The type of the parameters sent to the task upon
execution. Generally used as argument in doInBackground()
method.
Progress : The type of the progress units published during the
background computation. This is used as argument in
onProgressUpdate() method.
Result : The type of the result of the background computation.
Generally the parameter of onPostExecute() which is returned from
doInBackgroumd() methd
Points to remember while using AsyntTask:
• The AsyncTask instance must be created and
invoked in the UI thread.
• It has to be the inner class of MainActivity.
• The methods overridden in the AsyncTask class
should never be called. They’re called
automatically.
• AsyncTask can be called only once. Executing it
again will throw an exception.
• AsyncTask object can call execute() method to
start the thread and execute which accept a url
as an argument inside it.
• Internet permission is required in
AndroidManifest file.
SQLite Database in android
 SQLite is a Structure query base
database, open source, light weight, no
network access and standalone
database. It supports embedded
relational database features.
• Whenever an application needs to store large
amount of data then using SQLite is more preferable
than other repository system .
• Android has built in SQLite database
implementation.
• It is available locally over the device(mobile & tablet)
and contain data in text format.
• It carry light weight data and suitable with many
languages.
• So, it doesn’t required any administration or setup
procedure of the database.
Creating And Updating Database In
Android :
• For creating, updating and other operations you need to create a
subclass or SQLiteOpenHelper class.
• SQLiteOpenHelper is a helper class to manage database creation
and version management. It provides two methods
onCreate(SQLiteDatabase db);
onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion);
• The SQLiteOpenHelper is responsible for opening database if exist,
creating database if it does not exists and upgrading if required.
• The SQLiteOpenHelper only requires the DATABASE_NAME to
create database.
• After extending SQLiteOpenHelper you will need to implement its
methods onCreate(), onUpgrade() and constructor.
onCreate(SQLiteDatabase sqLiteDatabase) method :
• It is called only once throughout the application lifecycle.
• It will be called whenever there is a first call to
getReadableDatabase() or getWritableDatabase() function
available in super SQLiteOpenHelper class.
• So SQLiteOpenHelper class calls the onCreate() method after
creating database and instantiate SQLiteDatabase object.
• Database name is passed in constructor call.
onUpgrade(SQLiteDatabase db,int oldVersion, int
newVersion) method :
• It is only called whenever there is a updation in existing version.
• So to update a version we have to increment the value of version
variable passed in the superclass constructor.
Insert, Read, Delete & Update
Operation In SqLite:
• To perform insert, read, delete, update operation there are two different ways:
1) Write parameterized queries (Recommended) with the help of ContentValues
object.
2) Write raw queries
• Parameterized Queries: These are those queries which are performed using
inbuilt functions to insert, read, delete or update data. These operation related
functions are provided in SQLiteDatabase class.
• Raw Queries: These are simple sql queries similar to other databases like
MySql, SqlServer etc, In this case user will have to write query as text and
passed the query string in rawQuery(String sql,String [] selectionArgs) or
execSQL(String sql,Object [] bindArgs) method to perform operations.
• Android documentation don’t recommend to use raw queries to perform insert,
read, update, delete operations, always use SQLiteDatabase class’s insert,
query, update, delete functions.
 insert(…) :
To perform insert operation using parameterized query we
have to call insert function available in SQLiteDatabase class.
insert() function has three parameters as:
public long insert(String tableName,String
nullColumnHack,
ContentValues values)
Where,
 nullColumnHack may be passed null, it requires table
column value in case we don’t put column name in
ContentValues object so a null value must be inserted for
that particular column, values are those values that needs
to be inserted-
 ContentValues values is a key-pair based object which
accepts all primitive type values so whenever data is being
put in ContentValues object, it should be put again table
column name as key and data as value.
 insert() function will return a long value i.e number of
inserted row if successfully inserted, -1 otherwise.
 Raw Query example :
public void insertItem(Item item)
{
String query = "INSERT INTO " + ItemTable.NAME + " VALUES (0,?,?)";
SQLiteDatabase db = getWritableDatabase();
db.execSQL(query, new String[]{item.name, item.description});
db.close(); }
SQLiteDatabase db=getReadableDatabase();
Cursor cursor =db.rawQuery("select
user_name from users where mobile=? and
password=?",new String[]{mobile,password});
Steps to use SQLite DB(without
subclass of SQLiteOpenHelper) :
 Create an object of SQLiteDatabase.
 Initialize the object as
db=openOrCreateDatabase("Student_manage.db",
Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno
INTEGER,name VARCHAR,marks INTEGER);");
Then manage queries for CRUD operation and get
them executed as :
db.execSQL("INSERT INTO student
VALUES('"+eroll_no.getText()+"','"+ename.getText()+
"','"+emarks.getText()+"');");

More Related Content

Similar to MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx

Mobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdfMobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdfAbdullahMunir32
 
Data Transfer between activities and Database
Data Transfer between activities and Database Data Transfer between activities and Database
Data Transfer between activities and Database faiz324545
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)Khaled Anaqwa
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & DatabasesMuhammad Sajid
 
Multiple Activity and Navigation Primer
Multiple Activity and Navigation PrimerMultiple Activity and Navigation Primer
Multiple Activity and Navigation PrimerAhsanul Karim
 
Using intents in android
Using intents in androidUsing intents in android
Using intents in androidOum Saokosal
 
Android application development
Android application developmentAndroid application development
Android application developmentMd. Mujahid Islam
 
Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAnuchit Chalothorn
 
Android应用开发简介
Android应用开发简介Android应用开发简介
Android应用开发简介easychen
 
Android application-component
Android application-componentAndroid application-component
Android application-componentLy Haza
 
Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in BackgroundAhsanul Karim
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changesInnovationM
 
How to integrate flurry in android
How to integrate flurry in androidHow to integrate flurry in android
How to integrate flurry in androidadityakumar2080
 
Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intentDiego Grancini
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAhsanul Karim
 

Similar to MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx (20)

Mobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdfMobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdf
 
Data Transfer between activities and Database
Data Transfer between activities and Database Data Transfer between activities and Database
Data Transfer between activities and Database
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
Multiple Activity and Navigation Primer
Multiple Activity and Navigation PrimerMultiple Activity and Navigation Primer
Multiple Activity and Navigation Primer
 
Using intents in android
Using intents in androidUsing intents in android
Using intents in android
 
Android development session 2 - intent and activity
Android development   session 2 - intent and activityAndroid development   session 2 - intent and activity
Android development session 2 - intent and activity
 
Activity & Shared Preference
Activity & Shared PreferenceActivity & Shared Preference
Activity & Shared Preference
 
Android application development
Android application developmentAndroid application development
Android application development
 
Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; Share
 
Android应用开发简介
Android应用开发简介Android应用开发简介
Android应用开发简介
 
ANDROID
ANDROIDANDROID
ANDROID
 
Android application-component
Android application-componentAndroid application-component
Android application-component
 
Android session 2
Android session 2Android session 2
Android session 2
 
Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in Background
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changes
 
Level 1 &amp; 2
Level 1 &amp; 2Level 1 &amp; 2
Level 1 &amp; 2
 
How to integrate flurry in android
How to integrate flurry in androidHow to integrate flurry in android
How to integrate flurry in android
 
Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intent
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver Tutorial
 

Recently uploaded

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 

Recently uploaded (20)

POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 

MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx

  • 2. Unit V 20M Activity and multimedia with database
  • 3. Intents : An intent is to perform an action on the screen. Android intents are mainly used to:  Start the service  Launch an activity  Display a web page  Display a list of contacts  Broadcast a message  Dial a phone call etc. It is mostly used to start activity, send broadcast receiver, start services and send message between two activities.
  • 4. Types of intents : There are two types of intents available in android as Implicit Intents and Explicit Intents. Implicit Intent doesn't specify the component. In such case, intent provides information of available components provided by the system that is to be invoked. Many a times it is used to call built in applications. For example, you may write the following code to view the webpage. Intent intent=new Intent(Intent.ACTION_VIEW); Intent.setData(Uri.parse("http://www.mysite.com")); startActivity(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);
  • 5. Actions and Extras for intents : Main Actions which can be taken in intent are  ACTION_VIEW  ACTION_SEND Extras (mostly used with Explicit intent) This will be in key-value pairs for additional information that should be delivered to the component handling the intent. The extras can be set and read using the putExtras() and getExtras() methods respectively.
  • 6. To send values from one activity we can use putExtra() as : Intent i= new Intent(getApplicationContext(),ActivityTwo.class) i.putExtra(“First”,”Android”); i.putExtra(“Second”,”1234”); startActivity(i); In the other activity the values can be collected by getExtras() as: // Get bundle object at appropriate place in your code Bundle extras = getIntent().getExtras(); // Extract data using passed keys String value1 = extras.getString(“First"); String value2 = extras.getString(“Second");
  • 7. startActivityForResult()  startActivityForResult() method can be used to get result from another activity.  With the help of android startActivityForResult() method, we can send information from one activity to another and vice-versa.  In this case, we need to override the onActivityResult() method that is invoked automatically when second activity returns result.
  • 8. It can be used as :  public void startActivityForResult (Intent intent, int requestCode)  requestCode can be matched in onActivityResult() menthod and then data can be extracted by getStringExtra() method.  Other activity which sends the data should use the same requestCode.  Intent can be started by setResult(requestCode,intent) method and then can be finished by finish() method.
  • 9. Examples  Create an activity to browse a web page (implicit intent example)  Create an application containing two activities. On a click on a button of first activity open second activity. (Explicit intent example)
  • 10. Intent filters :  Used in AndroidManifest.xml  It is used to specify the type of intents that the component would like to receive.  Tag to be used is <intent-filter>  Elements to be used : action, category, data. Example <activity android:name=".ResultActivity"> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAU LT"/> <data android:mimeType="text/plain"/> </intent-filter> </activity>
  • 11. Activity : Activities however are what defines every major stage of your application. It wouldn't be possible to build an application without Activities. You will have a main Activity class and this will indeed be defined with 'extends Activity'.
  • 12. What is an Activity?  An Activity is an application component that provides a screen with which users can interact in order to do something.  Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI.
  • 13. Life cycle of an Activity
  • 14. 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.
  • 15. Broadcast Receiver :  Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself.  Because broadcast receivers are another well- defined entry into the app, the system can deliver broadcasts even to apps that aren't currently running.  Eg , an app can schedule an alarm to post a notification to tell the user about an upcoming event... and by delivering that alarm to a Broadcast Receiver of the app, there is no need for the app to remain running until the alarm goes off.  Broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs
  • 16. Sr.No Event Constant & Description 1 android.intent.action.BATTERY_CHANGED Sticky broadcast containing the charging state, level, and other information about the battery. 2 android.intent.action.BATTERY_LOW Indicates low battery condition on the device. 3 android.intent.action.BATTERY_OKAY Indicates the battery is now okay after being low. 4 android.intent.action.BOOT_COMPLETED This is broadcast once, after the system has finished booting. 5 android.intent.action. AIRPLANE_MODE Show if aeroplane mode on/off 6 android.intent.action.CALL Perform a call to someone specified by the data. 7 android.intent.action.CALL_BUTTON The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call. 8 android.intent.action.DATE_CHANGED The date has changed. 9 android.intent.action.REBOOT Have the device reboot. 10. android.net.conn.CONNECTIVITY_CHANGE : The mobile network or wifi connection is changed(or reset)
  • 17. Steps to use Broadcast receiver : 1. Create a subclass of Broadcast receiver 2. Override onReceive() method and take action to broadcast the message to system 3. Create appropriate intent filter in onStart() of MainActivity.java for the proper action. IntentFilter filter=new IntentFilter("android.intent.action.AIRPLANE_MODE"); 4. Create an object on extended BroadcastReceiver subclass and register it with the intent filter object with registerReceiver() method. 5. Receiver can be unregisterd by unregisterReceiver() in onStop). 6. You may also require to add <receiver> entry in AndroidManifest.xml as follows: <receiver android:name=".MyReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action. AIRPLANE_MODE"/> </intent-filter> </receiver>
  • 18. Files to be created :  activity_main.xml – for layout  MainActivity.java – for code behind  One more java class which is subclass of Broadcast Receiver.  <receiver> tag in AndroidManifest.xml
  • 19. Create an android app using broadcast Receiver to display appropriate messages if Aeroplane mode is on/off
  • 20. Service :  Android Services are the application components that run in the background.  We can understand it as a process that doesn’t need any direct user interaction.  As they perform long-running processes without user intervention, they have no User Interface.  They can be connected to other components and do inter-process communication (IPC).
  • 21. Types of Services : 1. Foreground Services Foreground services are those services that are visible to the users. The users can interact with them at ease and track what’s happening. These services continue to run even when users are using other applications. The perfect example of this is Music Player and Downloading. 2. Background Services These services run in the background, such that the user can’t see or can’t access them. These are the tasks that don’t need the user to know them. Syncing and Storing data can be the best example. 3. Bound Services Bound service runs as long as some other application component is bound to it. Many components can bind to one service at a time, but once they all unbind, the service will destroy.
  • 22. Lifecycle of Android Services Android services life-cycle can have two forms of services and they follow two paths, that are:  Started Service  Bounded Service
  • 24. 1. Started Service : A service becomes started only when an application component calls startService(). It performs a single operation and doesn’t return any result to the caller. Once this service starts, it runs in the background even if the component that created it destroys. This service can be stopped only in one of the two cases: By using the stopService() method. By stopping itself using the stopSelf() method.
  • 25. 2. Bound Service :  A service is bound only if an application component binds to it using bindService(). It gives a client- server relation that lets the components interact with the service. The components can send requests to services and get results.  This service runs in the background as long as another application is bound to it. Or it can be unbound according to our requirement by using the unbindService() method.
  • 26.  When a component wants to bind with the service by calling bindService(), we must provide an interface for clients to communicate with the service. For interprocess communication, we use the IBinder object.  It is a must to implement this method. If in case binding is not required, we should return null as implementation is mandatory.
  • 27.
  • 28.
  • 29. System Services :  Some predefined system services can be made on by getSystemService() method.  Some of the Constants are NOTIFICATION_SERVICE, NETWORK_STATS_SERVICE, POWER_SERVICE, USB_SERVICE, VIBRATOR_SERVICE, WIFI_SERVICE, WINDOW_SERVICE which can be qualified by Context class as follows: getApplicationContext().getSystemService(Context.servicename); Eg getApplicationContext.getSystemService(Context.WIFI_SERVICE);
  • 30.
  • 31. 1. Write a program to start a Wi-Fi using service. 2. Write a program to display the following output :
  • 32. Content Provider • A content provider component supplies data from one application to others on request. • 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. • 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. They handle the access to the central repository and supply data from one application to another on request. • 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.
  • 33. Following are some of the examples for content providers :  The Gallery that contains images.  Contact lists that contain Contact details.  A dictionary that has collections of all the words that are used.  The music playlist has a list of songs.  Call logs contain the call details.
  • 34. How and where content provider is needed in android? Content provider lets us collect the data centrally and provide them to applications. Content providers act the same as database and also we can query it to add, delete, insert or update the data. Content providers are not limited to texts, but also contains images and videos as well.
  • 35. Operations of content Provider:  Content providers provide the following four basic operations. These are also known as CRUD operations, where  Create: It is used for the creation of data in content providers.  Read: It reads the data stored in the content provider.  Update: It lets the editing in existing data in content providers.  Delete: It deletes the existing data stored in its Storage.
  • 36. How is it working as a central repository?
  • 37. 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.
  • 38. • 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 { ……… } • To query a content provider, you specify the query string in the form of a content URI which has following format − content://<authority>/<path>/<optional_id>
  • 39. Content URI − Content URIs are the uniform resource identifiers that identify the data in the content providers. A content URI includes two things: Authority that is the symbolic name of the Provider and a Path that is a name that points towards the data. Every content provider methods have an argument which is URI. content://<authority>/<path>/<optional_id> • content:// – It’s always present, and is the scheme portion of the URI. • authority – It is the unique name of the content provider, like photos, contacts. It’s a string that can identify the whole content provider. • path – It is often used to identify some or the other data of the provider. The path is mostly used to identify individual tables. • optional_id – id is used to access a single particular record of a file. We use this only in cases where we need to access only a particular record and not the complete file. It’s a numeric identifier to access a particular row of the data table. For example, if you are looking for contact number 5 in the Contacts content provider then URI would look like this content://contacts/people/5
  • 40. STEPS TO CREATE YOUR OWN CONTENT PROVIDER: • First of all you need to create a Content Provider class that extends the ContentProvider baseclass. • Second, you need to define your content provider URI address which will be used to access the content. • Next you will need to create your own database to keep the content. Usually, Android uses SQLite database and framework needs to override onCreate() method which will use SQLite Open Helper method to create or open the provider's database. When your application is launched, the onCreate() handler of each of its Content Providers is called on the main application thread. • Next you will have to implement Content Provider queries to perform different database specific operations. • Finally register your Content Provider in your activity file using <provider> tag in AndroidManifest.xml
  • 41. METHODS WHICH YOU NEED TO OVERRIDE IN CONTENT PROVIDER CLASS TO HAVE YOUR CONTENT PROVIDER WORKING • onCreate() This method is called when the provider is started. • query() This method receives a request from a client. The result is returned as a Cursor object. • insert()This method inserts a new record into the content provider. • delete() This method deletes an existing record from the content provider. • update() This method updates an existing record from the content provider. • getType() This method returns the MIME type of the data at the given URI.
  • 42. • Design an app to add and retrieve data from SQLite db using content provider
  • 43. Fragments :  In Android, Fragment is a part of an activity which enables more modular activity design.  we can say a fragment is a kind of sub- activity.  We can combine multiple Fragments in Single Activity to build a multi panel UI and reuse a Fragment in multiple Activities.  Fragments were added in Honeycomb version of Android i.e API version 11.
  • 44.
  • 45.
  • 46.  Fragments has its own layout and its own behavior with its own life cycle callbacks.  Fragments have their own events, layouts and complete life cycle.  Basic tag : <fragment android:id="@+id/fragments" android:layout_width="match_parent" android:layout_height="match_parent" />
  • 47. There are some primary classes related to Fragment’s are:  FragmentActivity: The base class for all activities using compatibility based Fragment (and loader) features.  Fragment: The base class for all Fragment definitions  FragmentManager: The class for interacting with Fragment objects inside an activity  FragmentTransaction: The class for performing an set of Fragment operations such as Replace or Add a Fragment.
  • 48. Lets try this example :
  • 49. TextToSpeech :  Android allows you convert your text into voice.  Not only you can convert it but it also allows you to speak text in variety of different languages.  Android provides TextToSpeech class for this purpose. In order to use this class, you need to instantiate an object of this class and also specify the initListener.  Its syntax is given below − Eg : EditText write; ttobj=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { .. .. } });
  • 50.  In this listener, you have to specify the properties for TextToSpeechobject , such as its language ,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given below − ttobj.setLanguage(Locale.UK);  The method setLanguage takes an Locale object as parameter. Locale can take values as US, CANADA, FRENCH,GERMANY, ITALY, JAPAN, CHINA.  Constructor of TextToSpeech class : TextToSpeech(Context context,TextToSpeech. OnInitListener)  TextToSpeech.OnInitListener Interface You need to implement TextToSpeech.OnInitListener interface, for performing event handling in TextToSpeech engine.
  • 51. There is only one method in this interface. Called to signal the completion of the TextToSpeech engine initialization. The status can be SUCCESS or ERROR. void onInit (int status) `
  • 52. Sensors :  In Android devices, there are various built-in sensors that can be used to measure the orientation, motions, and various other kinds of environmental conditions. In general, there are two types of sensors in Android devices:  Hardware Sensors: Hardware sensors are physical components that are present in Android devices. They can directly measure various properties like field strength, acceleration, etc according to the types of the sensors and after measuring the environment properties they can send the data to Software Sensors.  Software Sensors: Software sensors, also known as virtual sensors are those sensors that take the help of one or more Hardware sensors and based on the data collected by various Hardware sensors, they can derive
  • 53.  It is not necessary that all Android devices must have all the sensors. Some devices may have all sensors and some may lack one or two of them.  To express data values or to collect data, the sensors in Android devices uses a 3-axis coordinate system i.e. you will be having X, Y, and Z-axis. The following figure depicts the position of various axis used in sensors.  In default orientation, the horizontal axis is represented by X- axis, the vertical axis is represented by Y-axis and the Z-axis points towards the outside of the screen face i.e towards the user.
  • 54. Categories of Sensors: The three broad categories of sensors are : 1. Motion Sensors: The sensors that are responsible for measuring or identifying the shakes and tilts of your Android devices are called Motion sensors. These sensors measure the rotational forces along the three- axis. Gravity sensors, accelerometers, etc are some of the examples of Motion sensors. 2. Position Sensors: As the name suggests, the Position sensors are used to determine the position of an Android device. Magnetometers, Proximity sensors are some of the examples of Position sensors. 3. Environmental Sensors: These sensors are useful to measure various environmental parameters, such as ambient air temperature and pressure, illumination, and humidity. This category includes barometers, photometers, and thermometers.
  • 55. classes required to access device sensors Class Description SensorManager By using this class we can create an instance of sensor service and this class provides a various methods for accessing and listing sensors, registering and unregistering sensor event listeners and acquiring orientation information. Sensor By using this class we can create an instance of a specific sensor and this class provides a various methods that let you determine the sensor's capabilities. SensorEvent The system uses this class to create a sensor event object and it provides the raw sensor data, type of sensor that generated the event, accuracy of the data, and the timestamp for the event. SensorEventListener We can use this interface to create two callback methods that receive notifications (sensor events) when sensor values change or when sensor accuracy changes.
  • 56. Different sensor examples are : TYPE_ACCELEROMETER  TYPE_AMBIENT_TEMPERATURE  TYPE_GRAVITY  TYPE_GYROSCOPE  TYPE_LIGHT  TYPE_LINEAR_ACCELERATION  TYPE_MAGNETIC_FIELD  TYPE_ORIENTATION  TYPE_PRESSURE  TYPE_PROXIMITY  TYPE_RELATIVE_HUMIDITY  TYPE_ROTATION_VECTOR  TYPE_TEMPERATURE
  • 57. Media player in android :  By 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.  We can play audio or video files with the multiple playback options such as play, pause, forward, backward, etc.  All audio/video files have to be stored in raw folder under res.
  • 58. We can create object of MediaPlayer class and associate the audio file with it which can be played by start() method of the same as: MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.samplemusic); mPlayer.start(); The second parameter in create() method is the name of the audio file that we want to play from our application resource directory (res/raw). In case if raw folder not exists in your application, create a new raw folder under res directory and add a properly encoded and formatted media files in it. Or if it’s a file from outside resource … MediaPlayer mPlayer = new MediaPlayer(); mPlayer.setDataSource(Envrionment.getExternalStorageDirectory().getPath()”+filepath ); Filepath can be any such as ‘/Music/one.mp3’
  • 59. Method Description getCurrentPosition() It is used to get the current position of song in milliseconds. getDuration() It is used to get the total time duration of song in milliseconds. isPlaying() It returns true / false to indicate whether song playing or not. pause() It is used to pause the song playing. setAudioStreamType() it is used to specify the audio streaming type. setDataSource() It is used to specify the path of audio / video file to play. setVolume() It is used to adjust media player volume either up / down. seekTo(position) It is used to move song to particular position in milliseconds. getTrackInfo() It returns an array of track information. start() It is used to start playing the audio / video. stop() It is used to stop playing the audio / video. reset() It is used to reset the MediaPlayer object.
  • 60. Playing video :  By using VideoView component and MediaController class we can easily implement the video player in android applications.  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.
  • 61. Some of the methods : Method Description setMediaController() It is used to set the media controller to videoview. setVideoURI() It is used to set the path of video file. pause() It is used to pause the video playing. stopPlayback() it is used to stop the video playing. seekTo(position) It is used to move video to particular position in milliseconds. resume() It is used to resume the video playing. start() It is used to start playing the audio / video.
  • 62. Camera :  Camera is mainly used to capture picture and video. We can control the camera by using methods of Camera api.  Android provides the facility to work on camera by 2 ways: I. By Camera Intent II. By Camera API
  • 63.  By the help of 2 constants of MediaStore class, we can capture picture and video without using the instance of Camera class. ACTION_IMAGE_CAPTURE ACTION_VIDEO_CAPTURE  MediaRecorder : It is used to record video using camera. It can also be used to record audio files as we have seen in the previous example of media framework.
  • 64. Some of the actions associated with camera intent :  ACTION_IMAGE_CAPTURE_SECURE  It returns the image captured from the camera , when the device is secured  ACTION_VIDEO_CAPTURE  It calls the existing video application in android to capture video  EXTRA_SCREEN_ORIENTATION  It is used to set the orientation of the screen to vertical or landscape  EXTRA_FULL_SCREEN  It is used to control the user interface of the ViewImage  INTENT_ACTION_VIDEO_CAMERA  This intent is used to launch the camera in the video mode  EXTRA_SIZE_LIMIT  It is used to specify the size limit of video or image capture size
  • 65. Bluetooth:  Bluetooth is a way to send or receive data between two different devices.  Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices.  Android provides Bluetooth API to perform these different operations.  Android provides BluetoothAdapter class to communicate with Bluetooth. Its object can be created as : BluetoothAdapter BA= BluetoothAdapter.getDefaultAdapter(); Then an intent can be created with proper action as : Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOn, 0);
  • 66. There are some more intent actions as:  ACTION_REQUEST_DISCOVERABLE This constant is used for turn on discovering of bluetooth  ACTION_STATE_CHANGED This constant will notify that Bluetooth state has been changed. Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It returns a set of bluetooth devices as : Set <BluetoothDevice>pairedDevices = BA.getBondedDevices(); Some of methods are enable(), disable(), getState(), getName() to manage bluetooth activities.
  • 67. AsyncTask :  Android application runs on a single thread when launched called as UI thread.  Due to this single thread model tasks that take longer time to fetch the response can make the application non-responsive.  To avoid this we use android AsyncTask to perform the heavy tasks in background on a dedicated thread and passing the results back to the UI thread.  Hence use of AsyncTask in android application keeps the UI thread responsive at all times.
  • 68. Following methods are used in an android AsyncTask class :  onPreExecute() : This method contains the code which is executed before the background processing starts.  doInBackground() : This method contains the code which needs to be executed in background. In this method we can send results multiple times to the UI thread by publishProgress() method. To notify that the background processing has been completed we just need to use the return statements.  onProgressUpdate() : This method receives progress updates from doInBackground() method, which is published via publishProgress() method, and this method can use this progress update to update the UI thread  onPostExecute() : This method is called after doInBackground() method completes processing. Result from doInBackground() is passed to this method
  • 69. The three generic types used in an android AsyncTask class are given below : Params : The type of the parameters sent to the task upon execution. Generally used as argument in doInBackground() method. Progress : The type of the progress units published during the background computation. This is used as argument in onProgressUpdate() method. Result : The type of the result of the background computation. Generally the parameter of onPostExecute() which is returned from doInBackgroumd() methd
  • 70. Points to remember while using AsyntTask: • The AsyncTask instance must be created and invoked in the UI thread. • It has to be the inner class of MainActivity. • The methods overridden in the AsyncTask class should never be called. They’re called automatically. • AsyncTask can be called only once. Executing it again will throw an exception. • AsyncTask object can call execute() method to start the thread and execute which accept a url as an argument inside it. • Internet permission is required in AndroidManifest file.
  • 71. SQLite Database in android  SQLite is a Structure query base database, open source, light weight, no network access and standalone database. It supports embedded relational database features.
  • 72. • Whenever an application needs to store large amount of data then using SQLite is more preferable than other repository system . • Android has built in SQLite database implementation. • It is available locally over the device(mobile & tablet) and contain data in text format. • It carry light weight data and suitable with many languages. • So, it doesn’t required any administration or setup procedure of the database.
  • 73. Creating And Updating Database In Android : • For creating, updating and other operations you need to create a subclass or SQLiteOpenHelper class. • SQLiteOpenHelper is a helper class to manage database creation and version management. It provides two methods onCreate(SQLiteDatabase db); onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); • The SQLiteOpenHelper is responsible for opening database if exist, creating database if it does not exists and upgrading if required. • The SQLiteOpenHelper only requires the DATABASE_NAME to create database. • After extending SQLiteOpenHelper you will need to implement its methods onCreate(), onUpgrade() and constructor.
  • 74. onCreate(SQLiteDatabase sqLiteDatabase) method : • It is called only once throughout the application lifecycle. • It will be called whenever there is a first call to getReadableDatabase() or getWritableDatabase() function available in super SQLiteOpenHelper class. • So SQLiteOpenHelper class calls the onCreate() method after creating database and instantiate SQLiteDatabase object. • Database name is passed in constructor call. onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) method : • It is only called whenever there is a updation in existing version. • So to update a version we have to increment the value of version variable passed in the superclass constructor.
  • 75. Insert, Read, Delete & Update Operation In SqLite: • To perform insert, read, delete, update operation there are two different ways: 1) Write parameterized queries (Recommended) with the help of ContentValues object. 2) Write raw queries • Parameterized Queries: These are those queries which are performed using inbuilt functions to insert, read, delete or update data. These operation related functions are provided in SQLiteDatabase class. • Raw Queries: These are simple sql queries similar to other databases like MySql, SqlServer etc, In this case user will have to write query as text and passed the query string in rawQuery(String sql,String [] selectionArgs) or execSQL(String sql,Object [] bindArgs) method to perform operations. • Android documentation don’t recommend to use raw queries to perform insert, read, update, delete operations, always use SQLiteDatabase class’s insert, query, update, delete functions.
  • 76.  insert(…) : To perform insert operation using parameterized query we have to call insert function available in SQLiteDatabase class. insert() function has three parameters as: public long insert(String tableName,String nullColumnHack, ContentValues values) Where,  nullColumnHack may be passed null, it requires table column value in case we don’t put column name in ContentValues object so a null value must be inserted for that particular column, values are those values that needs to be inserted-  ContentValues values is a key-pair based object which accepts all primitive type values so whenever data is being put in ContentValues object, it should be put again table column name as key and data as value.  insert() function will return a long value i.e number of inserted row if successfully inserted, -1 otherwise.
  • 77.  Raw Query example : public void insertItem(Item item) { String query = "INSERT INTO " + ItemTable.NAME + " VALUES (0,?,?)"; SQLiteDatabase db = getWritableDatabase(); db.execSQL(query, new String[]{item.name, item.description}); db.close(); }
  • 78. SQLiteDatabase db=getReadableDatabase(); Cursor cursor =db.rawQuery("select user_name from users where mobile=? and password=?",new String[]{mobile,password});
  • 79. Steps to use SQLite DB(without subclass of SQLiteOpenHelper) :  Create an object of SQLiteDatabase.  Initialize the object as db=openOrCreateDatabase("Student_manage.db", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno INTEGER,name VARCHAR,marks INTEGER);"); Then manage queries for CRUD operation and get them executed as : db.execSQL("INSERT INTO student VALUES('"+eroll_no.getText()+"','"+ename.getText()+ "','"+emarks.getText()+"');");