Professional Documents
Culture Documents
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)
SmsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
SMSManager API required SEND_SMS permission in our android manifest
to send SMS. Following is the code snippet to set SEND_SMS permissions in
manifest file.
<uses-permission android:name="android.permission.SEND_SMS"/>
In android, we can easily send an email from our android application using existing
email clients such as GMAIL, Outlook, etc. instead of building an email client from
scratch.
Generally, the Intent object in android with proper action (ACTION_SEND)
and data will help us to launch the available email clients to send an email in our
application.
In android, Intent is a messaging object which is used to request an action
from another app component such as activities, services, broadcast receivers,
and content providers.
To send an email using the Intent object in android application, we need to write the
code as shown below.
1
EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.
2
EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.
3
EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.
4
EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to supply an
alternative to EXTRA_TEXT as HTML formatted text.
5
EXTRA_SUBJECT
A constant string holding the desired subject line of a message.
6
EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with ACTION_SEND to supply
the literal data to be sent.
7
EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER
To send an email you need to specify mailto: as URI using setData() method and data
type will be to text/plain using setType() method as follows −
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
Intent Object - Extra to send Email
Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which
can be attached to the intent before sending the intent to a target email client. You
can use following extra fields in your email
For below example code is present in folder email refer all files
By Intent
You can use Android Intent to send SMS by calling built-in SMS functionality
of the Android. Following section explains different parts of our Intent object
required to send an SMS.
Intent Object - Action to send SMS
You will use ACTION_VIEW action to launch an SMS client installed on
your Android device. Following is simple syntax to create an intent with
ACTION_VIEW action.
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
Intent Object - Data/Type to send SMS
To send an SMS you need to specify smsto: as URI using setData() method
and data type will be to vnd.android-dir/mms-sms using setType() method as
follows −
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
Methods Description
Or
map.getUiSettings().setZoomGesturesEnabled(true);
You can place a maker with some text over it displaying your location on the map.
It can be done by via addMarker() method. Its syntax is given below −
final LatLng TutorialsPoint = new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions()
.position(TutorialsPoint).title("TutorialsPoint"));
A class for handling geocoding and reverse geocoding. Geocoding is the process of
transforming a street address or other description of a location into a (latitude,
longitude) coordinate. Reverse geocoding is the process of transforming a (latitude,
longitude) coordinate into a (partial) address. The amount of detail in a reverse
geocoded location description may vary, for example one might contain the full
street address of the closest building, while another might contain only a city name
and postal code
Geocoder
Android Geocoder class is used for Geocoding as well as Reverse Geocoding.
Geocoding refers to transforming street address or any address into latitude and
longitude. Reverse Geocoding refers to transforming latitude and longitude into its
corresponding street address.
Address class helps in fetching the street address, locality, sub-locality, city, country,
landmark etc. features of the location.
Geocoding is the process of converting addresses (like a street address) into
geographic coordinates (like latitude and longitude), which you can use to place
markers on a map, or position the map.
Geocoding
Geocoding is the process of converting the addresses (postal address) into geo
coordinates as latitude and longitude. Reverse geocoding is converting a geo
coordinate latitude and longitude to an address. In this tutorial we will be doing
reverse geo coding and get the addresses of the passed coordinates.
• public double getLatitude ()- Returns the latitude of the address if known
• public String getLocality ()-Returns the locality of the address, for example
"Mountain View", or null if it is unknown.
• public double getLongitude ()- Returns the longitude of the address if known.
• public String getPhone ()- Returns the phone number of the address if known,
or null if it is unknown.
• public String getPostalCode ()Returns the postal code of the address, for
example "94110", or null if it is unknown.
• public String getPremises ()Returns the premises of the address, or null if it is
unknown.
• public boolean hasLatitude ()-Returns true if a latitude has been assigned to
this Address, false otherwise.
• public boolean hasLongitude ()-Returns true if a longitude has been assigned
to this Address, false otherwise.
• 11.public void setAddressLine (int index, String line)- Sets the line of the
address numbered by index (starting at 0) to the given String, which may be
null.
• public void setCountryCode (String countryCode)- Sets the country code of
the address to the given String, which may be null.
• public void setCountryName (String countryName)- Sets the country name of
the address to the given String, which may be null.
• public void setLatitude (double latitude)- Sets the latitude associated with this
address.
• public void setLocality (String locality)- Sets the locality of the address to the
given String, which may be null.
• public void setLongitude (double longitude)-Sets the longitude associated
with this address.
• public void setPhone (String phone)-Sets the phone number associated with
this address.
• public void setPostalCode (String postalCode)-Sets the postal code of the
address to the given String, which may be null.
• public void setPremises (String premises)-Sets the premises of the address to
the given String, which may be null.
Android Reverse Geocoding
Step1: Define Permissions
We need location access permission to find the latitude and longitude of the Android
device. Following two lines are the key to give permission to access the location.
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.javapapers.com.androidgeocodelocation" >
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Step 2: Accessing the Geo Location for Lat and Long
Following class is the key element in accessing the latitude and longitude of the
Android device. It implements the LocationListener and gets the location coordinate
updates. We have designed our requirement not to be a continous update for location.
On demand we will get the location coordinates.
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
Button btnGPSShowLocation;
Button btnShowAddress;
TextView tvAddress;
AppLocationService appLocationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
tvAddress = (TextView) findViewById(R.id.tvAddress);
appLocationService = new AppLocationService(
MyActivity.this);
//you can hard-code the lat & long if you have issues with getting it
//remove the below if-condition and use the following couple of lines
//double latitude = 37.422005;
//double longitude = -122.084095
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
} else {
showSettingsAlert();
}
}
});
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Location"
android:id="@+id/btnGPSShowLocation"
android:layout_toEndOf="@+id/textView"
android:layout_marginTop="53dp"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Address"
android:id="@+id/btnShowAddress"
android:layout_toEndOf="@+id/tvAddress"
android:layout_below="@+id/btnGPSShowLocation"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tvAddress"
android:layout_alignParentBottom="true"
android:layout_marginBottom="134dp"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Key Points for Geocoding
• Need Google API access and so remember to run in an emulator that is
configured for Google API.
• Remember to have the right permissions defined in the Mainfest.xml
• To test via an Android Emulator, we can use the DDMS and pass the latitude
and longitude using the ‘Emulator Control’.
<application
android:allowBackup="true">
...
<receiver android:name=".GeofenceBroadcastReceiver"/>
<application/>
To access the location APIs, you need to create an instance of the Geofencing
client. To learn how to connect your client:
Android security model
a) Threat Model
b) Android platform security model
1. Threat Model
Android application has been signed with a certificate with a private key Know the
owner of the application is unique. This allows the author of The application will be
identified if needed. When an application is installed in The phone is assigned a user
ID, thus avoiding it from affecting it Other applications by creating a sandbox for it.
This user ID is permanent on which devices and applications with the same user ID
are allowed to run in a single process. This is a way to ensure that a malicious
application has Can not access / compromise the data of the genuine application.
It is mandatory for an application to list all the resources it will Access during
installation. Terms are required of an application, in The installation process should
be user-based or interactive Check with the signature of the application.
• Design review: The Android security process begins early in the development
lifecycle with the creation of a rich and configurable security model and design. Each
major feature of the platform is reviewed by engineering and security resources, with
appropriate security controls integrated into the architecture of the system.
• Penetration testing and code review: During the development of the platform,
Android-created and open source components are subject to vigorous security
reviews. These reviews are performed by the Android Security Team, Google’s
Information Security Engineering team, and independent security consultants. The
goal of these reviews is to identify weaknesses and possible vulnerabilities well
before major releases, and to simulate the types of analysis that are performed by
external security experts upon release.
• Open source and community review: AOSP enables broad security review by any
interested party. Android also uses open source technologies that have undergone
significant external security review, such as the Linux kernel. Google Play provides
a forum for users and companies to provide information about specific apps directly
to users.
• Incident response: Even with these precautions, security issues may occur after
shipping, which is why the Android project has created a comprehensive security
response process. Full-time Android security team members monitor the Android-
specific and the general security community for discussion of potential
vulnerabilities and review security bugs filed on the Android bug database. Upon
the discovery of legitimate issues, the Android team has a response process that
enables the rapid mitigation of vulnerabilities to ensure that potential risk to all
Android users is minimized
• Monthly security updates: The Android security team provides monthly updates to
Google Android devices and all our device manufacturing partners.
API Keys
New Users: Before you can start using the Google Maps Platform APIs and SDKs,
you must sign up and create a billing account. To use the Places API you must
have an API key. The API key is a unique identifier that is used to authenticate
requests associated with your project for usage and billing purposes.
You must have at least one API key associated with your project.
3. Click the menu button and select APIs & Services > Credentials.
4. On the Credentials page, click Create credentials > API key.
The API key created dialog displays your newly created API key.
5. Click Close.
The new API key is listed on the Credentials page under API keys.
(Remember to restrict the API key before using it in production.)
Publish Your App
Publishing is the general process that makes your Android applications available to
users. When you publish an Android application you perform two main tasks:
Step 1: Sign up
Sign up for an account on the Android Developer Console. Creating an account costs
$25.
• Hi-res icon: I used the launcher icon. It was an SVG file, so I converted it to PNG
using GIMP.
• Feature graphic: This is an image that shows up on the top of the app download
page in Google Play on mobile phones.
• Remove the android:debuggable attribute from your manifest file. I didn’t have
to do this because Android Studio automatically sets this attribute based on the
kind of APK its building. Neat!
• Losing a key-pair consequences that you will not be able to push updates to your
app.
Google will perform a check on the APK. My app was using an SVG for the launcher
icon, which is no-bueno. I had to change it to PNG and recreate the signed APK.
Step 7:
Complete the checklist on the left until all the items have a green checkmark. The
console re-evaluates the checklist every time you click Save Draft in the top right.