SlideShare a Scribd company logo
Sensor
TK2323 Mobile Programming
Sem 1 2017/2018
Lam Meng Chun
lammc@ukm.edu.my (G-02)
Outline
Categories of sensors
▹ Motion sensors
▹ Environmental sensors
▹ Position sensors
Android Sensor
Framework
▹ Hardware-based
▹ Software-based
▹ SensorManager
▹ Sensor
▹ SensorEvent
▹ SensorEventListener
Best Practices for
Accessing and Using
Sensors
2
Location (Lab) Run Time Permission
Sensor
3
4
Sensor of
Galaxy S5
4
Categories of
sensors
6 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
▸useful if you want to monitor three-dimensional device
movement or positioning,
▸monitor changes in the ambient environment near a
device.
7 Sensors Overview
▹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 dew point,
▹or a travel application might use the geomagnetic field
sensor and accelerometer to report a compass bearing.
8 Sensors Overview
9 Sensors Categories Overview
▹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 proximity sensors and magnetometers.
Introduction to
Sensor
11 Introduction to Sensor
▹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.
12 Introduction to Sensor
▹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.
▸linear acceleration sensor
▸gravity sensor
13 Introduction to Sensor
14 Introduction to Sensor
▹Few Android devices have every type of sensor.
▹For example, most handset devices and tablets have an
accelerometer and a magnetometer, but fewer devices have
barometers or thermometers.
▹Also, a device can have more than one sensor of a given type.
▹For example, a device can have two gravity sensors, each one
having a different range.
15 Introduction to Sensor
16 Introduction to Sensor
Sensor.TYPE_AMBIENT_TEMPERATURE
• Introduced in Android 4.0 (API level 14) to replace the ambiguous
Sensor.TYPE_TEMPERATURE (Deprecated)
• This is a thermometer that returns the temperature in degrees
Celsius;
• The temperature returned will be the ambient room temperature.
(the temperature of the surroundings)
Sensor.TYPE_RELATIVE_HUMIDITY
• A relative humidity sensor that returns the current relative humidity
as a percentage.
17
Humidity
sensor
• https://www.ifixit.com/Teardown/Samsung+Galaxy+S4+Teardo
wn/13947
18
Temperature
and humidity
Sensor
• https://www.ifixit.com/Teardown/Samsung+Galaxy+S4+Teardo
wn/13947
19
Temperature and humidity
Sensor
▹ if a device has both a humidity sensor
(TYPE_RELATIVE_HUMIDITY) and a temperature sensor
(TYPE_AMBIENT_TEMPERATURE) you can use these two
data streams to calculate the dew point and the absolute
humidity.
20
Temperature and humidity
Sensor
▹dew point is the temperature at which a given volume of
air must be cooled, at constant barometric pressure, for
water vapor to condense into liquid water
21
Temperature and humidity
Sensor
▹The dew point is a very important tool in forecasting
weather. It helps us with forecasting fog, icing, and the
comfort level of the air to humans
22 Dew Point
23
Temperature and humidity
Sensor
▹Absolute humidity is the mass of water vapor in a given
volume of dry air (grams/meter3).
▹Relative humidity also measures water vapor
▸expressed as the amount of water vapor in the air as
a percentage of the total amount that could be held at
its current temperature.
• http://info.zehnderamerica.com/blog/absolute-vs.-relative-
humidity-what%E2%80%99s-the-difference
24
Humidity
25 Absolute Humidity
• http://info.zehnderamerica.com/blog/absolute-vs.-relative-
humidity-what%E2%80%99s-the-difference
26 Introduction to Sensor
Sensor.TYPE_ACCELEROMETER
• A three-axis accelerometer that returns the
current acceleration along three axes in
m/s2 (meters per second, per second.)
27 Accelerometer
▹Conceptually, an acceleration sensor determines the
acceleration that is applied to a device (Ad) by measuring
the forces that are applied to the sensor itself (Fs) using the
following relationship:
▹However, the force of gravity is always influencing the
measured acceleration according to the following
relationship:
28 Accelerometer
Mass on spring
Gravity Free Fall Linear Acceleration Linear
Acceleration
plus gravity
1g = 9.8m/s2
-1g
1g
29 Accelerometer
▹When the device is sitting on a table (and not accelerating), the accelerometer
reads a magnitude of g = 9.81 m/s2.
▹Similarly, when the device is in free fall and therefore rapidly accelerating toward
the ground at 9.81 m/s2, its accelerometer reads a magnitude of g = 0 m/s2.
▹Therefore, to measure the real acceleration of the device, the contribution of the
force of gravity must be removed from the accelerometer data.
▹This can be achieved by applying a high-pass filter and low-pass filter can be used
to isolate the force of gravity.
▹Example
(http://developer.android.com/guide/topics/sensors/sensors_motion.html)
30
Sensor
Coordinate
System
31 Accelerometer
▹Accelerometers use the standard sensor coordinate system. In
practice, this means that the following conditions apply when a
device is laying flat on a table in its natural orientation:
▸If you push the device on the left side (so it moves to the
right), the x acceleration value is positive.
▸If you push the device on the bottom (so it moves away from
you), the y acceleration value is positive.
▸If you push the device toward the sky with an acceleration of
A m/s2, the z acceleration value is equal to A + 9.81, which
corresponds to the acceleration of the device (+A m/s2) minus
the force of gravity (-9.81 m/s2).
32 Accelerometer
▹In general, the accelerometer is a good sensor to use if you are
monitoring device motion.
▹Almost every Android-powered handset and tablet has an
accelerometer,
▹and it uses about 10 times less power than the other motion
sensors.
▹One drawback is that you might have to implement low-pass
and high-pass filters to eliminate gravitational forces and reduce
noise.
33 Introduction to Sensor
Sensor.TYPE_GRAVITY
• A three-axis gravity sensor that returns the current direction and magnitude
of gravity along three axes in m/s2.
• The gravity sensor typically is implemented as a virtual sensor by applying a
low-pass filter to the accelerometer sensor results.
Sensor.TYPE_LINEAR_ACCELERATION
• A three-axis linear acceleration Sensor that returns the acceleration, not
including gravity, along three axes in m/s2 .
• Like the gravity sensor, the linear acceleration typically is implemented as a
virtual sensor using the accelerometer output.
• A high-pass filter is applied to the accelerometer output
34
Accelerometer
Mass on spring
Linear Acceleration Linear
Acceleration
plus gravity
35 Introduction to Sensor
Sensor.TYPE_GYROSCOPE
• A three-axis gyroscope that returns the rate of device
rotation along three axes in radians/second.
• To get the rotation, you can integrate the rate of rotation
over time to determine the current orientation of the
device;
• however, it generally is better practice to use this in
combination with other sensors (typically the
accelerometers) to provide a smoothed and corrected
orientation.
36 Gyroscope
▹The sensor's coordinate system is the same as the one
used for the acceleration sensor.
▹Rotation is positive in the counter-clockwise direction;
▹that is, an observer looking from some positive location
on the x, y or z axis at a device positioned on the origin
would report positive rotation if the device appeared to be
rotating counter clockwise.
37 Gyroscope
▹Standard gyroscopes provide raw rotational data without
any filtering or correction for noise and drift (bias).
▹In practice, gyroscope noise and drift will introduce errors
that need to be compensated for.
▹You usually determine the drift (bias) and noise by
monitoring other sensors, such as the gravity sensor or
accelerometer.
38 Uncalibrated Gyroscope
▹Uncalibrated sensors provide more raw results and may include
some bias, but their measurements contain fewer jumps from
corrections applied through calibration.
▹Some applications may prefer these uncalibrated results as
smoother and more reliable.
▹For instance, if an application is attempting to conduct its own
sensor fusion, using calibrations can actually distort results.
▹Sensor fusion.
(https://www.youtube.com/watch?v=C7JQ7Rpwn2k)
39 Introduction to Sensor
Sensor.TYPE_ROTATION_VECTOR
• Returns the orientation of the device as a combination of an
angle around an axis.
• It typically is used as an input to the
getRotationMatrixFromVector method from the Sensor
Manager to convert the returned rotation vector into a
rotation matrix.
• The rotation vector Sensor typically is implemented as a
virtual sensor that can combine and correct the results
obtained from multiple sensors, such as the accelerometers
and gyroscopes, to provide a smoother rotation matrix.
40
Using the Game Rotation
Vector Sensor
▹The game rotation vector sensor is identical to the Rotation Vector
Sensor, except it does not use the geomagnetic field.
▹Therefore the Y axis does not point north but instead to some other
reference.
▹Because the game rotation vector sensor does not use the magnetic
field, relative rotations are more accurate, and not impacted by
magnetic field changes.
▹Use this sensor in a game if you do not care about where north is,
and the normal rotation vector does not fit your needs because of its
reliance on the magnetic field.
41 Introduction to Sensor
Sensor.TYPE_MAGNETIC_FIELD
• A magnetometer that finds the current magnetic field in microteslas
(μT) along three axes.
Sensor.TYPE_PRESSURE
• An atmospheric pressure sensor, or barometer, that returns the
current atmospheric pressure in millibars (mbars) as a single value.
• The pressure Sensor can be used to determine altitude using the
getAltitude method on the Sensor Manager to compare the
atmospheric pressure in two locations.
• Barometers can also be used in weather forecasting by measuring
changes in atmospheric pressure in the same location.
Barometer: Pressure
• https://www.ifixit.com/Teardown/Samsung+Galaxy+S4+Teardo
wn/13947
43 Introduction to Sensor
Sensor.TYPE_LIGHT
• An ambient light sensor that
returns a single value describing
the ambient illumination in lux.
• A light sensor commonly is used to
control the screen brightness
dynamically.
44 Introduction to Sensor
Sensor.TYPE_PROXIMITY
• A proximity sensor that indicates the distance between the
device and the target object in centimeters.
• How a target object is selected, and the distances supported,
will depend on the hardware implementation of the proximity
detector.
• Some proximity sensors can return only “near” or “far” results.
• Typical uses for the proximity sensor are to detect when the
device is being held up against the user’s ear, to automatically
adjust screen brightness, or to initiate a voice command
45 Proximity sensor
▹The proximity sensor lets you determine how close the
face of a device is to an object.
▹Some proximity sensors provide only binary values
representing near and far.
46 Proximity sensor
47 Proximity Sensor
48 Air Gesture
▹The placement of the two IR sensors on either side of the
earpiece speaker explains how Samsung's new Air View/Air
Gesture feature operates.
▹By comparing IR light reflected from your hand into each
of the sensors, the phone can track sideways motion as you
gesture without touching the screen.
49 Introduction to Sensor
Sensor.TYPE_STEP_DETECTOR
• This sensor triggers an event each time the user takes a step.
• Upon each user step, this sensor delivers an event with a value
of 1.0 and a timestamp indicating when the step occurred.
Sensor.TYPE_STEP_COUNTER
• This sensor also triggers an event upon each detected step,
but instead delivers the total accumulated number of steps
since this sensor was first registered by an app.
Android sensor framework
51 Sensors Overview
▹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.
52 Sensors Overview
▹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.
53 Sensor Framework
▹You can access these
sensors and acquire raw
sensor data by using the
Android sensor framework.
▹It 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.
54 Sensor Framework
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.
55 Sensor Framework
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.
• onAccuracyChanged(Sensor sensor, int accuracy)
• onSensorChanged(SensorEvent event)
56
Get Default Sensor for
certain type of sensor
▹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.
57 Example: Get All 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.
private SensorManager mSensorManager;
...
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
List<Sensor> deviceSensors =
mSensorManager.getSensorList(Sensor.TYPE_ALL);
58
Get Default Sensor for
certain type of sensor
▹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.
59
Example: Get Default Sensor
for certain type of sensor
private SensorManager mSensorManager;
...
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
!= null){
// Success! There's a magnetometer.
}
else {
// Failure! No magnetometer.
}
60 Other Useful Method
▹you can use the public methods of the Sensor class to
determine the capabilities and attributes of individual
sensors.
▹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.
61 Other Useful Method
▹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.
62
Example: Find the best
sensor
List<Sensor> lightSensors = mSensorManager.getSensorList(Sensor.TYPE_LIGHT);
Sensor bestLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (bestLightSensor != null)
for (Sensor lightSensor : lightSensors) {
float range = lightSensor.getMaximumRange();
float power = lightSensor.getPower();
if (range >= bestLightSensor.getMaximumRange())
if (power < bestLightSensor.getPower()
|| range > bestLightSensor.getMaximumRange())
bestLightSensor = lightSensor;
}
}
Monitoring Sensor
Events
64 Monitoring Sensor Events
▹To monitor raw sensor data you need to implement two
callback methods that are exposed through the
SensorEventListener interface:
▸onAccuracyChanged()
▸onSensorChanged().
▹The Android system calls these methods whenever the
following occurs:
▸A sensor's accuracy changes.
▸A sensor reports a new value.
65 Monitoring Sensor Events
▹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,
▸SENSOR_STATUS_UNRELIABLE.
66 Monitoring Sensor Events
▹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.
67
Example: Monitoring Sensor
Events
public class MainActivity extends Activity
implements SensorEventListener {
public SensorManager mSensorManager;
private Sensor mLightSensor;
68
Example: Monitoring Sensor
Events
public class MainActivity extends Activity implements
SensorEventListener {
.
.
.
mSensorManager =
(SensorManager)getSystemService(SENSOR_SERVICE);
mLightSensor = new LightSensor(getBaseContext());
69
Example: Monitoring Sensor
Events
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
@Override
public 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.
}
70
Example: Monitoring Sensor
Events
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mSensorManager.registerListener(this, mLightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mSensorManager.unregisterListener(this);
}
Handling Different
Sensor
Configurations
72
Handling Different Sensor
Configurations
▹If your application relies on a specific type of sensor, you have to ensure
that the sensor is present on a device so your app can run successfully.
▸Motorola Xoom has a pressure sensor, but the Samsung Nexus S does
not
▸Motorola Xoom and Nexus S have gyroscopes, but the HTC Nexus One
does not
▹You have two options for ensuring that a given sensor is present on a
device:
▸Detect sensors at runtime and enable or disable application
features as appropriate.
▸Use Google Play filters to target devices with specific sensor
configurations.
73 Detecting sensors at runtime
▹If your application uses a specific type of sensor, but doesn't
rely on it, you can use the sensor framework to detect the sensor
at runtime and then disable or enable application features as
appropriate.
▹For example, a navigation application might use the
▸temperature sensor,
▸pressure sensor,
▸GPS sensor, and
▸geomagnetic field sensor
▸to display the temperature, barometric pressure, location,
and compass bearing.
Which is the most important one?
74 Detecting sensors at runtime
▹If a device doesn't have a pressure sensor, you can use the
sensor framework to detect the absence of the pressure
sensor at runtime and then disable the portion of your
application's UI that displays pressure.
▹For example, the following code checks whether there's a
pressure sensor on a device:
75
Example: Detecting sensors
at runtime
▹For example, the following code checks whether there's a
pressure sensor on a device:
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) != null){
// Success! There's a pressure sensor.
}
else {
// Failure! No pressure sensor.
}
76
Using Google Play filters to target
specific sensor configurations
▹If you are publishing your application on Google Play you can
use the <uses-feature> element in your manifest file to filter your
application from devices that do not have the appropriate sensor
configuration for your application.
▹The <uses-feature> element has several hardware descriptors
that let you filter applications based on the presence of specific
sensors.
▹The sensors you can list include: accelerometer, barometer,
compass (geomagnetic field), gyroscope, light, and proximity.
77 Example: Google Play filters
▹For example, the following code checks whether there's a
pressure sensor on a device:
<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
• If you add this element and descriptor to your application's manifest, users will see
your application on Google Play only if their device has an accelerometer.
78
Using Google Play filters to target specific
sensor configurations
▹You should set the descriptor
to android:required="true" only if your application relies
entirely on a specific sensor.
▹If your application uses a sensor for some functionality,
but still runs without the sensor, you should list the sensor in
the <uses-feature> element, but set the descriptor
to android:required="false".
79
Using Google Play filters to target
specific sensor configurations
▹This helps ensure that devices can install your app even if
they do not have that particular sensor.
▹This is also a project management best practice that helps
you keep track of the features your application uses.
▹Keep in mind, if your application uses a particular sensor,
but still runs without the sensor, then you should detect the
sensor at runtime and disable or enable application features
as appropriate.
Permission
80
81
Categories of the
Permissions
Normal permissions
do not directly risk the user's
privacy. If your app lists a
normal permission in its
manifest, the system grants the
permission automatically.
▹VIBRATE
▹BLUETOOTH
▹WIFI…
▹https://developer.android.com/guide/topics/permission
s/normal-permissions.html
Dangerous permissions
can give the app access to the
user's confidential data. If your
app lists a normal permission in
its manifest, the system grants
the permission automatically. If
you list a dangerous permission,
the user has to explicitly give
approval to your app.
81
82
Permission
Example
▹https://developer.android.com/guide/topics/permissions/requesting.html
83 Situations
▹If an app requests a dangerous permission listed in its
manifest, and the app does not currently have any
permissions in the permission group
▹For example, if an app requests the READ_CONTACTS
permission, the system dialog box just says the app needs
access to the device's contacts.
▹If the user grants approval, the system gives the app just
the permission it requested.
84 Situations
▹If an app requests a dangerous permission listed in its
manifest, and the app already has another dangerous
permission in the same permission group,
▹For example, if an app had previously requested and been
granted the READ_CONTACTS permission,
▹and it then requests WRITE_CONTACTS, the system
immediately grants that permission.
85
Request Permission
(Manifest)
Contains Dangerous
Permissions
Android 6.0 (API level
23) or higher
▹ Request in Runtime
▹ The user can revoke
the permissions at
any time, so the app
needs to check
whether it has the
permissions every
time it runs.
▹Android 5.1 (API level
22) or lower
▹Request during
installation
▹Once the user installs
the app, the only way
they can revoke the
permission is by
uninstalling the app.
87
Useful Information – check
android version
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
}
*Check user’s device android version
88
Useful Information – check
permission
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION) ==PackageManager.PERMISSION_GRANTED)
{
*Check the status of the permission (Granted / not granted)
89
Useful Information – if
denied, what should do
//shouldShowRequestPermissionRationale will be true if the permission
previously denied the request
if
(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION
)) {
90
Useful Information – the method called
after user has made their decision
//this method will be called after the uses has responed to the permission dialog box
@Override
public void onRequestPermissionsResult(int requestCode,String permissions[],
int[] grantResults)
{if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
91
▹Check the Lab assignment
Android Runtime Permission
Best Practices for
Accessing and Using
Sensors
93
Best Practices for Accessing
and Using Sensors
Unregister sensor listeners
Don't test your code on the emulator
Don't block the onSensorChanged() method
Avoid using deprecated methods or sensor types
Verify sensors before you use them
Choose sensor delays carefully
94 Unregister sensor listeners
▹Be sure to unregister a sensor's listener when you are
done using the sensor or when the sensor activity pauses.
▹If a sensor listener is registered and its activity is paused,
the sensor will continue to acquire data and use battery
resources unless you unregister the sensor.
▹onPause()
95
Don't test your code on the
emulator
▹You currently can't test sensor code on the emulator
because the emulator cannot emulate sensors.
▹You must test your sensor code on a physical device.
▹There are, however, sensor simulators that you can use
to simulate sensor output.
96
Don't block the
onSensorChanged() method
▹Sensor data can change at a high rate, which means the system
may call the onSensorChanged(SensorEvent) method quite
often.
▹As a best practice, you should do as little as possible within
the onSensorChanged(SensorEvent) method so you don't block it.
▹If your application requires you to do any data filtering or
reduction of sensor data, you should perform that work outside
of the onSensorChanged(SensorEvent) method.
97
Avoid using deprecated
methods or sensor types
▹Several methods and constants have been deprecated.
▹The TYPE_ORIENTATION sensor type has been deprecated.
▹To get orientation data you should use the getOrientation()
method instead.
▹Likewise, the TYPE_TEMPERATURE sensor type has been
deprecated.
▹You should use the TYPE_AMBIENT_TEMPERATURE sensor type
instead on devices that are running Android 4.0.
98
Verify sensors before you
use them
▹Always verify that a sensor exists on a device before you
attempt to acquire data from it.
▹Don't assume that a sensor exists simply because it's a
frequently-used sensor.
▹Device manufacturers are not required to provide any
particular sensors in their devices.
99
Choose sensor delays
carefully
▹When you register a sensor with the registerListener()
method, be sure you choose a delivery rate that is suitable
for your application or use-case.
▹Sensors can provide data at very high rates.
▹Allowing the system to send extra data that you don't
need wastes system resources and uses battery power.
Location
101 Location Services
▹Android gives your applications access to the location
services supported by the device through classes in the
android.location package
▹The central component of the location framework is the
LocationManager system service, which provides APIs to
determine location and bearing of the underlying device (if
available).
102 Location Services
▹As with other system services, you do not instantiate a
LocationManager directly.
▹You request an instance from the system by calling
getSystemService(Context.LOCATION_SERVICE).
▹The method returns a handle to a new LocationManager
instance.
103 Location Services
▹Once your application has a LocationManager, your application
is able to do three things:
▸Query for the list of all LocationProviders for the last known
user location.
▸Register/unregister for periodic updates of the user's current
location from a location provider (specified either by criteria or
name).
▸Register/unregister for a given Intent to be fired if the device
comes within a given proximity (specified by radius in meters)
of a given lat/long.
104
Challenges in Determining
User Location
▹Can contain errors and be inaccurate.
▹Multitude of location sources
▸GPS, Cell-ID, and Wi-Fi can each provide a clue to users location.
▸Determining which to use and trust is a matter of trade-offs in accuracy, speed, and
battery-efficiency.
▹User movement
▸Because the user location changes, you must account for movement by re-estimating user
location every so often.
▹Varying accuracy
▸Location estimates coming from each location source are not consistent in their accuracy.
▸A location obtained 10 seconds ago from one source might be more accurate than the
newest location from another or same source.
105 Requesting Location Updates
▹Getting user location in Android works by means of
callback.
▹You indicate that you'd like to receive location updates
from the LocationManager ("Location Manager") by calling
requestLocationUpdates(), passing it a LocationListener.
▹Your LocationListener must implement several callback
methods that the Location Manager calls when the user
location changes or when the status of the service changes.
106
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 5000, 5,
locationListener);
107 Requesting Location Updates
▹onLocationChanged(Location location)
▸Called when the location has changed.
▹onProviderEnabled(String provider)
▸Called when the provider is enabled by the user.
▹onProviderDisabled(String provider)
▸Called when the provider is disabled by the user.
▸If requestLocationUpdates is called on an already
disabled provider, this method is called immediately
108 Requesting Location Updates
▹onStatusChanged(String provider, int status, Bundle extras)
▸Called when the provider status changes.
▸This method is called when a provider is unable to fetch a
location or if the provider has recently become available after
a period of unavailability.
▸OUT_OF_SERVICE if the provider is out of service, and this is
not expected to change in the near future;
▸TEMPORARILY_UNAVAILABLE if the provider is temporarily
unavailable but is expected to be available shortly;
▸AVAILABLE if the provider is currently available.
109 Requesting User Permissions
▹If you are using both NETWORK_PROVIDER and GPS_PROVIDER,
then you need to request only the
ACCESS_FINE_LOCATION permission, because it includes
permission for both providers.
▹Permission for ACCESS_COARSE_LOCATION includes
permission only for NETWORK_PROVIDER.
<manifest ... >
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
...
</manifest>
110 Requesting Location Updates
▹The first parameter in requestLocationUpdates() is the type of location
provider to use
▸Network Location Provider
▸GPS Provider
▹You can control the frequency at which your listener receives updates
with the second and third parameter
▸the second is the minimum time interval between notifications
▸the third is the minimum change in distance between notifications
▸setting both to zero requests location notifications as frequently as
possible. The last parameter is your LocationListener, which receives
callbacks for location updates.
111 Could you answer it?
▹Android has classify the sensor into three categories. What
categories it is and explain about it.
▹Give three example of the sensors and describe the usage.
▹What is the best practices for accessing and Using Sensors
in term of the programming aspect?

More Related Content

PDF
Generic sensors for the Web
ODP
Android sensors
PPT
Smartphone sensor and gesture
PPTX
Mobile Sensors
PPSX
Sensor's inside
PDF
Android Sensors
PPTX
Different types of sensors
PDF
Sensors and location based services
Generic sensors for the Web
Android sensors
Smartphone sensor and gesture
Mobile Sensors
Sensor's inside
Android Sensors
Different types of sensors
Sensors and location based services

What's hot (20)

PPTX
Sensors and its type by ss
PDF
Correction tool for Lidar in complex terrains based on Meteodyn WT outputs
PPT
Types of sensors
PDF
Sensors on android
PPTX
Sensors and its types
PPTX
High speed measurement
PDF
Total station
DOCX
Anemometers Assignment
PPTX
List of instrument
PDF
Popular science a guide to common drone vocabulary
DOCX
Teodoro
PPSX
Speed, Acceleration and Vibration Measurement
PDF
Total station setup and operation
PPTX
Android Sensor
PDF
Wind speed measurement (1)
PDF
MISSION PLANNER GROUND CONTROL STATION
PDF
3 a1 lecture 8
PDF
Use of internal sensors of tablets and smarphones in physics #scichallenge2017
Sensors and its type by ss
Correction tool for Lidar in complex terrains based on Meteodyn WT outputs
Types of sensors
Sensors on android
Sensors and its types
High speed measurement
Total station
Anemometers Assignment
List of instrument
Popular science a guide to common drone vocabulary
Teodoro
Speed, Acceleration and Vibration Measurement
Total station setup and operation
Android Sensor
Wind speed measurement (1)
MISSION PLANNER GROUND CONTROL STATION
3 a1 lecture 8
Use of internal sensors of tablets and smarphones in physics #scichallenge2017
Ad

Similar to Tk2323 lecture 10 sensor (20)

PPTX
Sensors 9
PPT
iwatchjr | Mobile Handset Sensors Coordinate System
DOCX
Sensor android
PDF
Week12.pdf
PPT
Sensing Mobile Devices talk from QCon London 2013
PPTX
Base sensor
PDF
Better motion control using accelerometer/gyroscope sensor fusion
PPTX
IoT Sensors & Integration with Physical World
PPT
Low-g Accelerometers Part 1 - Basic Knowledge of Accelerometers
PPTX
Sensors and Actuators by VIRTUAL BASICS MACHINE.pptx
PDF
Motion recognition with Android devices
PPTX
power point presenatation onee sensers tc
PPTX
Android Training (Sensors)
PDF
Complex Sensors
PDF
Sensors in Android (old)
PPTX
Avi Itzkovitch- Designing with sensors
PPTX
Android 1.8 sensor
PPTX
Mobile Sensors
PPTX
Smart sensors
DOCX
Mobile Sensors and Types
Sensors 9
iwatchjr | Mobile Handset Sensors Coordinate System
Sensor android
Week12.pdf
Sensing Mobile Devices talk from QCon London 2013
Base sensor
Better motion control using accelerometer/gyroscope sensor fusion
IoT Sensors & Integration with Physical World
Low-g Accelerometers Part 1 - Basic Knowledge of Accelerometers
Sensors and Actuators by VIRTUAL BASICS MACHINE.pptx
Motion recognition with Android devices
power point presenatation onee sensers tc
Android Training (Sensors)
Complex Sensors
Sensors in Android (old)
Avi Itzkovitch- Designing with sensors
Android 1.8 sensor
Mobile Sensors
Smart sensors
Mobile Sensors and Types
Ad

More from MengChun Lam (11)

PPTX
Tk2323 lecture 9 api json
PPTX
Tk2323 lecture 11 process and thread
PPTX
Tk2323 lecture 8 firebase
PPTX
Tk2323 lecture 4 ui ux
PPTX
Tk2323 lecture 6 fragment (new)
PPTX
Tk2323 lecture 7 data storage
PPTX
Tk2323 lecture 5 material design &amp; recycler view
PPTX
Tk2323 lecture 7 sql
PPTX
Tk2323 lecture 3 intent
PPTX
Tk2323 lecture 2 ui
PPTX
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 9 api json
Tk2323 lecture 11 process and thread
Tk2323 lecture 8 firebase
Tk2323 lecture 4 ui ux
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 7 data storage
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 7 sql
Tk2323 lecture 3 intent
Tk2323 lecture 2 ui
Tk2323 lecture 1 introduction to mobile application

Recently uploaded (6)

PDF
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
PDF
6-UseCfgfhgfhgfhgfhgfhfhhaseActivity.pdf
PDF
heheheueueyeyeyegehehehhehshMedia-Literacy.pdf
DOC
证书学历UoA毕业证,澳大利亚中汇学院毕业证国外大学毕业证
DOC
Camb毕业证学历认证,格罗斯泰斯特主教大学毕业证仿冒文凭毕业证
PPTX
ASMS Telecommunication company Profile
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
6-UseCfgfhgfhgfhgfhgfhfhhaseActivity.pdf
heheheueueyeyeyegehehehhehshMedia-Literacy.pdf
证书学历UoA毕业证,澳大利亚中汇学院毕业证国外大学毕业证
Camb毕业证学历认证,格罗斯泰斯特主教大学毕业证仿冒文凭毕业证
ASMS Telecommunication company Profile

Tk2323 lecture 10 sensor

  • 1. Sensor TK2323 Mobile Programming Sem 1 2017/2018 Lam Meng Chun lammc@ukm.edu.my (G-02)
  • 2. Outline Categories of sensors ▹ Motion sensors ▹ Environmental sensors ▹ Position sensors Android Sensor Framework ▹ Hardware-based ▹ Software-based ▹ SensorManager ▹ Sensor ▹ SensorEvent ▹ SensorEventListener Best Practices for Accessing and Using Sensors 2 Location (Lab) Run Time Permission
  • 6. 6 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 ▸useful if you want to monitor three-dimensional device movement or positioning, ▸monitor changes in the ambient environment near a device.
  • 7. 7 Sensors Overview ▹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 dew point, ▹or a travel application might use the geomagnetic field sensor and accelerometer to report a compass bearing.
  • 9. 9 Sensors Categories Overview ▹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 proximity sensors and magnetometers.
  • 11. 11 Introduction to Sensor ▹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.
  • 12. 12 Introduction to Sensor ▹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. ▸linear acceleration sensor ▸gravity sensor
  • 14. 14 Introduction to Sensor ▹Few Android devices have every type of sensor. ▹For example, most handset devices and tablets have an accelerometer and a magnetometer, but fewer devices have barometers or thermometers. ▹Also, a device can have more than one sensor of a given type. ▹For example, a device can have two gravity sensors, each one having a different range.
  • 16. 16 Introduction to Sensor Sensor.TYPE_AMBIENT_TEMPERATURE • Introduced in Android 4.0 (API level 14) to replace the ambiguous Sensor.TYPE_TEMPERATURE (Deprecated) • This is a thermometer that returns the temperature in degrees Celsius; • The temperature returned will be the ambient room temperature. (the temperature of the surroundings) Sensor.TYPE_RELATIVE_HUMIDITY • A relative humidity sensor that returns the current relative humidity as a percentage.
  • 19. 19 Temperature and humidity Sensor ▹ if a device has both a humidity sensor (TYPE_RELATIVE_HUMIDITY) and a temperature sensor (TYPE_AMBIENT_TEMPERATURE) you can use these two data streams to calculate the dew point and the absolute humidity.
  • 20. 20 Temperature and humidity Sensor ▹dew point is the temperature at which a given volume of air must be cooled, at constant barometric pressure, for water vapor to condense into liquid water
  • 21. 21 Temperature and humidity Sensor ▹The dew point is a very important tool in forecasting weather. It helps us with forecasting fog, icing, and the comfort level of the air to humans
  • 23. 23 Temperature and humidity Sensor ▹Absolute humidity is the mass of water vapor in a given volume of dry air (grams/meter3). ▹Relative humidity also measures water vapor ▸expressed as the amount of water vapor in the air as a percentage of the total amount that could be held at its current temperature. • http://info.zehnderamerica.com/blog/absolute-vs.-relative- humidity-what%E2%80%99s-the-difference
  • 25. 25 Absolute Humidity • http://info.zehnderamerica.com/blog/absolute-vs.-relative- humidity-what%E2%80%99s-the-difference
  • 26. 26 Introduction to Sensor Sensor.TYPE_ACCELEROMETER • A three-axis accelerometer that returns the current acceleration along three axes in m/s2 (meters per second, per second.)
  • 27. 27 Accelerometer ▹Conceptually, an acceleration sensor determines the acceleration that is applied to a device (Ad) by measuring the forces that are applied to the sensor itself (Fs) using the following relationship: ▹However, the force of gravity is always influencing the measured acceleration according to the following relationship:
  • 28. 28 Accelerometer Mass on spring Gravity Free Fall Linear Acceleration Linear Acceleration plus gravity 1g = 9.8m/s2 -1g 1g
  • 29. 29 Accelerometer ▹When the device is sitting on a table (and not accelerating), the accelerometer reads a magnitude of g = 9.81 m/s2. ▹Similarly, when the device is in free fall and therefore rapidly accelerating toward the ground at 9.81 m/s2, its accelerometer reads a magnitude of g = 0 m/s2. ▹Therefore, to measure the real acceleration of the device, the contribution of the force of gravity must be removed from the accelerometer data. ▹This can be achieved by applying a high-pass filter and low-pass filter can be used to isolate the force of gravity. ▹Example (http://developer.android.com/guide/topics/sensors/sensors_motion.html)
  • 31. 31 Accelerometer ▹Accelerometers use the standard sensor coordinate system. In practice, this means that the following conditions apply when a device is laying flat on a table in its natural orientation: ▸If you push the device on the left side (so it moves to the right), the x acceleration value is positive. ▸If you push the device on the bottom (so it moves away from you), the y acceleration value is positive. ▸If you push the device toward the sky with an acceleration of A m/s2, the z acceleration value is equal to A + 9.81, which corresponds to the acceleration of the device (+A m/s2) minus the force of gravity (-9.81 m/s2).
  • 32. 32 Accelerometer ▹In general, the accelerometer is a good sensor to use if you are monitoring device motion. ▹Almost every Android-powered handset and tablet has an accelerometer, ▹and it uses about 10 times less power than the other motion sensors. ▹One drawback is that you might have to implement low-pass and high-pass filters to eliminate gravitational forces and reduce noise.
  • 33. 33 Introduction to Sensor Sensor.TYPE_GRAVITY • A three-axis gravity sensor that returns the current direction and magnitude of gravity along three axes in m/s2. • The gravity sensor typically is implemented as a virtual sensor by applying a low-pass filter to the accelerometer sensor results. Sensor.TYPE_LINEAR_ACCELERATION • A three-axis linear acceleration Sensor that returns the acceleration, not including gravity, along three axes in m/s2 . • Like the gravity sensor, the linear acceleration typically is implemented as a virtual sensor using the accelerometer output. • A high-pass filter is applied to the accelerometer output
  • 34. 34 Accelerometer Mass on spring Linear Acceleration Linear Acceleration plus gravity
  • 35. 35 Introduction to Sensor Sensor.TYPE_GYROSCOPE • A three-axis gyroscope that returns the rate of device rotation along three axes in radians/second. • To get the rotation, you can integrate the rate of rotation over time to determine the current orientation of the device; • however, it generally is better practice to use this in combination with other sensors (typically the accelerometers) to provide a smoothed and corrected orientation.
  • 36. 36 Gyroscope ▹The sensor's coordinate system is the same as the one used for the acceleration sensor. ▹Rotation is positive in the counter-clockwise direction; ▹that is, an observer looking from some positive location on the x, y or z axis at a device positioned on the origin would report positive rotation if the device appeared to be rotating counter clockwise.
  • 37. 37 Gyroscope ▹Standard gyroscopes provide raw rotational data without any filtering or correction for noise and drift (bias). ▹In practice, gyroscope noise and drift will introduce errors that need to be compensated for. ▹You usually determine the drift (bias) and noise by monitoring other sensors, such as the gravity sensor or accelerometer.
  • 38. 38 Uncalibrated Gyroscope ▹Uncalibrated sensors provide more raw results and may include some bias, but their measurements contain fewer jumps from corrections applied through calibration. ▹Some applications may prefer these uncalibrated results as smoother and more reliable. ▹For instance, if an application is attempting to conduct its own sensor fusion, using calibrations can actually distort results. ▹Sensor fusion. (https://www.youtube.com/watch?v=C7JQ7Rpwn2k)
  • 39. 39 Introduction to Sensor Sensor.TYPE_ROTATION_VECTOR • Returns the orientation of the device as a combination of an angle around an axis. • It typically is used as an input to the getRotationMatrixFromVector method from the Sensor Manager to convert the returned rotation vector into a rotation matrix. • The rotation vector Sensor typically is implemented as a virtual sensor that can combine and correct the results obtained from multiple sensors, such as the accelerometers and gyroscopes, to provide a smoother rotation matrix.
  • 40. 40 Using the Game Rotation Vector Sensor ▹The game rotation vector sensor is identical to the Rotation Vector Sensor, except it does not use the geomagnetic field. ▹Therefore the Y axis does not point north but instead to some other reference. ▹Because the game rotation vector sensor does not use the magnetic field, relative rotations are more accurate, and not impacted by magnetic field changes. ▹Use this sensor in a game if you do not care about where north is, and the normal rotation vector does not fit your needs because of its reliance on the magnetic field.
  • 41. 41 Introduction to Sensor Sensor.TYPE_MAGNETIC_FIELD • A magnetometer that finds the current magnetic field in microteslas (μT) along three axes. Sensor.TYPE_PRESSURE • An atmospheric pressure sensor, or barometer, that returns the current atmospheric pressure in millibars (mbars) as a single value. • The pressure Sensor can be used to determine altitude using the getAltitude method on the Sensor Manager to compare the atmospheric pressure in two locations. • Barometers can also be used in weather forecasting by measuring changes in atmospheric pressure in the same location.
  • 43. 43 Introduction to Sensor Sensor.TYPE_LIGHT • An ambient light sensor that returns a single value describing the ambient illumination in lux. • A light sensor commonly is used to control the screen brightness dynamically.
  • 44. 44 Introduction to Sensor Sensor.TYPE_PROXIMITY • A proximity sensor that indicates the distance between the device and the target object in centimeters. • How a target object is selected, and the distances supported, will depend on the hardware implementation of the proximity detector. • Some proximity sensors can return only “near” or “far” results. • Typical uses for the proximity sensor are to detect when the device is being held up against the user’s ear, to automatically adjust screen brightness, or to initiate a voice command
  • 45. 45 Proximity sensor ▹The proximity sensor lets you determine how close the face of a device is to an object. ▹Some proximity sensors provide only binary values representing near and far.
  • 48. 48 Air Gesture ▹The placement of the two IR sensors on either side of the earpiece speaker explains how Samsung's new Air View/Air Gesture feature operates. ▹By comparing IR light reflected from your hand into each of the sensors, the phone can track sideways motion as you gesture without touching the screen.
  • 49. 49 Introduction to Sensor Sensor.TYPE_STEP_DETECTOR • This sensor triggers an event each time the user takes a step. • Upon each user step, this sensor delivers an event with a value of 1.0 and a timestamp indicating when the step occurred. Sensor.TYPE_STEP_COUNTER • This sensor also triggers an event upon each detected step, but instead delivers the total accumulated number of steps since this sensor was first registered by an app.
  • 51. 51 Sensors Overview ▹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.
  • 52. 52 Sensors Overview ▹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.
  • 53. 53 Sensor Framework ▹You can access these sensors and acquire raw sensor data by using the Android sensor framework. ▹It 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.
  • 54. 54 Sensor Framework 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.
  • 55. 55 Sensor Framework 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. • onAccuracyChanged(Sensor sensor, int accuracy) • onSensorChanged(SensorEvent event)
  • 56. 56 Get Default Sensor for certain type of sensor ▹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.
  • 57. 57 Example: Get All 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. private SensorManager mSensorManager; ... mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); List<Sensor> deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
  • 58. 58 Get Default Sensor for certain type of sensor ▹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.
  • 59. 59 Example: Get Default Sensor for certain type of sensor private SensorManager mSensorManager; ... mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){ // Success! There's a magnetometer. } else { // Failure! No magnetometer. }
  • 60. 60 Other Useful Method ▹you can use the public methods of the Sensor class to determine the capabilities and attributes of individual sensors. ▹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.
  • 61. 61 Other Useful Method ▹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.
  • 62. 62 Example: Find the best sensor List<Sensor> lightSensors = mSensorManager.getSensorList(Sensor.TYPE_LIGHT); Sensor bestLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); if (bestLightSensor != null) for (Sensor lightSensor : lightSensors) { float range = lightSensor.getMaximumRange(); float power = lightSensor.getPower(); if (range >= bestLightSensor.getMaximumRange()) if (power < bestLightSensor.getPower() || range > bestLightSensor.getMaximumRange()) bestLightSensor = lightSensor; } }
  • 64. 64 Monitoring Sensor Events ▹To monitor raw sensor data you need to implement two callback methods that are exposed through the SensorEventListener interface: ▸onAccuracyChanged() ▸onSensorChanged(). ▹The Android system calls these methods whenever the following occurs: ▸A sensor's accuracy changes. ▸A sensor reports a new value.
  • 65. 65 Monitoring Sensor Events ▹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, ▸SENSOR_STATUS_UNRELIABLE.
  • 66. 66 Monitoring Sensor Events ▹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.
  • 67. 67 Example: Monitoring Sensor Events public class MainActivity extends Activity implements SensorEventListener { public SensorManager mSensorManager; private Sensor mLightSensor;
  • 68. 68 Example: Monitoring Sensor Events public class MainActivity extends Activity implements SensorEventListener { . . . mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); mLightSensor = new LightSensor(getBaseContext());
  • 69. 69 Example: Monitoring Sensor Events @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Do something here if sensor accuracy changes. } @Override public 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. }
  • 70. 70 Example: Monitoring Sensor Events @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); mSensorManager.registerListener(this, mLightSensor, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); mSensorManager.unregisterListener(this); }
  • 72. 72 Handling Different Sensor Configurations ▹If your application relies on a specific type of sensor, you have to ensure that the sensor is present on a device so your app can run successfully. ▸Motorola Xoom has a pressure sensor, but the Samsung Nexus S does not ▸Motorola Xoom and Nexus S have gyroscopes, but the HTC Nexus One does not ▹You have two options for ensuring that a given sensor is present on a device: ▸Detect sensors at runtime and enable or disable application features as appropriate. ▸Use Google Play filters to target devices with specific sensor configurations.
  • 73. 73 Detecting sensors at runtime ▹If your application uses a specific type of sensor, but doesn't rely on it, you can use the sensor framework to detect the sensor at runtime and then disable or enable application features as appropriate. ▹For example, a navigation application might use the ▸temperature sensor, ▸pressure sensor, ▸GPS sensor, and ▸geomagnetic field sensor ▸to display the temperature, barometric pressure, location, and compass bearing. Which is the most important one?
  • 74. 74 Detecting sensors at runtime ▹If a device doesn't have a pressure sensor, you can use the sensor framework to detect the absence of the pressure sensor at runtime and then disable the portion of your application's UI that displays pressure. ▹For example, the following code checks whether there's a pressure sensor on a device:
  • 75. 75 Example: Detecting sensors at runtime ▹For example, the following code checks whether there's a pressure sensor on a device: mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if (mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) != null){ // Success! There's a pressure sensor. } else { // Failure! No pressure sensor. }
  • 76. 76 Using Google Play filters to target specific sensor configurations ▹If you are publishing your application on Google Play you can use the <uses-feature> element in your manifest file to filter your application from devices that do not have the appropriate sensor configuration for your application. ▹The <uses-feature> element has several hardware descriptors that let you filter applications based on the presence of specific sensors. ▹The sensors you can list include: accelerometer, barometer, compass (geomagnetic field), gyroscope, light, and proximity.
  • 77. 77 Example: Google Play filters ▹For example, the following code checks whether there's a pressure sensor on a device: <uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" /> • If you add this element and descriptor to your application's manifest, users will see your application on Google Play only if their device has an accelerometer.
  • 78. 78 Using Google Play filters to target specific sensor configurations ▹You should set the descriptor to android:required="true" only if your application relies entirely on a specific sensor. ▹If your application uses a sensor for some functionality, but still runs without the sensor, you should list the sensor in the <uses-feature> element, but set the descriptor to android:required="false".
  • 79. 79 Using Google Play filters to target specific sensor configurations ▹This helps ensure that devices can install your app even if they do not have that particular sensor. ▹This is also a project management best practice that helps you keep track of the features your application uses. ▹Keep in mind, if your application uses a particular sensor, but still runs without the sensor, then you should detect the sensor at runtime and disable or enable application features as appropriate.
  • 81. 81 Categories of the Permissions Normal permissions do not directly risk the user's privacy. If your app lists a normal permission in its manifest, the system grants the permission automatically. ▹VIBRATE ▹BLUETOOTH ▹WIFI… ▹https://developer.android.com/guide/topics/permission s/normal-permissions.html Dangerous permissions can give the app access to the user's confidential data. If your app lists a normal permission in its manifest, the system grants the permission automatically. If you list a dangerous permission, the user has to explicitly give approval to your app. 81
  • 83. 83 Situations ▹If an app requests a dangerous permission listed in its manifest, and the app does not currently have any permissions in the permission group ▹For example, if an app requests the READ_CONTACTS permission, the system dialog box just says the app needs access to the device's contacts. ▹If the user grants approval, the system gives the app just the permission it requested.
  • 84. 84 Situations ▹If an app requests a dangerous permission listed in its manifest, and the app already has another dangerous permission in the same permission group, ▹For example, if an app had previously requested and been granted the READ_CONTACTS permission, ▹and it then requests WRITE_CONTACTS, the system immediately grants that permission.
  • 86. Contains Dangerous Permissions Android 6.0 (API level 23) or higher ▹ Request in Runtime ▹ The user can revoke the permissions at any time, so the app needs to check whether it has the permissions every time it runs. ▹Android 5.1 (API level 22) or lower ▹Request during installation ▹Once the user installs the app, the only way they can revoke the permission is by uninstalling the app.
  • 87. 87 Useful Information – check android version if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { } *Check user’s device android version
  • 88. 88 Useful Information – check permission if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION) ==PackageManager.PERMISSION_GRANTED) { *Check the status of the permission (Granted / not granted)
  • 89. 89 Useful Information – if denied, what should do //shouldShowRequestPermissionRationale will be true if the permission previously denied the request if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION )) {
  • 90. 90 Useful Information – the method called after user has made their decision //this method will be called after the uses has responed to the permission dialog box @Override public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the contacts-related task you need to do. } else { // permission denied, boo! Disable the // functionality that depends on this permission. } return; }
  • 91. 91 ▹Check the Lab assignment Android Runtime Permission
  • 92. Best Practices for Accessing and Using Sensors
  • 93. 93 Best Practices for Accessing and Using Sensors Unregister sensor listeners Don't test your code on the emulator Don't block the onSensorChanged() method Avoid using deprecated methods or sensor types Verify sensors before you use them Choose sensor delays carefully
  • 94. 94 Unregister sensor listeners ▹Be sure to unregister a sensor's listener when you are done using the sensor or when the sensor activity pauses. ▹If a sensor listener is registered and its activity is paused, the sensor will continue to acquire data and use battery resources unless you unregister the sensor. ▹onPause()
  • 95. 95 Don't test your code on the emulator ▹You currently can't test sensor code on the emulator because the emulator cannot emulate sensors. ▹You must test your sensor code on a physical device. ▹There are, however, sensor simulators that you can use to simulate sensor output.
  • 96. 96 Don't block the onSensorChanged() method ▹Sensor data can change at a high rate, which means the system may call the onSensorChanged(SensorEvent) method quite often. ▹As a best practice, you should do as little as possible within the onSensorChanged(SensorEvent) method so you don't block it. ▹If your application requires you to do any data filtering or reduction of sensor data, you should perform that work outside of the onSensorChanged(SensorEvent) method.
  • 97. 97 Avoid using deprecated methods or sensor types ▹Several methods and constants have been deprecated. ▹The TYPE_ORIENTATION sensor type has been deprecated. ▹To get orientation data you should use the getOrientation() method instead. ▹Likewise, the TYPE_TEMPERATURE sensor type has been deprecated. ▹You should use the TYPE_AMBIENT_TEMPERATURE sensor type instead on devices that are running Android 4.0.
  • 98. 98 Verify sensors before you use them ▹Always verify that a sensor exists on a device before you attempt to acquire data from it. ▹Don't assume that a sensor exists simply because it's a frequently-used sensor. ▹Device manufacturers are not required to provide any particular sensors in their devices.
  • 99. 99 Choose sensor delays carefully ▹When you register a sensor with the registerListener() method, be sure you choose a delivery rate that is suitable for your application or use-case. ▹Sensors can provide data at very high rates. ▹Allowing the system to send extra data that you don't need wastes system resources and uses battery power.
  • 101. 101 Location Services ▹Android gives your applications access to the location services supported by the device through classes in the android.location package ▹The central component of the location framework is the LocationManager system service, which provides APIs to determine location and bearing of the underlying device (if available).
  • 102. 102 Location Services ▹As with other system services, you do not instantiate a LocationManager directly. ▹You request an instance from the system by calling getSystemService(Context.LOCATION_SERVICE). ▹The method returns a handle to a new LocationManager instance.
  • 103. 103 Location Services ▹Once your application has a LocationManager, your application is able to do three things: ▸Query for the list of all LocationProviders for the last known user location. ▸Register/unregister for periodic updates of the user's current location from a location provider (specified either by criteria or name). ▸Register/unregister for a given Intent to be fired if the device comes within a given proximity (specified by radius in meters) of a given lat/long.
  • 104. 104 Challenges in Determining User Location ▹Can contain errors and be inaccurate. ▹Multitude of location sources ▸GPS, Cell-ID, and Wi-Fi can each provide a clue to users location. ▸Determining which to use and trust is a matter of trade-offs in accuracy, speed, and battery-efficiency. ▹User movement ▸Because the user location changes, you must account for movement by re-estimating user location every so often. ▹Varying accuracy ▸Location estimates coming from each location source are not consistent in their accuracy. ▸A location obtained 10 seconds ago from one source might be more accurate than the newest location from another or same source.
  • 105. 105 Requesting Location Updates ▹Getting user location in Android works by means of callback. ▹You indicate that you'd like to receive location updates from the LocationManager ("Location Manager") by calling requestLocationUpdates(), passing it a LocationListener. ▹Your LocationListener must implement several callback methods that the Location Manager calls when the user location changes or when the status of the service changes.
  • 106. 106 // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. makeUseOfNewLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; // Register the listener with the Location Manager to receive location updates locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 5000, 5, locationListener);
  • 107. 107 Requesting Location Updates ▹onLocationChanged(Location location) ▸Called when the location has changed. ▹onProviderEnabled(String provider) ▸Called when the provider is enabled by the user. ▹onProviderDisabled(String provider) ▸Called when the provider is disabled by the user. ▸If requestLocationUpdates is called on an already disabled provider, this method is called immediately
  • 108. 108 Requesting Location Updates ▹onStatusChanged(String provider, int status, Bundle extras) ▸Called when the provider status changes. ▸This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability. ▸OUT_OF_SERVICE if the provider is out of service, and this is not expected to change in the near future; ▸TEMPORARILY_UNAVAILABLE if the provider is temporarily unavailable but is expected to be available shortly; ▸AVAILABLE if the provider is currently available.
  • 109. 109 Requesting User Permissions ▹If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request only the ACCESS_FINE_LOCATION permission, because it includes permission for both providers. ▹Permission for ACCESS_COARSE_LOCATION includes permission only for NETWORK_PROVIDER. <manifest ... > <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> ... </manifest>
  • 110. 110 Requesting Location Updates ▹The first parameter in requestLocationUpdates() is the type of location provider to use ▸Network Location Provider ▸GPS Provider ▹You can control the frequency at which your listener receives updates with the second and third parameter ▸the second is the minimum time interval between notifications ▸the third is the minimum change in distance between notifications ▸setting both to zero requests location notifications as frequently as possible. The last parameter is your LocationListener, which receives callbacks for location updates.
  • 111. 111 Could you answer it? ▹Android has classify the sensor into three categories. What categories it is and explain about it. ▹Give three example of the sensors and describe the usage. ▹What is the best practices for accessing and Using Sensors in term of the programming aspect?