SlideShare a Scribd company logo
Mobile Application
Development
By:
Muhammad Usman Ali Source: www.tutorialspoint.com
Week 12
2
Outline
●
Sensors
●
Location Sensor
●
Motion Sensor
●
Environment Sensor
3
Sensors Overview
Most Android-powered devices have built-in sensors that measure
motion, orientation, and various environmental conditions. These
sensors are capable of providing raw data with high precision and
accuracy, and are useful if you want to monitor three-dimensional
device movement or positioning, or you want to monitor changes
in the ambient environment near a device. For example, a game
might track readings from a device's gravity sensor to infer
complex user gestures and motions, such as tilt, shake, rotation, or
swing. Likewise, a weather application might use a device's
temperature sensor and humidity sensor to calculate and report
the dewpoint, or a travel application might use the geomagnetic
field sensor and accelerometer to report a compass bearing.
Type of Sensors
Motion Sensors
Position Sensors
Environment Sensors
4
Categories of Sensors
The Android platform supports three broad categories of sensors:
Motion sensors
These sensors measure acceleration forces and rotational
forces along three axes. This category includes accelerometers,
gravity sensors, gyroscopes, and rotational vector sensors.
Environmental sensors
These sensors 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 measure the physical position of a device. This
category includes orientation sensors and magnetometers.
5
Android sensor framework
You can access sensors available on the device and acquire raw
sensor data by using the Android sensor framework. The sensor
framework provides several classes and interfaces that help you
perform a wide variety of sensor-related tasks. For example, you
can use the sensor framework to do the following:
●
Determine which sensors are available on a device.
●
Determine an individual sensor's capabilities, such as its
maximum range, manufacturer, power requirements, and
resolution.
●
Acquire raw sensor data and define the minimum rate at
which you acquire sensor data.
●
Register and unregister sensor event listeners that monitor
sensor changes.
6
Introduction Sensors
The Android sensor framework lets you access many types
of sensors. Some of these sensors are hardware-based
and some are software-based. Hardware-based sensors
are physical components built into a handset or tablet
device. They derive their data by directly measuring
specific environmental properties, such as acceleration,
geomagnetic field strength, or angular change.
Software-based sensors are not physical devices, although
they mimic hardware-based sensors. Software-based
sensors derive their data from one or more of the
hardware-based sensors and are sometimes called virtual
sensors or synthetic sensors. The linear acceleration
sensor and the gravity sensor are examples of software-
based sensors.
7
Supported Sensors
Following Table summarizes the sensors that are
supported by the Android platform.
Sensor Type Description Common Uses
TYPE_ACCELEROMETE
R
Hardware Measures the acceleration force in m/s2 that is applied to a
device on all three physical axes (x, y, and z), including the
force of gravity.
Motion detection
(shake, tilt, etc.).
TYPE_AMBIENT_TEMP
ERATURE
Hardware Measures the ambient room temperature in degrees Celsius
(°C). See note below.
Monitoring air
temperatures.
TYPE_GRAVITY Software or
Hardware
Measures the force of gravity in m/s2 that is applied to a device
on all three physical axes (x, y, z).
Motion detection
(shake, tilt, etc.).
TYPE_GYROSCOP Hardware Measures a device's rate of rotation in rad/s around each of the
three physical axes (x, y, and z).
Rotation detection
(spin, turn, etc.).
TYPE_LIGHT Hardware Measures the ambient light level (illumination) in lx. Controlling screen
brightness.
TYPE_LINEAR_ACCEL
ERATION
Software or
Hardware
Measures the acceleration force in m/s2 that is applied to a
device on all three physical axes (x, y, and z), excluding the
force of gravity.
Monitoring acceleration
along a single axis.
TYPE_MAGNETIC_FIE
LD
Hardware Measures the ambient geomagnetic field for all three physical
axes (x, y, z) in μT.
Creating a compass.
8
Supported Sensors
Sensor Type Description Common Uses
TYPE_ORIENTATION Software Measures degrees of rotation that a device makes around all
three physical axes (x, y, z). As of API level 3 you can obtain
the inclination matrix and rotation matrix for a device by using
the gravity sensor and the geomagnetic field sensor in
conjunction with the getRotationMatrix() method.
Determining device
position.
TYPE_PRESSURE Hardware Measures the ambient air pressure in hPa or mbar. Monitoring air pressure
changes.
TYPE_PROXIMITY Hardware Measures the proximity of an object in cm relative to the view
screen of a device. This sensor is typically used to determine
whether a handset is being held up to a person's ear.
Phone position during a
call.
TYPE_RELATIVE_HUM
IDITY
Hardware Measures the relative ambient humidity in percent (%). Monitoring dewpoint,
absolute, and relative
humidity.
TYPE_ROTATION_VEC
TOR
Software or
Hardware
Measures the orientation of a device by providing the three
elements of the device's rotation vector.
Motion detection and
rotation detection.
TYPE_TEMPERATURE Hardware Measures the temperature of the device in degrees Celsius
(°C). This sensor implementation varies across devices and
this sensor was replaced with the TYPE_ sensor in API Level
14
Monitoring
temperatures.
9
Sensor Framework
You can access these sensors and acquire raw sensor data by using the Android sensor
framework. The sensor framework is part of the android.hardware package and includes the
following classes and interfaces:
SensorManager
You can use this class to create an instance of the sensor service. This class provides various
methods for accessing and listing sensors, registering and unregistering sensor event listeners,
and acquiring orientation information. This class also provides several sensor constants that are
used to report sensor accuracy, set data acquisition rates, and calibrate sensors.
Sensor
You can use this class to create an instance of a specific sensor. This class provides various
methods that let you determine a sensor's capabilities.
SensorEvent
The system uses this class to create a sensor event object, which provides information about
a sensor event. A sensor event object includes the following information: the raw sensor data,
the type of sensor that generated the event, the accuracy of the data, and the timestamp for the
event.
SensorEventListener
You can use this interface to create two callback methods that receive notifications (sensor
events) when sensor values change or when sensor accuracy changes.
10
Sensor Framework ...
In a typical application you use these sensor-related APIs to perform two basic
tasks:
Identifying sensors and sensor capabilities
Identifying sensors and sensor capabilities at runtime is useful if your application
has features that rely on specific sensor types or capabilities. For example, you may
want to identify all of the sensors that are present on a device and disable any
application features that rely on sensors that are not present. Likewise, you may
want to identify all of the sensors of a given type so you can choose the sensor
implementation that has the optimum performance for your application.
Monitor sensor events
Monitoring sensor events is how you acquire raw sensor data. A sensor event
occurs every time a sensor detects a change in the parameters it is measuring. A
sensor event provides you with four pieces of information: the name of the sensor
that triggered the event, the timestamp for the event, the accuracy of the event,
and the raw sensor data that triggered the event.
11
Sensor Availability
While sensor availability varies from device to device, it
can also vary between Android versions. This is because
the Android sensors have been introduced over the course
of several platform releases.
For example, many sensors were introduced in Android 1.5
(API Level 3), but some were not implemented and were
not available for use until Android 2.3 (API Level 9).
Likewise, several sensors were introduced in Android 2.3
(API Level 9) and Android 4.0 (API Level 14). Two sensors
have been deprecated and replaced by newer, better
sensors.
12
Identifying Sensors
The Android sensor framework provides several methods that make it easy for you to
determine at runtime which sensors are on a device. The API also provides methods that
let you determine the capabilities of each sensor, such as its maximum range, its
resolution, and its power requirements.
To identify the sensors that are on a device you first need to get a reference to the sensor
service. To do this, you create an instance of the SensorManager class by calling the
getSystemService() method and passing in the SENSOR_SERVICE argument. For example:
private SensorManager sensorManager;
...
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Next, you can get a listing of every sensor on a device by calling the getSensorList()
method and using the TYPE_ALL constant. For example:
List<Sensor> deviceSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
13
Specific Sensor
If you want to list all of the sensors of a given type, you could use another constant instead
of TYPE_ALL such as TYPE_GYROSCOPE, TYPE_LINEAR_ACCELERATION, or TYPE_GRAVITY
.
You can also determine whether a specific type of sensor exists on a device by using the
getDefaultSensor() method and passing in the type constant for a specific sensor. If a
device has more than one sensor of a given type, one of the sensors must be designated as
the default sensor. If a default sensor does not exist for a given type of sensor, the method
call returns null, which means the device does not have that type of sensor. For example,
the following code checks whether there's a magnetometer on a device:
private SensorManager sensorManager;
...
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){
// Success! There's a magnetometer.
} else {
// Failure! No magnetometer.
}
14
Sensor Capabilities
In addition to listing the sensors that are on a device, you can use the
public methods of the Sensor class to determine the capabilities and
attributes of individual sensors. This is useful if you want your
application to behave differently based on which sensors or sensor
capabilities are available on a device. For example, you can use the
getResolution() and getMaximumRange() methods to obtain a sensor's
resolution and maximum range of measurement. You can also use the
getPower() method to obtain a sensor's power requirements.
Two of the public methods are particularly useful if you want to
optimize your application for different manufacturer's sensors or
different versions of a sensor. For example, if your application needs
to monitor user gestures such as tilt and shake, you could create one
set of data filtering rules and optimizations for newer devices that
have a specific vendor's gravity sensor, and another set of data
filtering rules and optimizations for devices that do not have a gravity
sensor and have only an accelerometer.
15
Check Sensor capabilities
The following code sample shows you how you can use the getVendor() and
getVersion() methods to do this.
private SensorManager sensorManager;
private Sensor mSensor;
...
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = null;
if (sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY) != null){
List<Sensor> gravSensors = sensorManager.getSensorList(Sensor.TYPE_GRAVITY);
for(int i=0; i<gravSensors.size(); i++) {
if ((gravSensors.get(i).getVendor().contains("Google LLC")) && // checking vendor
(gravSensors.get(i).getVersion() == 3)){ // checking version
// Use the version 3 gravity sensor.
mSensor = gravSensors.get(i);
}
}
}
if (mSensor == null){
// Use the accelerometer.
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null){
mSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
} else{
// Sorry, there are no accelerometers on your device.
// You can't play this game.
}
}
16
Check Sensor capabilities ...
Another useful method is the getMinDelay() method, which returns the minimum
time interval (in microseconds) a sensor can use to sense data. Any sensor that
returns a non-zero value for the getMinDelay() method is a streaming sensor.
Streaming sensors sense data at regular intervals and were introduced in Android
2.3 (API Level 9). If a sensor returns zero when you call the getMinDelay() method,
it means the sensor is not a streaming sensor because it reports data only when
there is a change in the parameters it is sensing.
The getMinDelay() method is useful because it lets you determine the maximum
rate at which a sensor can acquire data. If certain features in your application
require high data acquisition rates or a streaming sensor, you can use this method
to determine whether a sensor meets those requirements and then enable or
disable the relevant features in your application accordingly.
Caution: A sensor's maximum data acquisition rate is not necessarily the rate at
which the sensor framework delivers sensor data to your application. The sensor
framework reports data through sensor events, and several factors influence the
rate at which your application receives sensor events.
17
Monitoring Sensor Events
To monitor raw sensor data you need to implement two callback methods that are
exposed through the SensorEventListener interface: onAccuracyChanged() and
onSensorChanged(). The Android system calls these methods whenever the following
occurs:
A sensor's accuracy changes.
In this case the system invokes the onAccuracyChanged() method, providing you with a
reference to the Sensor object that changed and the new accuracy of the sensor. Accuracy
is represented by one of four status constants: SENSOR_STATUS_ACCURACY_LOW,
SENSOR_STATUS_ACCURACY_MEDIUM, SENSOR_STATUS_ACCURACY_HIGH, or
SENSOR_STATUS_UNRELIABLE.
A sensor reports a new value.
In this case the system invokes the onSensorChanged() method, providing you with a
SensorEvent object. A SensorEvent object contains information about the new sensor
data, including: the accuracy of the data, the sensor that generated the data, the
timestamp at which the data was generated, and the new data that the sensor recorded.
18
onSensorChanged()
The following code shows how to use the
onSensorChanged() method to monitor
data from the light sensor. This example
displays the raw sensor data in a
TextView that is defined in the main.xml
file as sensor_data.
public class SensorActivity extends Activity implements
SensorEventListener {
private SensorManager sensorManager;
private Sensor mLight;
@Override
public final void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
mLight =
sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
@Override
public final void onAccuracyChanged(Sensor sensor, int
accuracy) {
// Do something here if sensor accuracy changes.
}
@Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
float lux = event.values[0];
// Do something with this sensor value.
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, mLight,
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
19
Location (GPS Sensor)
Location user drivers allow your app to publish updates to the device's
physical location through the Android location services. The API supports
constellations of the Global Navigation Satellite System (GNSS), such as the
Global Positioning System (GPS).
GNSS modules are receive-only devices that triangulate signals from
remote satellites in order to determine an accurate physical location. Once
the module collects enough satellite data to calculate an accurate position,
it has a valid location (a fix ) that it can report.
Receiver modules typically connect to the host system via UART, but may
use other forms of Peripheral I/O. For example, they may contain additional
GPIO pins to control power management or report when the module has
gained or lost a fix.
Note: The framework only supports a single source for GNSS location data.
You cannot register multiple GNSS drivers.
20
How to get location of user?
Adding the required permission
Add the required permission for the user driver to your app's manifest file:
<uses-permission
android:name="com.google.android.things.permission.MANAGE_GNSS_DRI
VERS" />
Creating the driver
The driver implementation is responsible for communicating with the
connected hardware, monitoring for valid location changes, and reporting
those changes to the framework. To create a driver:
1) Create a new GnssDriver instance.
2) Register the driver with the UserDriverManager:
import com.google.android.things.userdriver.location.GnssDriver;
import com.google.android.things.userdriver.UserDriverManager;
21
How to get location of user?
public class LocationDriverService extends Service {
private GnssDriver mDriver;
@Override
public void onCreate() {
super.onCreate();
mDriver = new GnssDriver(); // Create a new driver implementation
UserDriverManager manager = UserDriverManager.getInstance(); // Register with the framework
manager.registerGnssDriver(mDriver);
}
}
3) Unregister the driver when location events are not longer required.
public class LocationDriverService extends Service {
...
@Override
protected void onDestroy() {
super.onDestroy();
UserDriverManager manager = UserDriverManager.getInstance();
manager.unregisterGnssDriver();
}
}
22
Reporting location
Report each new location fix to the Android framework with the reportLocation() method.
This method accepts a Location object, which contains the updated contents to report.
Set the provider for each reported Location to LocationManager.GPS_PROVIDER.
import android.location.Location;
...
public class LocationDriverService extends Service {
private GnssDriver mDriver;
...
private Location parseLocationFromString(String data) {
Location result = new Location(LocationManager.GPS_PROVIDER);
// ...parse raw GNSS information...
return result;
}
public void handleLocationUpdate(String rawData) {
// Convert raw data into a location object
Location location = parseLocationFromString(rawData);
// Send the location update to the framework
mDriver.reportLocation(location);
}
}
23
Location attributes
he following table describes the Location attributes
that a driver can report to the framework. Attributes
marked required must be included or the framework will
reject the location update:
Required Attributes Optional Attributes
Accuracy
Timestamp
Latitude
Longitude
Altitude
Bearing
Speed
24
Converting GPS data
GPS is a commonly used constellation of GNSS satellites. GPS hardware typically reports
location information as ASCII strings in the NMEA standard format. Each line of data is a
comma-separated list of data values known as a sentence. While each GPS module may
choose to report different portions of the NMEA protocol, most devices send one or more of
the following sentences:
GPGGA (Fix Information): Includes position fix, altitude, timestamp, and satellite
metadata.
GPGLL (Geographic Latitude/Longitude): Includes position fix and timestamp.
GPRMC (Recommended Minimum Navigation): Includes position fix, speed, timestamp,
and navigation metadata.
As an example, the GPRMC sentence takes the following format:
$GPRMC,<Time>,<Status>,<Latitude>,<Longitude>,<Speed>,<Angle>,<Date>,<Variatio
n>,<Integrity>,<Checksum>
Using real data values, here is a sample GPRMC with the latitude, longitude, and speed
portions highlighted in bold:
$GPRMC,172934.975,V,3554.931,N,07402.499,W,16.4,3.35,300816,,E*41
25
GPRMC string format into a
Location instance
// Convert latitude from DMS to decimal format
private float parseLatitude(String latString, String hemisphere) {
float lat = Float.parseFloat(latString.substring(2))/60.0f;
lat += Float.parseFloat(latString.substring(0, 2));
if (hemisphere.contains("S")) {
lat *= -1;
}
return lat;
}
// Convert longitude from DMS to decimal format
private float parseLongitude(String longString, String hemisphere) {
float lat = Float.parseFloat(longString.substring(3))/60.0f;
lat += Float.parseFloat(longString.substring(0, 3));
if (hemisphere.contains("W")) {
lat *= -1;
}
return lat;
}
26
GPRMC string format into a
Location instance
// Return a location from an NMEA GPRMC string
public Location parseLocationFromString(String rawData) {
// Tokenize the string input
String[] nmea = rawData.split(",");
Location result = new Location(LocationManager.GPS_PROVIDER);
// Create timestamp from the date + time tokens
SimpleDateFormat format = new SimpleDateFormat("ddMMyyhhmmss.ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date date = format.parse(nmea[9] + nmea[1]);
result.setTime(date.getTime());
} catch (ParseException e) {
return null;
}
// Parse the fix information tokens
result.setLatitude(parseLatitude(nmea[3], nmea[4]));
result.setLongitude(parseLongitude(nmea[5], nmea[6]));
result.setSpeed(Float.parseFloat(nmea[7]));
return result;
}
27
GPS Data Example
public class MainActivity extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("Location", "Checking Sensors.");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.i("Location","location.getLongitude()");
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// for ActivityCompat#requestPermissions for more details.
Log.i("Location","Permission not allowed");
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60, 10, this);
}
}
28
GPS Data Example
@Override
public void onLocationChanged(@NonNull Location location) {
Log.i("Location",""+location.getLongitude());
((TextView)findViewById(R.id.tvLocation)).setText(""+location.getLatitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("Location",""+ status + ", "+extras.toString());
}
}
29
IMU Sensors
Gyroscope
Accelerometer
30
Sources
●
https://developer.android.com/guide/
topics/sensors/sensors_overview
●
https://developer.android.com/things/
sdk/drivers/location
●
https://developer.android.com/guide/
topics/sensors/gnss

