Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit No.5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

Unit No. 5 Activity and Multimedia with databases.

20M
Syllabus:
5.1 Intent, Intent Filter
5.2 Activity Lifecycle; Broadcast Lifecycle
5.3 Content Provider; Fragments
5.4 Service: Features Of service, 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.
Unit Outcomes (UOs) (in cognitive domain)
• 5a Apply the given Intents and service in Application development.
• 5b Use Fragment to generate the given multiple activities.
• 5c Develop programs to play the given multimedia.
• 5d Write the query to perform the given database management operation.
Assignment Question
1)Write the syntax for Intent-Filter tag. 2M
2) Define services in Android operating system. 2M
3) Explain the activity life cycle. 4M
4) Discuss the need of permissions in Android. Describe the permissions to set
system functionalities like Bluetooth, camera. 4M
5) Describe the significance of SQLite database in Anroid.4M
6) List sensors in Android and explain any one in detail.4M
7) Explain zoom control (IN / OUT) with the help of an example.4M
8)
9) Write a program to capture an image using camera and display it.4M
10) Develop an application to store student details like roll no, name, branch,
marks, percentage and retrieve student information using roll no. in SQLite
databases. 6M
11) Enlist different ways to handle databases in android? Elaborate any one.2M
12)Draw the life cycle of an activity.2M
13) Write steps to develop an android application.4M
14) Define content provider and explain fragments.4M
15) Difference between onStop() & onDestroy() methods,also between onPause()
& onResume() methods.4M
16) Give the hierarchy of directory structure where you store activity file.4M
17) List the best practices for accessing and using sensors in android.4M
18) Write a program to display the list of sensors supported by the mobile
device.4M
19) List all the methods related to camera class.4M
20) Explain the method that is used to detect the face in android.2M
21) Name the methods which are used to enable and disable Bluetooth adapter.2M
22) write the steps to perform Tween Animation.4M
23) Explain the use of from XScale and fromYscale method in detail.2M
24) List the basic methods used in an android AsyncTaskclass.2M
25) Difference between AsyncTask and Services.4M
26) Name the method used, if a process takes a long time to do its work?2M
Intent:
An Intent is a simple message object that is used to communicate between
android components such as activities, content providers, broadcast receivers and
services. Intents are also used to transfer data between activities.
Intent facilitate you to redirect your activity to another activity on occurrence of
any event. By calling, startActivity() you can perform this task.
For Example:
Intent intent = new Intent (getApplicationContext(), SecondActivity.class);
startActivity(intent)
In the above example, foreground activity is getting redirected to another activity
i.e. SecondActivity.java.
getApplicationContext() returns the context for your foreground activity.
Use of Intent:
1. For Launching an Activity
2. To start a New Service
3. For Broadcasting Messages
4. To Display a list of contacts in ListView
Types of Intent
1. Implicit Intent
2. Explicit Intent
1. Explicit Intent:
• Explicit Intents is 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.
• If you want communication between the components of your application only
then you can use the Explicit Intents.
• Explicit Intents are used to communicate with a particular component of the
same application.
• For example, if you want to launch an Activity by clicking some button on the
present Activity then you can specify the fully-qualified address of the desired
Activity to launch that Activity.
Intent intent = new Intent (getApplicationContext(), SecondActivity.class);
• startActivity(intent);
Implicit Intent:
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.
In this don’t need to specify the fully-qualified address. Just you need to specify the action
that is to be performed by an Intent.
By using the Implicit Intents you can communicate between various applications present in
the mobile device. For example, you can access the current location by accessing the location
data from other application also i.e. if one application A is detecting the current location of the
user then you can use the data of the user i.e. the current location by communicating with
application A.

The basic example of implicit Intent is to open any web page


