ANDOID O NOTES Ch5
ANDOID O NOTES Ch5
Intent:
Android uses Intent for communicating between the components of an Application and also from
one application to another application.
Intent are the objects which is used in android for passing the information among
Activities in an Application and from one app to another also. Intent are used for communicating
between the Application components and it also provides the connectivity between two apps.
Example-
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
getApplicationContext() returns the context for your foreground activity.
Types of intent:
Explicit Intent:
Explicit Intents are used to connect the application internally.
Explicit Intent work internally within an application to perform navigation and data
transfer.
Example-
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
Implicit Intent:
In Implicit Intents we do need to specify the name of the component. We just specify the
Action which has to be performed and further this action is handled by the component of another
application.
The basic example of implicit Intent is to open any web page
Example-
Intent intentObj = new Intent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.abhiandroid.com"));
startActivity(intentObj);
Intent Filter:
-decide the behavior of an intent.
-Intent about the navigation of one activity to another,that can be achieve by
declaring intent filter.
-We can declare an Intent Filter for an Activity in manifest file.
- Intent filters specify the type of intents that an Activity, service or Broadcast receiver can
respond to.
• Syntax of Intent Filters:
<activity android:name=".MainActivity">
<intent-filter
android:icon="@drawable/icon" android:label="@string/label" >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter>
</activity>
• icon: This is displayed as icon for activity. You can check or save png image of name
icon in drawable folder.
android:icon="@drawable/icon"
• label: The label / title that appears at top in Toolbar of that particular Activity. You can
check or edit label name by opening String XML file present inside Values folder
android:label = "@string/label“
or
android:label = "New Activity“
Just like icon attribute, if you have not declared any label for your activity then it
will be same as your parent activity.
• Elements In Intent Filter:
There are following three elements in an intent filter:
1.Action
2.Data
3.Category
Activity Lifecycle:
Activity is a screen that user interact with. Every Activity in android has lifecycle
like created, started, resumed, paused, stopped or destroyed. These different states are
known as Activity Lifecycle.
onCreate() – Called when the activity is first created
onStart() – Called just after it’s creation or by restart method after onStop(). Here
Activity start becoming visible to user
onResume() –
Called when Activity is visible to user and user can interact with it
onPause() – Called when Activity content is not visible because user resume previous
activity
onStop() – Called when activity is not visible to user because some other activity takes
place of it
onRestart() – Called when user comes on screen or resume the activity which was
stopped
onDestroy – Called when Activity is not in background
Diagram:
Broadcast Receiver
Broadcast Receiver is a component which will allow android system or other apps to
deliver events to the app like sending a low battery message or screen turned off message to the
app. The apps can also initiate broadcasts to let other apps know that required data available in a
device to use it.
Generally, we use Intents to deliver broadcast events to other apps and Broadcast
Receivers use status bar notifications to let user know that broadcast event occurs.
is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as
an Intent object.
Content Provider:
Content Provider will act as a central repository to store the applications data in one
place and make that data available for different applications to access whenever it’s required.
the Content Provider is a part of an android application and it will act as more like
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.
content provider is having different ways to store app data. The app data can be stored in
a SQLite database or in files or even over a network based on our requirements. By using content
providers we can manage data such as audio, video, images and personal contact information.
• ContentResolver-
To access a data from content provider,
we need to use ContentResolver
• CursorLoader-
is used to run the query asynchronously in
background
• ContentProvider-
receive a data requests from client,
performs the requested actions
(create, update, delete, retrieve)
and return the result.
• Content URIs:
To query a content provider, you specify the query string in the form of a URI which has
following format −
content://authority/path
content:// - The string content:// is always present in the URI
authority - It represents the name of content provider
path - It represents the table’s path.
The ContentResolver object use the URI’s authority to find the appropriate provider and
send the query objects to the correct provider. After that ContentProvider uses the path of
content URI to choose the right table to access.
To create a content provider in android applications we should follow below
steps.
1. We need to create a content provider class that extends the ContentProvider base class.
2. We need to define our content provider URI to access the content.
3. The ContentProvider class defines a six abstract methods (insert(), update(), delete(),
query(), getType()) which we need to implement all these methods as a part of our
subclass.
4. We need to register our content provider in AndroidManifest.xml using <provider> tag.
Methods:
1. 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.
2. insert() - This method will insert a new row into our content provider and it will
return the content URI for newly inserted row.
3. update() - This method will update an existing rows in our content provider and it
return the number of rows updated.
4. delete() - This method will delete the rows in our content provider and it return the
number of rows deleted.
5. getType() - This method will return the MIME type of data to given content URI.
6. onCreate() - This method will initialize our provider. The android system will call
this method immediately after it creates our provider.
Fragment:
Fragment is a part of an activity which enable more modular activity design. It will not be wrong
if we 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.
• A fragment has its own layout and its own behaviour with its own life cycle callbacks.
• You can add or remove fragments in an activity while the activity is running.
• You can combine multiple fragments in a single activity to build a multi-pane UI.
• A fragment can be used in multiple activities.
• Fragment life cycle is closely related to the life cycle of its host activity which means
when the activity is paused, all the fragments available in the activity will also be
stopped.
Need of Fragment:
• Before the introduction of Fragment’s we can only show a single Activity on the screen
at one given point of time so we were not able to divide the screen and control different
parts separately. With the help of Fragment’s we can divide the screens in different parts
and controls different parts separately.
• By using Fragments we can comprise multiple Fragments in a single Activity. Fragments
have their own events, layouts and complete life cycle. It provide flexibility and also
removed the limitation of single Activity on the screen at a time.
Types of Fragment :
• Single frame fragments − Single frame fragments are using for hand hold devices like
mobiles, here we can show only one fragment as a view.
• List fragments − fragments having special list view is called as list fragment
• Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment
Services:
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.
• three different types of services:
1. Foreground- A foreground service performs some operation that is noticeable to
the user.
2. Background- A background service performs an operation that isn't directly
noticed by the user.
3. Bound- A service is bound when an application component binds to it by
calling bindService(). A bound service offers a client-server interface that allows components
to interact with the service, send requests, receive results, and even do so across processes
with interprocess communication (IPC). A bound service runs only as long as another
application component is bound to it. Multiple components can bind to the service at once,
but when all of them unbind, the service is destroyed.
A service can essentially take two states −
• Started
A service is started when an application component, such as an activity, starts it by
calling startService(). Once started, a service can run in the background indefinitely, even if
the component that started it is destroyed.
• Bound
A service is bound when an application component binds to it by calling bindService().
A bound service offers a client-server interface that allows components to interact with the
service, send requests, get results, and even do so across processes with interprocess
communication (IPC).
The onStartCommand() method will return a value from one of the following
constants.
1. START_STICKY
It will restart the service in case if it terminated and the Intent data which is passed
to onStartCommand() method is NULL. This is suitable for the service which are not executing
commands but running independently and waiting for the job.
2. START_NOT_STICKY
It will not restart the service and it is useful for the services which will run periodically. The
service will restart only when there are a pending startService() calls. It’s a best option to
avoid running a service in case if it is not necessary.
3. START_REDELIVER_INTENT
It’s same as STAR_STICY and it recreates the service, call onStartCommand() with
last intent that was delivered to the service.
Android Architecture:
Android operating system is a stack of software components which is roughly divided into
five sections and four main layers as shown below in the architecture diagram.
Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This provides a
level of abstraction between the device hardware and it contains all the essential hardware drivers
like camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good
at such as networking and a vast array of device drivers, which take the pain out of interfacing to
peripheral hardware.
Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine
WebKit, well known library libc, SQLite database which is a useful repository for storage and
sharing of application data, libraries to play and record audio and video, SSL libraries responsible
for Internet security etc.
Android Libraries
This category encompasses those Java-based libraries that are specific to Android development.
Examples of libraries in this category include the application framework libraries in addition to
those that facilitate user interface building, graphics drawing and database access. A summary of
some key core Android libraries available to the Android developer is as follows −
• android.app − Provides access to the application model and is the cornerstone of all
Android applications.
• android.content − Facilitates content access, publishing and messaging between
applications and application components.
• android.database − Used to access data published by content providers and includes
SQLite database management classes.
• android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.
• android.os − Provides applications with access to standard operating system services
including messages, system services and inter-process communication.
• android.text − Used to render and manipulate text on a device display.
• android.view − The fundamental building blocks of application user interfaces.
• android.widget − A rich collection of pre-built user interface components such as buttons,
labels, list views, layout managers, radio buttons etc.
• android.webkit − A set of classes intended to allow web-browsing capabilities to be built
into applications.
Having covered the Java-based core libraries in the Android runtime, it is now time to turn our
attention to the C/C++ based libraries contained in this layer of the Android software stack.
Android Runtime
This is the third section of the architecture and available on the second layer from the bottom.
This section provides a key component called Dalvik Virtual Machine which is a kind of Java
Virtual Machine specially designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-threading,
which is intrinsic in the Java language. The Dalvik VM enables every Android application to run
in its own process, with its own instance of the Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android application
developers to write Android applications using standard Java programming language.
Application Framework
The Application Framework layer provides many higher-level services to applications in the form
of Java classes. Application developers are allowed to make use of these services in their
applications.
The Android framework includes the following key services −
• Activity Manager − Controls all aspects of the application lifecycle and activity stack.
• Content Providers − Allows applications to publish and share data with other
applications.
• Resource Manager − Provides access to non-code embedded resources such as strings,
color settings and user interface layouts.
• Notifications Manager − Allows applications to display alerts and notifications to the
user.
• View System − An extensible set of views used to create application user interfaces.
Applications
You will find all the Android application at the top layer. You will write your application to be
installed on this layer only. Examples of such applications are Contacts Books, Browser, Games
etc.
Multimedia Framework:
A multimedia framework is a software framework that handles media on a computer and through
a network. A good multimedia framework offers an intuitive API and a modular architecture to
easily add support for new audio, video and container formats and transmission protocols. It is
meant to be used by applications such as media players and audio or video editors, but can also
be used to build videoconferencing applications, media converters and other multimedia tools.
Data is processed among modules automatically, it is unnecessary for app to pass buffers
between connected modules one by one.
In contrast to function libraries, a multimedia framework provides a run time environment for the
media processing. Ideally such an environment provides execution contexts for the media
processing blocks separated from the application using the framework. The separation supports
the independent processing of multimedia data in a timely manner. These separate contexts can
be implemented as threads
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.
• Scan for other Bluetooth devices
• Get a list of paired devices
• Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of
this calling by calling the static method getDefaultAdapter(). Its syntax is given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth
constant ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Apart from this constant, there are other constants provided the API , that supports different tasks.
They are listed below.
1 ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth
ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed
ACTION_FOUND
3
This constant is used for receiving information about each device that is discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Apart form the parried Devices , there are other methods in the API that gives more control over
Blueetooth. They are listed below.
1 enable()
This method enables the adapter if not enabled
isEnabled()
2
This method returns true if adapter is enabled
disable()
3
This method disables the adapter
getName()
4
This method returns the name of the Bluetooth adapter
setName(String name)
5
This method changes the Bluetooth name
getState()
6
This method returns the current state of the Bluetooth Adapter.
startDiscovery()
7
This method starts the discovery process of the Bluetooth for 120 seconds.
Example
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
5 Run the application and choose a running android device and install the application on it and verify
the results.
Animation:
Animation in android is possible from many ways. In this chapter we will discuss one easy and
widely used way of making animation called tweened animation.
Tween Animation
Tween Animation takes some parameters such as start value , end value, size , time duration ,
rotation angle e.t.c and perform the required animation on that object. It can be applied to any
type of object. So in order to use this , android has provided us a class called Animation.
In order to perform animation in android , we are going to call a static function loadAnimation()
of the class AnimationUtils. We are going to receive the result in an instance of Animation Object.
Its syntax is as follows −
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
Note the second parameter. It is the name of the our animation xml file. You have to create a new
folder called anim under res directory and make an xml file under anim folder.
This animation class has many useful functions which are listed below −
setDuration(long duration)
2
This method sets the duration of an animation.
getDuration()
3
This method gets the duration which is set by above method
end()
4
This method ends the animation.
cancel()
5
This method cancels the animation.
In order to apply this animation to an object , we will just call the startAnimation() method of the
object. Its syntax is −
ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);
Example
The following example demonstrates the use of Animation in android. You would be able to
choose different type of animation from the menu and the selected animation will be applied on
an imageView on the screen.
To experiment with this example , you need to run this on an emulator or an actual device.
Steps Description
1 You will use Android studio IDE to create an Android application and name it as My Application under a package
com.example.sairamkrishna.myapplication.
4 Create a new folder under res directory and call it anim. Confim it by visiting res/anim
5 Right click on anim and click on new and select Android XML file You have to create different files that are listed
below.
7 No need to change default string constants. Android studio takes care of default constants at values/string.xml.
8 Run the application and choose a running android device and install the application on it and verify the results.
Camera:
These are the following two ways, in which you can use camera in your application
• Using existing android camera application in our application
• Directly using Camera API provided by android in our application
1 ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured
2 ACTION_VIDEO_CAPTURE
It calls the existing video application in android to capture video
EXTRA_SCREEN_ORIENTATION
3
It is used to set the orientation of the screen to vertical or landscape
EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage
INTENT_ACTION_VIDEO_CAMERA
5
This intent is used to launch the camera in the video mode
EXTRA_SIZE_LIMIT
6
It is used to specify the size limit of video or image capture size
Now you will use the function startActivityForResult() to launch this activity and wait for its
result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity. There
are methods defined in the activity class that does the same job , but used when you are not calling
from the activity but from somewhere else. They are listed below
No matter which function you used to launch the activity , they all return the result. The result
can be obtained by overriding the function onActivityResult.
Example
Here is an example that shows how to launch the existing camera application to capture an image
and display the result in the form of bitmap.
To experiment with this example , you need to run this on an actual device on which camera is
supported.
Steps Description
1 You will use Android studio IDE to create an Android application and name it as Camera under a
com.example.sairamkrishna.myapplication.
4 Add the Camera permission and run the application and choose a running android device and install
the application on it and verify the results.
Audio and Video player:
• Android provides many ways to control playback of audio/video files and streams. One
of this way is through a class called MediaPlayer.
• The android media framework provides a built in support for playing a variety of
common media types, such as audio or video. We have a multiple ways to play audio or
video but the most important component of media framework is MediaPlayer class.
• In android, by using MediaPlayer class we can access audio or video files from
application (raw) resources, standalone files in file system or from a data stream arriving
over a network connection and play audio or video files with the multiple playback
options such as play, pause, forward, backward, etc.
• we have to call a static Method create() of this class. This method returns an instance of
MediaPlayer class. Its syntax is as follows
Syntax:
MediaPlayer mPlayer = MediaPlayer.create(this,
R.raw.baitikochi_chuste);
• Once you have created the Mediaplayer object you can call some methods to start or stop
the music. These methods are listed below.
1. mediaPlayer.start();
2. mediaPlayer.pause();
• In order to start music from the beginning, you have to call reset() method. Its syntax is
given below.
mediaPlayer.reset();
• In case, if we want to play an audio from a URI that is locally available in the system, we
need to write the code like as shown below
Uri myUri = ....; // initialize Uri here
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(getApplicationContext(), myUri);
mPlayer.prepare();
mPlayer.start();
• STREAM_MUSIC- Used to identify the volume of audio streams for music playback
• If we want to play an audio from a URL via HTTP streaming, we need to write the code
like as shown below.
Example:
String url = "http://........"; // your URL here
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(url);
mPlayer.prepare(); // might take long! (for buffering, etc)
mPlayer.start();
• Methods of media player class:
Method Description
public void setDataSource(String sets the data source (file path or http
path) url) to use.
Method Description
• Video Player:
In android, by using VideoView component and MediaController class we can easily
implement the video player in android applications to play the videos with multiple
playback options, such as play, pause, forward, backward, etc.
Example:
VideoView videoView = (VideoView)findViewById(R.id.vdVw);
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" +
R.raw.video1);
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
Description
Method
setMediaController() It is used to set the media controller to
videoview.
• Text to Speech:
Text to speech (TTS) makes an android device read the text and convert it to
audio out via the speaker. Android TTS supports multiple languages. TTS is a simple but
powerful feature. It can also be effectively used in mobile APPs dedicated to visually
impaired people or in educational app for kids or can be used in pronunciation learning
app, etc. These are some of the ways you can use TTS. Using TextToSpeech enhances
interaction between the user and the mobile application.
• Generally, the android TextToSpeech instance can only be used to synthesize text once it
has completed its initialization so implement TextToSpeech.OnInitListener to notify
the completion of initialization.
• During the initialization, we can set the audio pitch rate, audio speed, type of language to
speak, etc. based on our requirements.
• OnInitListener-Interface definition of a callback to be invoked indicating the completion
of the TextToSpeech engine initialization.
• TextToSpeech needs to be initialized first. For this, you need to implement
the TextToSpeech.OnInitListener interface and override the method: onInit
TextToSpeech tts = new TextToSpeech(this, this);
public TextToSpeech (Context context, TextToSpeech.OnInitListener listener)
• How to speak the text?
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
– The first parameter is the text that would be spoken.
– The second parameter defines that the previous input is flushed so as to begin a
clean slate. Alternatively, we can use QUEUE_ADD to add the current text to the
speech.
– The third parameter is the bundle that is passed.
– Fourth is the utterance id string.
• OnUtteranceProgressListener is used to listen for the tts events: start,
done, error
2 getLanguage()
This method returns a Locale instance describing the language.
3 isSpeaking()
This method checks whether the TextToSpeech engine is busy speaking.
4 setPitch(float pitch)
This method sets the speech pitch for the TextToSpeech engine.
5 setSpeechRate(float speechRate)
This method sets the speech rate.
6 shutdown()
This method releases the resources used by the TextToSpeech engine.
7 stop()
This method stop the speak.
Contants-
• ERROR-Denotes a generic operation failure.
• ERROR_SERVICE-Denotes a failure of a TTS service.
• LANG_AVAILABLE-Denotes the language is available for the language by the locale
• LANG_COUNTRY_AVAILABLE-Denotes the language is available for the language
and country specified by the locale
• LANG_MISSING_DATA-Denotes the language data is missing.
• LANG_NOT_SUPPORTED-Denotes the language is not supported.
• SUCCESS-Denotes a successful operation.
• QUEUE_FLUSH-Queue mode where all entries in the playback queue (media to be
played and text to be synthesized) are dropped and replaced by the new entry.
• STOPPED-Denotes a stop requested by a client.
Sensors
• Generally, most of the android devices have a built-in sensors to measure motion,
orientation and various environmental conditions.
• Most of the android devices have built-in sensors that measure motion, orientation, and
various environmental condition. The android platform supports three broad categories of
sensors.
– Motion Sensors
– Environmental sensors
– Position sensors
• Motion Sensors-These sensors are useful to measure acceleration forces and rotational
forces along three axes. This category includes accelerometers, gravity sensors,
gyroscopes, and rotational vector sensors.
• 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.
• Position Sensors- These sensors are useful to measure the physical position of a device.
This category includes orientation sensors and magnetometers.
Android provided a framework called sensor framework to access all the sensors
available on device and to get all the raw sensor data. The sensor framework provided a wide
variety of sensor related tasks. For example, by using sensor framework we can perform
following things
Classes –
Class Description
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.
• getSensorList()
public List<Sensor> getSensorList (int type)
- Use this method to get the list of available sensors of a certain type. Make multiple calls
to get sensors of different types or use Sensor.TYPE_ALL to get all the sensors.
• registerListener
public boolean registerListener (SensorEventListener listener, Sensor sensor, int
samplingPeriodUs)
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.
The Sensor class defines several constants for accessing the different sensors
Sensor Type Description Common
Uses
TYPE_ACCELEROMETER Hardware Measures the acceleration Motion
force in m/s2 that is detection
applied to a device on all (shake, tilt,
three physical axes (x, y, etc.).
and z), including the
force of gravity.
TYPE_AMBIENT_TEMPERATURE Hardware Measures the ambient Monitoring
room temperature in air
degrees Celsius (°C). See temperatures.
note below.
TYPE_GRAVITY Software Measures the force of Motion
or gravity in m/s2 that is detection
Hardware applied to a device on all (shake, tilt,
three physical axes (x, y, etc.).
z).
TYPE_GYROSCOPE Hardware Measures a device's rate of rotation in rad/s Rotation
around each of the three physical axes (x, y, and detection
z). (spin, turn,
etc.).
TYPE_LIGHT Hardware Measures the ambient light level (illumination) Controlling
in lx. screen
brightness.
TYPE_LINEAR_ACCELERATION Software Measures the acceleration force in m/s2 that is Monitoring
or applied to a device on all three physical axes (x, acceleration
Hardware y, and z), excluding the force of gravity. along a
single axis.
TYPE_MAGNETIC_FIELD Hardware Measures the ambient geomagnetic field for all Creating a
three physical axes (x, y, z) in μT. compass.
TYPE_ORIENTATION Software Measures degrees of rotation that a device Determining
makes around all three physical axes (x, y, z). device
As of API level 3 you can obtain the inclination position.
matrix and rotation matrix for a device by using
the gravity sensor and the geomagnetic field
sensor in conjunction with
the getRotationMatrix() method.
TYPE_PRESSURE Hardware Measures the ambient air pressure in hPa or Monitoring
mbar. air pressure
changes.
TYPE_PROXIMITY Hardware Measures the proximity of an object in cm Phone
relative to the view screen of a device. This position
sensor is typically used to determine whether a during a call.
handset is being held up to a person's ear.
TYPE_RELATIVE_HUMIDITY Hardware Measures the relative ambient humidity in Monitoring
percent (%). dew point,
absolute, and
relative
humidity.
TYPE_ROTATION_VECTOR Software Measures the orientation of a device by Motion
or providing the three elements of the device's detection and
Hardware rotation vector. rotation
detection.
TYPE_TEMPERATURE Hardware Measures the temperature of the device in Monitoring
degrees Celsius (°C). This sensor temperatures.
implementation varies across devices and this
sensor was replaced with
the TYPE_AMBIENT_TEMPERATURE sensor
in API Level 14
Sensor Class:
You can access the sensor via the sensorManager.getDefaultSensor() method, which takes the
sensor type and the delay defined as constants on SensorManager as parameters.
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
SensorEvent class-
Its instance is created by the system. It provides information about the sensor.
SensorEventListener interface-
It provides two call back methods to get information when sensor values (x,y and z)
change or sensor accuracy changes
Public and abstract methods Description
void onAccuracyChanged(Sensor sensor, it is called when sensor accuracy is changed.
int accuracy)
void onSensorChanged(SensorEvent event) it is called when sensor values are changed.
Steps:
1. Android provides SensorManager and Sensor classes to use the sensors in our
application. In order to use sensors, first thing you need to do is to instantiate the object
of SensorManager class. It can be achieved as follows.
SensorManager sMgr; sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
2. The next thing you need to do is to instantiate the object of Sensor class by calling the
getDefaultSensor() method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
3. Once that sensor is declared , you need to register its listener and override two methods
which are onAccuracyChanged and onSensorChanged. Its syntax is as follows −
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy)
{}
public void onSensorChanged(SensorEvent event) { }
SQLite Database:
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't
need to establish any kind of connections for it like JDBC,ODBC e.t.c
Database - Package
The main package is android.database.sqlite that contains the classes to manage your own
databases
Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. It returns an instance of SQLite database which you
have to receive in your own object.Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
Apart from this , there are other functions available in the database package , that does this job.
They are listed below
1
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,
DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode. The common flags mode
could be OPEN_READWRITE OPEN_READONLY
2
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
It is similar to the above method as it also opens the existing database but it does not define any handler to
handle the errors of databases
3
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method is equivalent to openDatabase method.
4
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
This method is similar to above method but it takes the File object as a path rather then a string. It is
equivalent to file.getPath()
Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the
same job but take some additional parameter is given below
1
execSQL(String sql, Object[] bindArgs)
This method not only insert data , but also used to update or modify already existing data in database
using bind arguments
Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a method
of this class called rawQuery and it will return a resultset with the cursor pointing to the table.
We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the
data. That includes
1
getColumnCount()
This method return the total number of columns of the table.
2
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column
3
getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column
4
getColumnNames()
This method returns the array of all the column names of the table.
5
getCount()
This method returns the total number of rows in the cursor
6
getPosition()
This method returns the current position of the cursor in the table
7
isClosed()
This method returns true if the cursor is closed and return false otherwise
Database - Helper class
For managing all the operations related to the database , an helper class has been given and is
called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its
syntax is given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}
Example
Here is an example demonstrating the use of SQLite Database. It creates a basic contacts
applications that allows insertion, deletion and modification of contacts.
To experiment with this example, you need to run this on an actual device on which camera is
supported.
Steps Description
1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to get references of all the XML components and populate the contacts
on listView.
4 Create a new Activity as DisplayContact.java that will display the contact on the screen
10 Run the application and choose a running android device and install the application on it and verify the
results.
Constructor Description
There are many methods in SQLiteOpenHelper class. Some of them are as follows:
Method Description
public abstract void onCreate(SQLiteDatabase db) called only once when database is
created for the first time.
public abstract void onUpgrade(SQLiteDatabase db, int called when database needs to be
oldVersion, int newVersion) upgraded.
public void onDowngrade(SQLiteDatabase db, int oldVersion, called when database needs to be
int newVersion) downgraded.
SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete, select etc.
There are many methods in SQLiteDatabase class. Some of them are as follows:
Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String inserts a record on the database. The table specifies the table
nullColumnHack, ContentValues name, nullColumnHack doesn't allow completely null values.
values) If second argument is null, android will store null values if
values are empty. The third argument specifies the values to
be stored.
int update(String table, ContentValues updates a row.
values, String whereClause, String[]
whereArgs)