More Related Content

Similar to Week12.pdf (20)

PDF
MOBILE PHONE SENSORS META-MODEL
ijasuc
 
PPTX
Tk2323 lecture 10 sensor
MengChun Lam
 
PPTX
Peno sensor
DarrenJin
 
PPTX
Sensors in smartphones ( MEMS technology)
Kamal Bhagat
 
PPTX
sensor in iot related with many diffferent types of sensors
NivethithaV19PHD1192
 
PPT
iwatchjr | Mobile Handset Sensors Coordinate System
iwatchjr
 
PPTX
Smart Phone Sensor
Bhawani Singh Chouhan
 
PDF
RMV sensors
anand hd
 
PPTX
Sensors & applications , commenly used sensors
Kamal Bhagat
 
PDF
VARIOUS SENSOR USED IN ROBOTICS WITH APPLICATIONS | J4RV3I12003
Journal For Research
 
PDF
Chap 5 introduction to intelligent instruments
LenchoDuguma
 
PPT
Synapseindia android application development tutorial
Synapseindiappsdevelopment
 
PPT
Synapseindia android apps development tutorial
Synapseindiappsdevelopment
 
PDF
Robotics unit3 sensors
Janarthanan B
 
PPTX
Smart sensors
JayantBhatt6
 
PPTX
roboticsunit3sensors and -201013084413.pptx
DrPArivalaganASSTPRO
 