Intent intent=new Intent (Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.google.com"));
startActivity(intent);
Intent_Filter:
Android OS uses filters to pinpoint the set of Activities, Services, and
Broadcast receivers that can handle the Intent with help of specified set of
action, categories, data scheme associated with an Intent.
An intent filter is an expression in an app's manifest file that specifies the
type of intents that the component would like to receive.
For instance, by declaring an intent filter for an activity, you make it
possible for other apps to directly start your activity with a certain kind of
intent. Likewise, if you do not declare any intent filters for an activity, then
it can be started only with an implicit intent.
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.
5.2 Activity Lifecycle, Broadcast Lifecycle:
Android Activity Lifecycle is controlled by 7 methods of
android.app.Activity class.
The android Activity is the subclass of ContextThemeWrapper class.
An activity is the single screen in android. It is like window or frame of
Java.
By the help of activity, you can place all your UI components or widgets in
a single screen.
The onCreate() and onDestroy() methods are called only once throughout
the activity lifecycle.
Life Cycle Methods and Callbacks In general, activity lifecycle has seven
callback methods:
Life cycle activity
1) onCreate()
2) onStart()
3) onResume()
4) onPause()
5) onStop()
6) onRestart()
7) onDestroy()
1. onCreate(): In this state, the activity is created.
2. onStart(): This callback method is called when the activity becomes visible to the user.
3. onResume(): The activity is in the foreground and the user can interact with it.
4. onPause(): Activity is partially obscured by another activity. Another activity that’s in the
foreground
is semi-transparent.
5. onStop(): The activity is completely hidden and not visible to the user.
6. onRestart(): From the Stopped state, the activity either comes back to interact with the
user or the
activity is finished running and goes away. If the activity comes back, the system invokes
onRestart()
7. onDestroy(): Activity is destroyed and removed from the memory.
So these are the various methods of the Activity Life Cycle. Now let’s see the situations
where the life
cycle methods and states will occur.
When you open the app it will go through below states:
onCreate() –> onStart() –> onResume()
So these are the various methods of the Activity Life Cycle. Now let’s see the situations
where the life
cycle methods and states will occur.
When you open the app it will go through below states:
onCreate() –> onStart() –> onResume()
When you press the back button and exit the app
onPaused() — > onStop() –> onDestory()
When you press the home button
onPaused() –> onStop()
After pressing the home button, again when you open the app from a recent task list
onRestart() –> onStart() –> onResume()
After dismissing the dialog or back button from the dialog
onResume()
After dismissing the dialog or back button from the dialog
onResume()
If a phone is ringing and user is using the app
onPause() –> onResume()
After the call ends
onResume()
When your phone screen is off
onPaused() –> onStop()
When your phone screen is turned back on
onRestart() –> onStart() –> onResume()
Broadcast lifecycle:
We know that intents are of two types as implicit and explicit intents.
1. Implicit intents are used to start activities based on registered components that the system
is aware of for example general functionality.
2. Explicit intents are used to start specific fully qualified activities as well as pass
information between activities in your app.
Broadcast Intents:
We required third types of intent that can be delivered to any interested application known
as the broadcast intent.
Broadcast intents are delivered using sendBroadcast() or a related method
A broadcast intent is background operation, on the other hand, is a foreground operation that
modifies what the user is currently interacting with.
Following are two types of broadcast intents:
System Broadcast intents (Those delivered by the system)
Custom Broadcast Intents (Those that your app delivers)
System Broadcast Intents:
Delivers a system broadcast intent when a system event occurs that might interest your app.
In this intent events are defined as final static fields in the intent class . for example the
Telephony Manager defines events for the change of the phone state.
Custom Broadcast Intents:
Custom broadcast intents are broadcast intents that your application sends out. Use a custom
broadcast intent when you want your app take an action without launching an activity.
For example when you want to let other apps know that data has been downloaded to the
device and is available for them to use.
Broadcast Receivers:
Broadcast intents aren’t targeted at specific recipients. Instead interested
apps register a component to “listen” for these kinds of intents. This
listening component is called a broadcast receiver.
1. Creating the Broadcast Receiver:
Implement as subclass of BroadcastReceiver class and overriding the
onReceive(); method in this each message is received as a Intent object
parameter.
2. Receiving Broadcast Receiver:
By registering a broadcast receiver in AndroidManifest.xml file.
5.3 Content Provider, Fragments
• Fragments: A fragment is an independent Android component which can
be used by an activity. A fragment encapsulates functionality so that it is
easier to reuse within activities and layouts.
How to use Fragments?
This involves number of simple steps to create Fragments.
1) First of all decide how many fragments you want to use in an activity.
For example let's we want to use two fragments to handle landscape and
portrait modes of the device.
2) Next based on number of fragments, create classes which will extend
the Fragment class. The Fragment class has above mentioned callback
functions. You can override any of the functions based on your
requirements.
3) Corresponding to each fragment, you will need to create layout files in
XML file. These files will have layout for the defined fragments.
4) Finally modify activity file to define the actual logic of replacing
fragments based on your requirement.
Creating Fragment:
To create a fragment, you must create a subclass of Fragment (or an existing
subclass of it).
The Fragment class has code that looks a lot like an Activity. It contains callback
methods similar to an activity, such as onCreate(), onStart(), onPause(), and
onStop().
In fact, if you're converting an existing Android application to use fragments, you
might simply move code from your activity's callback methods into the
respective callback methods of your fragment.
onCreate(): The system calls this when creating the fragment. Within your
implementation, you should initialize essential components of the fragment that
you want to retain when the fragment is paused or stopped, then resumed.
onCreateView()
The system calls this when it's time for the fragment to draw its user
interface for the first time. To draw a UI for your fragment, you must return
a View from this method that is the root of your fragment's layout.
You can return null if the fragment does not provide a UI.
onPause()
The system calls this method as the first indication that the user is leaving
the fragment (though it doesn't always mean the fragment is being
destroyed). This is usually where you should commit any changes that
should be persisted beyond the current user session (because the user might
not come back).
Content Provider
A content provider component supplies data from one application to others on request.
Such requests are handled by the methods of the ContentResolver class. The data may be
stored in the file system, the database or somewhere else entirely.
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.
In android, Content Provider will act as a central repository to store the applicationsdata
in one place and make that data available for different applications to access whenever it’s
required.
In android, we can configure Content Providers to allow other applications securely
access and modify our app data based on our requirements.