PDF
IRJET - A Novel Technology for Shooting Sports
IRJET Journal
 
PDF
IRJET- Offline Location Detection and Accident Indication using Mobile Sensors
IRJET Journal
 
PPTX
Sensors and Actuators by VIRTUAL BASICS MACHINE.pptx
MahalakshmiS100
 
PDF
Unit III - Solved Question Bank- Robotics Engineering -
Sanjay Singh
 
MOBILE PHONE SENSORS META-MODEL
ijasuc
 
Tk2323 lecture 10 sensor
MengChun Lam
 
Peno sensor
DarrenJin
 
Sensors in smartphones ( MEMS technology)
Kamal Bhagat
 
sensor in iot related with many diffferent types of sensors
NivethithaV19PHD1192
 
iwatchjr | Mobile Handset Sensors Coordinate System
iwatchjr
 
Smart Phone Sensor
Bhawani Singh Chouhan
 
RMV sensors
anand hd
 
Sensors & applications , commenly used sensors
Kamal Bhagat
 
VARIOUS SENSOR USED IN ROBOTICS WITH APPLICATIONS | J4RV3I12003
Journal For Research
 
Chap 5 introduction to intelligent instruments
LenchoDuguma
 
Synapseindia android application development tutorial
Synapseindiappsdevelopment
 
Synapseindia android apps development tutorial
Synapseindiappsdevelopment
 
Robotics unit3 sensors
Janarthanan B
 
Smart sensors
JayantBhatt6
 
roboticsunit3sensors and -201013084413.pptx
DrPArivalaganASSTPRO
 
IRJET - A Novel Technology for Shooting Sports
IRJET Journal
 
IRJET- Offline Location Detection and Accident Indication using Mobile Sensors
IRJET Journal
 
Sensors and Actuators by VIRTUAL BASICS MACHINE.pptx
MahalakshmiS100
 
Unit III - Solved Question Bank- Robotics Engineering -
Sanjay Singh
 

Recently uploaded (20)

PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Ad

Week12.pdf

  • 1. Mobile Application Development By: Muhammad Usman Ali Source: www.tutorialspoint.com Week 12
  • 3. 3 Sensors Overview Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions. These sensors are capable of providing raw data with high precision and accuracy, and are useful if you want to monitor three-dimensional device movement or positioning, or you want to monitor changes in the ambient environment near a device. For example, a game might track readings from a device's gravity sensor to infer complex user gestures and motions, such as tilt, shake, rotation, or swing. Likewise, a weather application might use a device's temperature sensor and humidity sensor to calculate and report the dewpoint, or a travel application might use the geomagnetic field sensor and accelerometer to report a compass bearing. Type of Sensors Motion Sensors Position Sensors Environment Sensors
  • 4. 4 Categories of Sensors The Android platform supports three broad categories of sensors: Motion sensors These sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors. Environmental sensors These sensors 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 measure the physical position of a device. This category includes orientation sensors and magnetometers.
  • 5. 5 Android sensor framework You can access sensors available on the device and acquire raw sensor data by using the Android sensor framework. The sensor framework provides several classes and interfaces that help you perform a wide variety of sensor-related tasks. For example, you can use the sensor framework to do the following: ● Determine which sensors are available on a device. ● Determine an individual sensor's capabilities, such as its maximum range, manufacturer, power requirements, and resolution. ● Acquire raw sensor data and define the minimum rate at which you acquire sensor data. ● Register and unregister sensor event listeners that monitor sensor changes.
  • 6. 6 Introduction Sensors The Android sensor framework lets you access many types of sensors. Some of these sensors are hardware-based and some are software-based. Hardware-based sensors are physical components built into a handset or tablet device. They derive their data by directly measuring specific environmental properties, such as acceleration, geomagnetic field strength, or angular change. Software-based sensors are not physical devices, although they mimic hardware-based sensors. Software-based sensors derive their data from one or more of the hardware-based sensors and are sometimes called virtual sensors or synthetic sensors. The linear acceleration sensor and the gravity sensor are examples of software- based sensors.
  • 7. 7 Supported Sensors Following Table summarizes the sensors that are supported by the Android platform. Sensor Type Description Common Uses TYPE_ACCELEROMETE R Hardware Measures the acceleration force in m/s2 that is applied to a device on all three physical axes (x, y, and z), including the force of gravity. Motion detection (shake, tilt, etc.). TYPE_AMBIENT_TEMP ERATURE Hardware Measures the ambient room temperature in degrees Celsius (°C). See note below. Monitoring air temperatures. TYPE_GRAVITY Software or Hardware Measures the force of gravity in m/s2 that is applied to a device on all three physical axes (x, y, z). Motion detection (shake, tilt, etc.). TYPE_GYROSCOP Hardware Measures a device's rate of rotation in rad/s around each of the three physical axes (x, y, and z). Rotation detection (spin, turn, etc.). TYPE_LIGHT Hardware Measures the ambient light level (illumination) in lx. Controlling screen brightness. TYPE_LINEAR_ACCEL ERATION Software or Hardware Measures the acceleration force in m/s2 that is applied to a device on all three physical axes (x, y, and z), excluding the force of gravity. Monitoring acceleration along a single axis. TYPE_MAGNETIC_FIE LD Hardware Measures the ambient geomagnetic field for all three physical axes (x, y, z) in μT. Creating a compass.
  • 8. 8 Supported Sensors Sensor Type Description Common Uses TYPE_ORIENTATION Software Measures degrees of rotation that a device makes around all three physical axes (x, y, z). As of API level 3 you can obtain the inclination matrix and rotation matrix for a device by using the gravity sensor and the geomagnetic field sensor in conjunction with the getRotationMatrix() method. Determining device position. TYPE_PRESSURE Hardware Measures the ambient air pressure in hPa or mbar. Monitoring air pressure changes. TYPE_PROXIMITY Hardware Measures the proximity of an object in cm relative to the view screen of a device. This sensor is typically used to determine whether a handset is being held up to a person's ear. Phone position during a call. TYPE_RELATIVE_HUM IDITY Hardware Measures the relative ambient humidity in percent (%). Monitoring dewpoint, absolute, and relative humidity. TYPE_ROTATION_VEC TOR Software or Hardware Measures the orientation of a device by providing the three elements of the device's rotation vector. Motion detection and rotation detection. TYPE_TEMPERATURE Hardware Measures the temperature of the device in degrees Celsius (°C). This sensor implementation varies across devices and this sensor was replaced with the TYPE_ sensor in API Level 14 Monitoring temperatures.
  • 9. 9 Sensor Framework You can access these sensors and acquire raw sensor data by using the Android sensor framework. The sensor framework is part of the android.hardware package and includes the following classes and interfaces: SensorManager You can use this class to create an instance of the sensor service. This class provides various methods for accessing and listing sensors, registering and unregistering sensor event listeners, and acquiring orientation information. This class also provides several sensor constants that are used to report sensor accuracy, set data acquisition rates, and calibrate sensors. Sensor You can use this class to create an instance of a specific sensor. This class provides various methods that let you determine a sensor's capabilities. SensorEvent The system uses this class to create a sensor event object, which provides information about a sensor event. A sensor event object includes the following information: the raw sensor data, the type of sensor that generated the event, the accuracy of the data, and the timestamp for the event. SensorEventListener You can use this interface to create two callback methods that receive notifications (sensor events) when sensor values change or when sensor accuracy changes.
  • 10. 10 Sensor Framework ... In a typical application you use these sensor-related APIs to perform two basic tasks: Identifying sensors and sensor capabilities Identifying sensors and sensor capabilities at runtime is useful if your application has features that rely on specific sensor types or capabilities. For example, you may want to identify all of the sensors that are present on a device and disable any application features that rely on sensors that are not present. Likewise, you may want to identify all of the sensors of a given type so you can choose the sensor implementation that has the optimum performance for your application. Monitor sensor events Monitoring sensor events is how you acquire raw sensor data. A sensor event occurs every time a sensor detects a change in the parameters it is measuring. A sensor event provides you with four pieces of information: the name of the sensor that triggered the event, the timestamp for the event, the accuracy of the event, and the raw sensor data that triggered the event.
  • 11. 11 Sensor Availability While sensor availability varies from device to device, it can also vary between Android versions. This is because the Android sensors have been introduced over the course of several platform releases. For example, many sensors were introduced in Android 1.5 (API Level 3), but some were not implemented and were not available for use until Android 2.3 (API Level 9). Likewise, several sensors were introduced in Android 2.3 (API Level 9) and Android 4.0 (API Level 14). Two sensors have been deprecated and replaced by newer, better sensors.
  • 12. 12 Identifying Sensors The Android sensor framework provides several methods that make it easy for you to determine at runtime which sensors are on a device. The API also provides methods that let you determine the capabilities of each sensor, such as its maximum range, its resolution, and its power requirements. To identify the sensors that are on a device you first need to get a reference to the sensor service. To do this, you create an instance of the SensorManager class by calling the getSystemService() method and passing in the SENSOR_SERVICE argument. For example: private SensorManager sensorManager; ... sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Next, you can get a listing of every sensor on a device by calling the getSensorList() method and using the TYPE_ALL constant. For example: List<Sensor> deviceSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
  • 13. 13 Specific Sensor If you want to list all of the sensors of a given type, you could use another constant instead of TYPE_ALL such as TYPE_GYROSCOPE, TYPE_LINEAR_ACCELERATION, or TYPE_GRAVITY . You can also determine whether a specific type of sensor exists on a device by using the getDefaultSensor() method and passing in the type constant for a specific sensor. If a device has more than one sensor of a given type, one of the sensors must be designated as the default sensor. If a default sensor does not exist for a given type of sensor, the method call returns null, which means the device does not have that type of sensor. For example, the following code checks whether there's a magnetometer on a device: private SensorManager sensorManager; ... sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if (sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){ // Success! There's a magnetometer. } else { // Failure! No magnetometer. }
  • 14. 14 Sensor Capabilities In addition to listing the sensors that are on a device, you can use the public methods of the Sensor class to determine the capabilities and attributes of individual sensors. This is useful if you want your application to behave differently based on which sensors or sensor capabilities are available on a device. For example, you can use the getResolution() and getMaximumRange() methods to obtain a sensor's resolution and maximum range of measurement. You can also use the getPower() method to obtain a sensor's power requirements. Two of the public methods are particularly useful if you want to optimize your application for different manufacturer's sensors or different versions of a sensor. For example, if your application needs to monitor user gestures such as tilt and shake, you could create one set of data filtering rules and optimizations for newer devices that have a specific vendor's gravity sensor, and another set of data filtering rules and optimizations for devices that do not have a gravity sensor and have only an accelerometer.
  • 15. 15 Check Sensor capabilities The following code sample shows you how you can use the getVendor() and getVersion() methods to do this. private SensorManager sensorManager; private Sensor mSensor; ... sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mSensor = null; if (sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY) != null){ List<Sensor> gravSensors = sensorManager.getSensorList(Sensor.TYPE_GRAVITY); for(int i=0; i<gravSensors.size(); i++) { if ((gravSensors.get(i).getVendor().contains("Google LLC")) && // checking vendor (gravSensors.get(i).getVersion() == 3)){ // checking version // Use the version 3 gravity sensor. mSensor = gravSensors.get(i); } } } if (mSensor == null){ // Use the accelerometer. if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null){ mSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); } else{ // Sorry, there are no accelerometers on your device. // You can't play this game. } }
  • 16. 16 Check Sensor capabilities ... Another useful method is the getMinDelay() method, which returns the minimum time interval (in microseconds) a sensor can use to sense data. Any sensor that returns a non-zero value for the getMinDelay() method is a streaming sensor. Streaming sensors sense data at regular intervals and were introduced in Android 2.3 (API Level 9). If a sensor returns zero when you call the getMinDelay() method, it means the sensor is not a streaming sensor because it reports data only when there is a change in the parameters it is sensing. The getMinDelay() method is useful because it lets you determine the maximum rate at which a sensor can acquire data. If certain features in your application require high data acquisition rates or a streaming sensor, you can use this method to determine whether a sensor meets those requirements and then enable or disable the relevant features in your application accordingly. Caution: A sensor's maximum data acquisition rate is not necessarily the rate at which the sensor framework delivers sensor data to your application. The sensor framework reports data through sensor events, and several factors influence the rate at which your application receives sensor events.
  • 17. 17 Monitoring Sensor Events To monitor raw sensor data you need to implement two callback methods that are exposed through the SensorEventListener interface: onAccuracyChanged() and onSensorChanged(). The Android system calls these methods whenever the following occurs: A sensor's accuracy changes. In this case the system invokes the onAccuracyChanged() method, providing you with a reference to the Sensor object that changed and the new accuracy of the sensor. Accuracy is represented by one of four status constants: SENSOR_STATUS_ACCURACY_LOW, SENSOR_STATUS_ACCURACY_MEDIUM, SENSOR_STATUS_ACCURACY_HIGH, or SENSOR_STATUS_UNRELIABLE. A sensor reports a new value. In this case the system invokes the onSensorChanged() method, providing you with a SensorEvent object. A SensorEvent object contains information about the new sensor data, including: the accuracy of the data, the sensor that generated the data, the timestamp at which the data was generated, and the new data that the sensor recorded.
  • 18. 18 onSensorChanged() The following code shows how to use the onSensorChanged() method to monitor data from the light sensor. This example displays the raw sensor data in a TextView that is defined in the main.xml file as sensor_data. public class SensorActivity extends Activity implements SensorEventListener { private SensorManager sensorManager; private Sensor mLight; @Override public final void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); } @Override public final void onAccuracyChanged(Sensor sensor, int accuracy) { // Do something here if sensor accuracy changes. } @Override public final void onSensorChanged(SensorEvent event) { // The light sensor returns a single value. // Many sensors return 3 values, one for each axis. float lux = event.values[0]; // Do something with this sensor value. } @Override protected void onResume() { super.onResume(); sensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); sensorManager.unregisterListener(this); } }
  • 19. 19 Location (GPS Sensor) Location user drivers allow your app to publish updates to the device's physical location through the Android location services. The API supports constellations of the Global Navigation Satellite System (GNSS), such as the Global Positioning System (GPS). GNSS modules are receive-only devices that triangulate signals from remote satellites in order to determine an accurate physical location. Once the module collects enough satellite data to calculate an accurate position, it has a valid location (a fix ) that it can report. Receiver modules typically connect to the host system via UART, but may use other forms of Peripheral I/O. For example, they may contain additional GPIO pins to control power management or report when the module has gained or lost a fix. Note: The framework only supports a single source for GNSS location data. You cannot register multiple GNSS drivers.
  • 20. 20 How to get location of user? Adding the required permission Add the required permission for the user driver to your app's manifest file: <uses-permission android:name="com.google.android.things.permission.MANAGE_GNSS_DRI VERS" /> Creating the driver The driver implementation is responsible for communicating with the connected hardware, monitoring for valid location changes, and reporting those changes to the framework. To create a driver: 1) Create a new GnssDriver instance. 2) Register the driver with the UserDriverManager: import com.google.android.things.userdriver.location.GnssDriver; import com.google.android.things.userdriver.UserDriverManager;
  • 21. 21 How to get location of user? public class LocationDriverService extends Service { private GnssDriver mDriver; @Override public void onCreate() { super.onCreate(); mDriver = new GnssDriver(); // Create a new driver implementation UserDriverManager manager = UserDriverManager.getInstance(); // Register with the framework manager.registerGnssDriver(mDriver); } } 3) Unregister the driver when location events are not longer required. public class LocationDriverService extends Service { ... @Override protected void onDestroy() { super.onDestroy(); UserDriverManager manager = UserDriverManager.getInstance(); manager.unregisterGnssDriver(); } }
  • 22. 22 Reporting location Report each new location fix to the Android framework with the reportLocation() method. This method accepts a Location object, which contains the updated contents to report. Set the provider for each reported Location to LocationManager.GPS_PROVIDER. import android.location.Location; ... public class LocationDriverService extends Service { private GnssDriver mDriver; ... private Location parseLocationFromString(String data) { Location result = new Location(LocationManager.GPS_PROVIDER); // ...parse raw GNSS information... return result; } public void handleLocationUpdate(String rawData) { // Convert raw data into a location object Location location = parseLocationFromString(rawData); // Send the location update to the framework mDriver.reportLocation(location); } }
  • 23. 23 Location attributes he following table describes the Location attributes that a driver can report to the framework. Attributes marked required must be included or the framework will reject the location update: Required Attributes Optional Attributes Accuracy Timestamp Latitude Longitude Altitude Bearing Speed
  • 24. 24 Converting GPS data GPS is a commonly used constellation of GNSS satellites. GPS hardware typically reports location information as ASCII strings in the NMEA standard format. Each line of data is a comma-separated list of data values known as a sentence. While each GPS module may choose to report different portions of the NMEA protocol, most devices send one or more of the following sentences: GPGGA (Fix Information): Includes position fix, altitude, timestamp, and satellite metadata. GPGLL (Geographic Latitude/Longitude): Includes position fix and timestamp. GPRMC (Recommended Minimum Navigation): Includes position fix, speed, timestamp, and navigation metadata. As an example, the GPRMC sentence takes the following format: $GPRMC,<Time>,<Status>,<Latitude>,<Longitude>,<Speed>,<Angle>,<Date>,<Variatio n>,<Integrity>,<Checksum> Using real data values, here is a sample GPRMC with the latitude, longitude, and speed portions highlighted in bold: $GPRMC,172934.975,V,3554.931,N,07402.499,W,16.4,3.35,300816,,E*41
  • 25. 25 GPRMC string format into a Location instance // Convert latitude from DMS to decimal format private float parseLatitude(String latString, String hemisphere) { float lat = Float.parseFloat(latString.substring(2))/60.0f; lat += Float.parseFloat(latString.substring(0, 2)); if (hemisphere.contains("S")) { lat *= -1; } return lat; } // Convert longitude from DMS to decimal format private float parseLongitude(String longString, String hemisphere) { float lat = Float.parseFloat(longString.substring(3))/60.0f; lat += Float.parseFloat(longString.substring(0, 3)); if (hemisphere.contains("W")) { lat *= -1; } return lat; }
  • 26. 26 GPRMC string format into a Location instance // Return a location from an NMEA GPRMC string public Location parseLocationFromString(String rawData) { // Tokenize the string input String[] nmea = rawData.split(","); Location result = new Location(LocationManager.GPS_PROVIDER); // Create timestamp from the date + time tokens SimpleDateFormat format = new SimpleDateFormat("ddMMyyhhmmss.ss"); format.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date date = format.parse(nmea[9] + nmea[1]); result.setTime(date.getTime()); } catch (ParseException e) { return null; } // Parse the fix information tokens result.setLatitude(parseLatitude(nmea[3], nmea[4])); result.setLongitude(parseLongitude(nmea[5], nmea[6])); result.setSpeed(Float.parseFloat(nmea[7])); return result; }
  • 27. 27 GPS Data Example public class MainActivity extends AppCompatActivity implements LocationListener { private LocationManager locationManager; Location location; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i("Location", "Checking Sensors."); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Log.i("Location","location.getLongitude()"); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // for ActivityCompat#requestPermissions for more details. Log.i("Location","Permission not allowed"); return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60, 10, this); } }
  • 28. 28 GPS Data Example @Override public void onLocationChanged(@NonNull Location location) { Log.i("Location",""+location.getLongitude()); ((TextView)findViewById(R.id.tvLocation)).setText(""+location.getLatitude()); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.i("Location",""+ status + ", "+extras.toString()); } }