Generally, the Content Provider is a part of an android application and it will act as
morelike relational database to store the app data. We can perform a multiple operations
like insert, update, delete and edit on the data stored in content provider using insert(),
update(), delete() and query() methods.
Access Data from Content Provider
• To access a data from content provider, we need to use ContentResolver
object in our application to communicate with the provider as a client. The
ContentResolver object will communicate with the provider object
(ContentProvider) which is implemented by instance of class.
• Following is the pictorial representation of requesting an operation from UI
using Activity or Fragment to get the data from ContentProvider object.
Content URIs
In android, Content URI is an URI which is used to query a content provider
to get the required data. The Content URIs will contain the name of entire
provider (authority) and the name that points to a table (path).
Generally the format of URI in android applications will be like as shown
below content://authority/path
Following are the details about various parts of an URI in android
application.
content:// - The string content:// is always present in the URI and it is used to
represent the given URI is a content URI.
Creating a Content Provider
To create a content provider in android applications we
should follow below steps.
• We need to create a content provider class that extends the
ContentProvider baseclass.
• We need to define our content provider URI to access the
content.
• The ContentProvider class defines a six abstract methods
(insert(), update(), delete(), query(), getType()) which we
need to implement all these methods as apart of our subclass.
• We need to register our content provider in
AndroidManifest.xml using tag. Following are the list of
methods which need to implement as a partof
ContentProvider class.
query() - It receives a request from the client. By using arguments it will get a
data from requested table and return the data as a Cursor object.
insert() - This method will insert a new row into our content provider and it will
returnthe content URI for newly inserted row.
update() - This method will update an existing rows in our content provider and
it return the number of rows updated.
delete() - This method will delete the rows in our content provider and it return
the number of rows deleted.
getType() - This method will return the MIME type of data to given content
URI.
onCreate() - This method will initialize our provider. The android system will
call this method immediately after it creates our provider.
5.4 Service: Features Of service, Android platform service, Defining new
service, Service Lifecycle, Permission, example of service
Android Service
Android service is a component that is used to perform operations on the
background such as playing music, handle network transactions, interacting
content providers etc.
It doesn't has any UI (user interface). The service runs in the background
indefinitely even if application is destroyed.
Moreover, service can be bounded by a component to perform interactivity
and inter process communication (IPC).
Features of Service
• Service is an Android Component without an UI
• It is used to perform long running operations in background. Services run
indefinitly unless they are explicitly stopped or destroyed
• It can be started by any other application component. Components can
even infactbind to a service to perform Interprocess- Comminication
• It can still be running even if the application is killed unless it stops itself
by calling stopself() or is stopped by a Android component by calling
stopService().
• If not stopped it goes on running unless is terminated by Android due to
resource shortage
• The android.app.Service is subclass of ContextWrapper class.
Android platform service
The Android platform provides and runs predefined system services and
every Android application can use them, given the right permissions.
These system services are usually exposed via a specific Manager class.
Access to them can be gained via the getSystemService() method.
Permission
The purpose of a permission is to protect the privacy of an Android user.
Android apps must request permission to access sensitive user data (such as
contacts and SMS), as well as certain system features (such as camera and
internet).
Depending on the feature, the system might grant the permission
automatically or might prompt the user to approve the request.
Life Cycle of Android Service
• There can be two forms of a service.
• The lifecycle of service can follow two different paths: started or bound.
1. Started 2. Bound
1) Started Service: A service is started when component (like activity)
calls startService() method, now it runs in the background indefinitely. It
is stopped by stopService() method. The service can stop itself by calling
the stopSelf() method.
2) Bound Service:A service is bound when another component (e.g. client)
calls bindService() method. The client can unbind the service by calling the
unbindService() method. The service cannot be stopped until all clients
unbind the service.
onCreate(): This is the first callback which will be invoked when any component
starts the service. If the same service is called again while it is still running this method
wont be invoked. Ideally one time setup and intializing should be done in this callback.
onStartCommand(): This callback is invoked when service is started by any
component by calling startService(). It basically indicates that the service has started
and can now run indefinetly.
onBind(): This is invoked when any component starts the service by calling onBind.
onUnbind():This is invoked when all the clients are disconnected from the service.
onRebind():This is invoked when new clients are connected to the service. It is called
after onUnbind
onDestroy():This is a final clean up call from the system. This is invoked just before
the service is being destroyed. Could be very useful to cleanup any resources such as
threads, registered listeners, or receivers.
5.5 Android System Architecture, Multimedia framework, Play
Audio and Video, Text to speech, Sensors, Async tasks
• Android System Architecture:The android system consists of five layers and each
layer consists of some core components. Already shown the architecture of android.
• From top to down, the core components are: Applications, Application Framework,
Native C libraries, Android Runtime Environment (JVM), HAL (Hardware Abstract
Layer), Linux Kernel.
• 1) Applications. Application layer consists of many core Java-based applications,
such as calendar, web browser, SMS application, E-mail, etc.
• 2) Application Framework. Application framework consists of many components and
Java classes to allow android application developers to develop various kinds of
applications. By using Java language, it hides the internal implementation of system
core functions and provides the developers an easy-use API. Basically, it includes
Java core class and some special components of android. Some typical components
are as follows: View (List, Grids), Content Provider, Resource Manager, Activity
Manager.
3) Native C Libraries. In Native C library layer, it consists of many C/C++
libraries. And the core functions of android are implemented by those libraries.
Some typical core libraries are as follows: Bionic C lib, OpenCore, SQLite,
Surface Manager, WebKit, 3D library.
4) Android Runtime Environment. Runtime environment consists of Dalvik Java
virtual machine and some implementations of Java core libraries.
5) HAL. This layer abstracts different kinds of hardwares and provides an
unified program interface to Native C libraries. HAL can make Android port on
different platforms more easily.
6) Linux Kernel. Android’s core system functions (e.g., safety management,
RAM management, process management, network stack) depend on Linux
kernels.
Android Multimedia framework
• The android multimedia system
includes multimedia applications,
multimedia framework, OpenCore
engine and hardware abstract for
audio/video input/output devices.
• And the goal of the android multimedia
framework is to provide a consistent
interface for Java services.
• At the native level, Android provides a
multimedia framework that utilizes the
Stagefright engine for audio and video
recording and playback. Stagefright
comes with a default list of supported
software codecs and you can implement
your own hardware codec by using the
OpenMax integration layer standard.
Application Framework
At the application framework level is application code that utilizes android.media APIs
to interact with the multimedia hardware.
Binder IPC
The Binder IPC proxies facilitate communication over process boundaries. They are
located in the frameworks/av/media/libmedia directory and begin with the letter "I".
Native Multimedia Framework
At the native level, Android provides a multimedia framework that utilizes the
Stagefright engine for audio and video recording and playback. Stagefright comes with
a default list of supported software codecs and you can implement your own hardware
codec by using the OpenMax integration layer standard. For more implementation
details, see the MediaPlayer and Stagefright components located in
frameworks/av/media.
OpenMAX Integration Layer (IL)
The OpenMAX IL provides a standardized way for Stagefright to recognize and use
custom hardware-based multimedia codecs called components. You must provide an
OpenMAX plugin in the form of a shared library named libstagefrighthw.so. This
plugin links Stagefright with your custom codec components, which must be
implemented according to the OpenMAX IL component standard.
Play Audio and Video
We can play and control the audio files in android by the help of Media
Player class. Here, we are going to see a simple example to play the audio
file. In the next page, we will see the example to control the audio playback
like start, stop, pause etc.
MediaPlayer class:
The android.media.MediaPlayer class is used to control the audio or video
files. Methods of MediaPlayer class There are many methods of
MediaPlayer class. Some of them are as follows:
Android Video Player
Example By the help of MediaController and VideoView classes, we can play the
video files in android.
MediaController class
The android.widget.MediaController is a view that contains media controls like
play/pause, previous, next, fast-forward, rewind etc.
VideoView class
The android.widget.VideoView class provides methods to play and control the
video player. The commonly used methods of VideoView class are as follows:
Text To Speech:
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.
It’s syntax is given below
private EditText write; ttobj=newTextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() { @Override public void onInit(int status) { }
});
• Android Sensor: Sensors can be used to monitor the three-
dimensional device movement or change in the environment of
the device. Android provides sensor api to work with different
types of sensors.
• Types of Sensors Android supports three types of sensors:
• 1) Motion Sensors :These are used to measure acceleration
forces and rotational forces along with three axes.
• 2) Position Sensors: These are used to measure the physical
position of device.
• 3) Environmental Sensors: These are used to measure the
environmental changes such as temperature, humidity etc.
• Android Sensor API :Android sensor api provides many classes and interface.
The important classes and interfaces of sensor api are as follows:
• 1) SensorManager class The android.hardware.SensorManager class provides
methods.
• to get sensor instance.
• to access and list sensors,
• to register and unregister sensor listeners etc.
• You can get the instance of SensorManager by calling the method
getSystemService() and passing the SENSOR_SERVICE constant in it.
SensorManager sm
=(SensorManager)getSystemService(SENSOR_SERVICE);
• 2) Sensor class: The android.hardware.Sensor class provides methods to get
information of the sensor such as sensor name, sensor type, sensor resolution,
sensor type etc.
• 3) SensorEvent class: Its instance is created by the system. It provides
information about the sensor.
• 4) SensorEventListener interface:It provides two call back methods to get
information when sensor values (x,y and z) change or sensor accuracy changes.
• AsyncTask: Android AsyncTask is an abstract class provided by Android
which gives us the liberty to perform heavy tasks in the background and
keep the UI thread light thus making the application more responsive.
• Android application runs on a single thread when launched. 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.
• The basic methods used in an android AsyncTask class are defined below :
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.
Progress : The type of the progress units published during the background
computation.
• Result : The type of the result of the background computation Android
AsyncTask
• Example To start an AsyncTask the following snippet must be present in
the MainActivity class :
• MyTask myTask = new MyTask(); myTask.execute();
• In the above snippet we’ve used a sample classname that extends
AsyncTask and execute method is used to start the background thread.
5.6 Audio Capture, Camera
Audio Capture: Android has a built in microphone through which you can
capture audio and store it , or play it in your phone. There are many ways to
do that but the most common way is through MediaRecorder class.
Android provides MediaRecorder class to record audio or video. In order to
use MediaRecorder class ,you will first create an instance of
MediaRecorder class. Its syntax is given below.

Now you will set the source , output and encoding format and output file. Their
syntax is given below.
• After specifying the audio source and format and its output file, we can then call
the two basic methods prepare and start to start recording the audio.

• Apart from these methods , there are other methods listed in the MediaRecorder
class that allows you more control over audio and video recording.
• Camera :In Android In Android, Camera is a hardware device that allows
capturing pictures and videos in your applications. Follow this tutorial to
easily understand how to use a camera in your own Android App. Android
provides the facility to work on camera by 2 ways:
• 1. By Camera Intent
• 2. By Camera API
• 1 Using Camera By Using Camera Application We can capture pictures
without using the instance of Camera class. Here you will use an intent
action type of MediaStore.ACTION_IMAGE_CAPTURE to launch an
existing Camera application on your phone. In Android MediaStore is a
type of DataBase which stores pictures and videos in android.
• Intent cameraIntent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
2 Using Camera By using Camera Api: This class is used for controlling
device cameras. It can be used to take pictures when you are building a
camera application.
Camera API works in following ways:
1.Camera Manager: This is used to get all the cameras available in the
device like front camera back camera each having the camera id.
2.CameraDevice: You can get it from Camera Manager class by its id.
3.CaptureRequest: You can create a capture request from camera device to
capture images.
4.CameraCaptureSession: To get capture request’s from Camera Device
create a CameraCaptureSession.
5.CameraCaptureSession.CaptureCallback: This is going to provide the
Capture session results.
Camera Permission Declarations: In Manifest First, you should declare the
Camera requirement in your Manifest file if Camera is compulsory for your
application and you don’t want your application to be installed on a device that
does not support Camera.
Before you start development on your application you have to make sure that
your Manifest has appropriate declarations in it that will allow you to use Camera
feature in your Application.
5.7 Bluetooth, Animation
•Bluetooth is a way to exchange data with other
devices wirelessly. Android provides Bluetooth API to
perform several tasks such as:
•scan bluetooth devices
•connect and transfer data from and to other devices
•manage multiple connections etc.
• Android Bluetooth API :The android.bluetooth package provides a lot of
interfaces classes to work with bluetoothsuch as:
• BluetoothAdapter
• BluetoothDevice
• BluetoothSocket
• BluetoothServerSocket
• BluetoothClass
• BluetoothProfile
• BluetoothProfile.ServiceListener
• BluetoothHeadset
• BluetoothA2dp
• BluetoothHealth
• BluetoothHealthCallback
• BluetoothHealthAppConfiguratio
• BluetoothAdapter class
• By the help of BluetoothAdapter class, we can perform fundamental tasks
such as initiatedevice discovery, query a list of paired (bonded) devices,
create a BluetoothServerSocketinstance to listen for connection requests
etc.
• Constants of BluetoothAdapter class
• BluetoothAdapter class provides many constants. Some of them are as
follows:
• String ACTION_REQUEST_ENABLE
• String ACTION_REQUEST_DISCOVERABLE
• String ACTION_DISCOVERY_STARTED
• String ACTION_DISCOVERY_FINISHED
• Methods of BluetoothAdapter class:Commonly used methods of
BluetoothAdapter class are as follows:
• static synchronized BluetoothAdapter
• getDefaultAdapter() returns the instance of BluetoothAdapter.
• boolean enable() enables the bluetooth adapter if it is disabled.
• boolean isEnabled() returns true if the bluetooth adapter is enabled.
• boolean disable() disables the bluetooth adapter if it is enabled.
• String getName() returns the name of the bluetooth adapter.
• boolean setName(String name) changes the bluetooth name.
• int getState() returns the current state of the local bluetooth adapter. o Set
getBondedDevices() returns a set of paired (bonded) BluetoothDevice objects.
• boolean startDiscovery() starts the discovery process.
Android Animation
• Aanimation in android apps is the process of creating motion and shape change.
Android Animation Example XML We create a resource directory under the res
folder names anim to keep all the xml files containing the animation logic.
Following is a sample xml file showing an android animation code logic.
sample_animation.xml
android:interpolator : It is the rate of change in animation. We can define our own
interpolators using the time as the constraint. In the above xml code an inbuilt
interpolator is assigned.
android:duration : Duration of the animation in which the animation should
complete. It is 300ms here. This is generally the ideal duration to show the
transition on the screen.
The start and end of the animation are set using
android:fromTRANSFORMATION
android:toTRANSFORMATION
• TRANSFORMATION : is the transformation that we want to specify. In
our case we start with an x and y scale of 0 and end with an x and y scale
of 1.
• android:fillAfter : property specifies whether the view should be visible or
hidden at theend of the animation. We’ve set it visible in the above code.
If it sets to false, the element changes to its previous state after the
animation.
• android:startOffset : It is the waiting time before an animation starts. This
property is mainly used to perform multiple animations in a sequential
manner .
• android:repeatMode : This is useful when you want the animation to be
repeat.
• android:repeatCount : This defines number of repetitions on animation. If
we set this value to infinite then animation will repeat infinite times.
• Setting the Animation Listeners: This is only
needed if we wish to listen to events like start,
end or repeat. For this the activity must
implement.
• AnimationListener and the following methods
need to overridden.
• onAnimationStart : This will be triggered once
the animation started onAnimationEnd : This
will be triggered once the animation is over.
• onAnimationRepeat : This will be triggered if
the animation repeats.
5.8 SQLite Database, necessity of SQLite, Creation and connection of the
database, extracting value from cursors, Transactions.
Android SQLite Database
Android SQLite is the mostly preferred way to store data for android
applications. For many applications, SQLite is the apps backbone whether it’s
used directly or via some third-party wrapper. Below is the final app we will
create today using Android SQLite database.
Android SQLite: Android SQLite is a very lightweight database which comes
with Android OS. Android SQLite combines a clean SQL interface with a very
small memory footprint and decent speed. For Android, SQLite is “baked into”
the Android runtime, so every Android application can create its own SQLite
databases.
Android SQLite native API is not JDBC, as JDBC might be too much
overhead for a memory-limited smartphone. Once a database is created
successfully its located in data/data//databases/ accessible from Android
Device Monitor.
SQLite is a typical relational database, containing tables (which consists of
rows and columns), indexes etc. We can create our own tables to hold the
data accordingly. This structure is referred to as a schema.
Android SQLite SQLiteOpenHelper Android has features available to handle
changing database schemas, which mostly depend on using the
SQLiteOpenHelper class.
SQLiteOpenHelper is designed to get rid of two very common problems.
1. When the application runs the first time – At this point, we do not yet have a
database. So we will have to create the tables, indexes, starter data, and so on.
2. When the application is upgraded to a newer schema – Our database will still
be on the old schema from the older edition of the app.
• We will have option to alter the database schema to match the needs of the rest
of the app.
• SQLiteOpenHelper wraps up these logic to create and upgrade a database as
per our specifications. For that we’ll need to create a custom subclass of
SQLiteOpenHelper implementing at least the following three methods.
• 1. Constructor : This takes the Context (e.g., an Activity), the name of the
database, an optional cursor factory (we’ll discuss this later), and an integer
representing the version of the database schema you are using (typically
starting from 1 and increment later).
• 2. public DatabaseHelper(Context context) { super(context, DB_NAME, null,
DB_VERSION); }
onCreate(SQLiteDatabase db) : It’s called when there is no database and
the app needsone. It passes us a SQLiteDatabase object, pointing to a newly-
created database, that we can populate with tables and initial data
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) : It’s
called when the schema version we need does not match the schema version
of the database, It passes us a SQLiteDatabase object and the old and new
version numbers. Hence we can figure out the best way to convert the
database from the old schema to the new one. We define a DBManager class
to perform all database CRUD(Create, Read, Update and Delete) operations.
SQLite Transaction: Transactions are units or sequences of work
accomplished in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program. A transaction is the
propagation of one or more changes to the database. For example, if you are
creating, updating, or deleting a record from the table, then you are
performing transaction on the table. It is important to control transactions
toensure data integrity and to handle database errors.
• SQLite & ACID SQLite is a transactional database that all changes and queries are
atomic, consistent, isolated, and durable (ACID). SQLite guarantees all the
transactions are ACID compliant even if the transaction is interrupted by a program
crash, operation system dump, or power failure to the computer.
• Atomic: a transaction should be atomic. It means that a change cannot be broken
down into smaller ones. When you commit a transaction, either the entire transaction
is applied or not.
• Consistent: a transaction must ensure to change the database from one valid state to
another. When a transaction starts and executes a statement to modify data, the
database becomes inconsistent. However, when the transaction is committed or rolled
back, it is important that the transaction must keep the database consistent.
• Isolation: a pending transaction performed by a session must be isolated from other
sessions. When a session starts a transaction and executes the INSERT or UPDATE
statement to change the data, these changes are only visible to the current session, not
others. On the other hand, the changes committed by other sessions after the
transaction started should not be visible to the current session.
• Durable: if a transaction is successfully committed, the changes must be permanent
in the database regardless of the condition such as power failure or program crash.
On the contrary, if the program crashes before the transaction is committed, the
change should not persist.
SQLite transaction statements By default, SQLite operates in auto-commit mode.
It means that for each command, SQLite starts, processes, and commits the
transaction automatically.
To start a transaction explicitly, you use the following steps:
• First, open a transaction by issuing the BEGIN TRANSACTION command.
BEGIN TRANSACTION; After executing the statement BEGIN
TRANSACTION, the transaction is open until it is explicitly committed or rolled
back.
• Second, issue SQL statements to select or update data in the database. Note that
the change is only visible to the current session (or client).
• Third, commit the changes to the database by using the COMMIT or COMMIT
TRANSACTION statement.
COMMIT;
• If you do not want to save the changes, you can roll back usingthe ROLLBACK
or ROLLBACK TRANSACTION statement:
ROLLBACK;

You might also like