Android Sensors Mobile Application Development Selected Topics CPIT
Android Sensors Mobile Application Development Selected Topics – CPIT 490 09 -Jun-21
Objective n Working in Background n Sensor Manager n Sensor Types n Examples 2
Android Sensors n n n n n MIC Camera Temperature Location (GPS or Network) Orientation Accelerometer Proximity Pressure Light 3
Android. hardware Package n n n n n Support for Hardware classes with some interfaces Camera: used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. Camera. Info: Information about a camera Camera. Parameters: Camera service settings. Camera. Size: Image size (width and height dimensions). Geomagnetic. Field: Estimate magnetic field at a given point on Earth and compute the magnetic declination from true north. Sensor: Class representing a sensor. Sensor. Event: Represents a Sensor event and holds information such as sensor's type, time-stamp, accuracy and sensor's data. Sensor. Manager: Sensor. Manager lets you access the device's sensors. http: //developer. android. com/reference/android/hardware/packagesummary. html 4
Types of Sensors n n n Not every device has every kind of sensor Constants from Sensor class Sensor. TYPE_ACCELEROMETER n hardware n acceleration force in m/s 2 n x, y, z axis n includes gravity 5
Accelerometer Sensor n n Acceleration is defined as the rate of change of velocity. Accelerometers measure how quickly the speed of the device is changing in a given direction. Detect movement and corresponding speed’s rate of change. Accelerometers do not measure velocity 6
Types of Sensors n n Sensor. TYPE_AMBIENT_TEMPERATURE n hardware n "room" temperature in degrees Celsius n no such sensor on dev phones Sensor. TYPE_GRAVITY n software or hardware n just gravity n if phone at rest same as TYPE_ACCELEROMETER 7
Types of Sensors n n Sensor. TYPE_GYROSCOPE n hardware n measure device's rate of rotation in radians / second around 3 axis Sensor. TYPE_LIGHT n hardware n light level in lx, n lux is SI measure illuminance in luminous flux per unit area 8
Types of Sensors n n Sensor. TYPE_LINEAR_ACCELERATION n software or hardware n measure acceleration force applied to device in three axes n excluding the force of gravity Sensor. TYPE_MAGNETC_FIELD n hardware n ambient geomagnetic field in all three axes n u. T micro Teslas 9
Types of Sensors n n Sensor. TYPE_ORIENTATION [deprecated] n software n measure of degrees of rotation a device makes around all three axes Sensor. TYPE_PRESSURE n hardware n ambient air pressure in h. Pa or mbar n force per unit area n 1 Pascal = 1 Newton per square meter n hecto Pascals (100 Pascals) n milli bar - 1 mbar = 1 hecto Pascal 10
Orientation Sensor n n n Orientation Sensor is a combination of the magnetic field Sensors, which function as an electronic compass, and accelerometers, which determine the pitch and roll. Two alternatives for determining the device orientation. n Query the orientation Sensor directly n Derive the orientation using the accelerometers and magnetic field Sensors. x-axis (azimuth) 0/360 degrees is north, 90 east, 180 south, and 270 west y-axis (pitch) 0 flat on its back, -90 standing upright. z-axis (roll) 0 flat on its back, -90 is the screen facing left 11
Types of Sensors n n Sensor. TYPE_PROXIMITY n hardware n proximity of an object in cm relative to the view screen of a device n most just binary (see range, resolution) n typically used to determine if handset is being held to person's ear during a call Sensor. TYPE_RELATIVE_HUMIDITY n ambient humidity in percent ( 0 to 100) 12
Types of Sensors n n n Sensor. TYPE_ROTATION_VECTOR n hardware or software n orientation of device, three elements of the device's rotation vector Sensor. TYPE_TEMPERATURE n hardware n temperature of the device in degrees Celsius http: //developer. android. com/reference/android/hardware/Sensor. html 13
Availability of Sensors 14
Async Callbacks n n n Android’s sensors are controlled by external services and only send events when they choose to An app must register a callback to be notified of a sensor event Each sensor has a related XXXListener interface that your callback must implement e. g. Location. Listener 15
Sensing and Sensor Manager n n n Device specific Service. Manager provides access to Sensor Manager Service Use Context. get. System. Service(SENSOR_SERVICE) for access String service_name = Context. SENSOR_SERVICE; Sensor. Manager sensor. Manager = ( Sensor. Manager ) get. System. Service(service_name) n n Note that you should disable any sensors you don’t need, especially when activity paused. System will not disable automatically when screen turns off Battery will drain quickly otherwise. 16
Sensor. Manager’s Methods n n n Sensor get. Default. Sensor(int type) Use this method to get the default sensor for a given type List<Sensor> get. Sensor. List(int type) Use this method to get the list of available sensors of a certain type boolean register. Listener(Sensor. Event. Listener listener, Sensor sensor, int rate) Registers a Sensor. Event. Listener for the given sensor. void unregister. Listener(Sensor. Event. Listener listener, Sensor sensor) Unregisters a listener for the sensors with which it is registered. http: //developer. android. com/reference/android/hardware/Se nsor. Manager. html 17
Sensor’s Methods n n n public float get. Maximum. Range () - maximum range of the sensor in the sensor's unit. public int get. Min. Delay () - the minimum delay allowed between two events in microsecond or zero if this sensor only returns a value when the data it's measuring changes. public String get. Name () - name string of the sensor. public float get. Power () - the power in m. A used by this sensor while in use. public float get. Resolution () - resolution of the sensor in the sensor's unit. 18
get. Power() Methods n n The device’s battery has a 1500 m. A Under normal use, the battery lasts 10 hours. If we use orientation, rotation vector, & magnetic field sensors How long would it last now? 19
Checking for Sensors n n n Sensor default. Gyroscope = sensor. Manager. get. Default. Sensor (Sensor. TYPE_GYROSCOPE); //(Returns null if none) //Or, get a list of all sensors of a type: List<Sensor> pressure. Sensors = sensor. Manager. get. Sensor. List(Sensor. TYPE_PRESSURE); //Or, get a list of all sensors of a type: List<Sensor> all. Sensors = sensor. Manager. get. Sensor. List(Sensor. TYPE_ALL); 20
Listening for Sensors n n n n n final Sensor. Event. Listener my. Sensor. Event. Listener = new Sensor. Event. Listener() { public void on. Sensor. Changed(Sensor. Event sensor. Event) { // TODO Monitor Sensor changes. } public void on. Accuracy. Changed(Sensor sensor, int accuracy) { // TODO React to a change in Sensor accuracy. } } Accuracy: n Sensor. Manager. SENSOR_STATUS_ACCURACY_LOW n Sensor. Manager. SENSOR_STATUS_ACCURACY_MEDIUM n Sensor. Manager. SENSOR_STATUS_ACCURACY_HIGH n Sensor. Manager. SENSOR_STATUS_ACCURACY_UNRELIABL 21
Sensor. Event n Sensor. Event parameter in the on. Sensor. Changed method includes four properties used to describe a Sensor event: n sensor: The sensor that triggered the event. n accuracy: The accuracy of the Sensor when the event occurred. n values: A float array that contains the new value(s) detected. n timestamp: The time in nanosecond at which the event occurred. 22
Sensor Values 23
Register n n // Usually in on. Resume Sensor sensor = sensor. Manager. get. Default. Sensor(Sensor. TYPE_PROXIMITY); sensor. Manager. register. Listener(my. Sensor. Event. Listener, sensor, Sensor. Manager. SENSOR_DELAY_NORMAL); n n n // Usually in on. Pause sensor. Manager. unregister. Listener(my. Sensor. Event. Listener); n n Update Rate: n Sensor. Manager. SENSOR_DELAY_FASTEST n Sensor. Manager. SENSOR_DELAY_GAME n Sensor. Manager. SENSOR_DELAY_NORMAL n Sensor. Manager. SENSOR_DELAY_UI 24
Accelerometer, Compass, & Orientation n n Allow you to: n Determine the current device orientation n Monitor and track changes in orientation n Know which direction the user is facing n Monitor acceleration—changes in movement rate—in any direction Open possibilities for your applications: n Use these with a map, camera, and location-based services to create augmented reality interfaces. n Create user interface that adjust dynamically to suit device orientation. n Monitor rapid acceleration to detect if a device is dropped or thrown. n Measure movement or vibration (e. g. , locking application). n User interface controls that use physical gestures and movement. 25
Listener for Changes (Accel) n n n n public void setup. Sensor. Listener() { Sensor. Manager sm = (Sensor. Manager)get. System. Service(Context. SENSOR_SERVICE); int sensor. Type = Sensor. TYPE_ACCELEROMETER; sm. register. Listener(my. Sensor. Event. Listener, sm. get. Default. Sensor(sensor. Type), Sensor. Manager. SENSOR_DELAY_NORMAL); } final Sensor. Event. Listener my. Sensor. Event. Listener = new Sensor. Event. Listener() { public void on. Sensor. Changed(Sensor. Event sensor. Event) { if (sensor. Event. sensor. get. Type() == Sensor. TYPE_ACCELEROMETER) { float x. Axis_lateral. A = sensor. Event. values[0]; float y. Axis_longitudinal. A = sensor. Event. values[1]; float z. Axis_vertical. A = sensor. Event. values[2]; // TODO apply the acceleration changes to your application. } } }; 26
Accelerometer Data 27
Listener for Changes (Orientation) n n n n public void setup. Sensor. Listener() { Sensor. Manager sm = (Sensor. Manager)get. System. Service(Context. SENSOR_SERVICE); int sensor. Type = Sensor. TYPE_ORIENTATION; sm. register. Listener(my. Sensor. Event. Listener, sm. get. Default. Sensor(sensor. Type), Sensor. Manager. SENSOR_DELAY_NORMAL); } final Sensor. Event. Listener my. Sensor. Event. Listener = new Sensor. Event. Listener() { public void on. Sensor. Changed(Sensor. Event sensor. Event) { if (sensor. Event. sensor. get. Type() == Sensor. TYPE_ORIENTATION) { float heading. Angle = sensor. Event. values[0]; float pitch. Angle = sensor. Event. values[1]; float roll. Angle = sensor. Event. values[2]; // TODO apply the orientation changes to your application. } } }; 28
Controlling Vibration n n Vibration is an excellent way to provide haptic user feedback. Applications need the VIBRATE permission in application manifest: n n n n <uses-permission android: name="android. permission. VIBRATE"/> Example: String vibrator. Service = Context. VIBRATOR_SERVICE; Vibrator vibrator = (Vibrator)get. System. Service(vibrator. Service); long [] pattern = {1000, 2000, 4000, 8000, 16000 }; vibrator. vibrate(pattern, 0); // Execute vibration pattern. vibrator. vibrate(1000); // Vibrate for 1 second. 29
Sensors – Summary n n n Many types of sensors n Accelerometer, Ambient Temperature, Gravity, Gyroscope, Light, Linear Acceleration, Magnetic Field, Orientation, Pressure, Proximity, Relative Humidity, Rotation Vector, Temperature Need to invoke Sensor. Manager n Sensor. Manager m. Sensor. Manager = (Sensor. Manager) get. System. Service(Context. SENSOR_SERVICE); n m. Sensor. Manager. get. Default. Sensor(Sensor. TYPE_ACCELE ROMETER); Have a Sensor. Event. Listener n Allows you to monitor sensor events 30
Example 1. Displaying Accelerometer and Orientation Data n n n n Create an activity with accelerometer and orientation data. package com. exercise. Android. Sensor. List; import android. app. List. Activity; import android. content. Context; import android. hardware. Sensor. Manager; import android. os. Bundle; import android. widget. Array. Adapter; public class Sensor. Test extends Activity implements Sensor. Event. Listener { Sensor. Manager sensor. Manager = null ; //for accelerometer values Text. View output. X; Text. View output. Y; Text. View output. Z; //for orientation values Text. View output. X 2; Text. View output. Y 2; Text. View output. Z 2; 31
Example 1. Displaying Accelerometer and Orientation Data n n n n @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); sensor. Manager = (Sensor. Manager) get. System. Service(SENSOR_SERVICE); set. Content. View(R. layout. main); //just some textviews, for data output. X = (Text. View) find. View. By. Id(R. id. Text. View 01); output. Y = (Text. View) find. View. By. Id(R. id. Text. View 02); output. Z = (Text. View) find. View. By. Id(R. id. Text. View 03); output. X 2 = (Text. View) find. View. By. Id(R. id. Text. View 04); output. Y 2 = (Text. View) find. View. By. Id(R. id. Text. View 05); output. Z 2 = (Text. View) find. View. By. Id(R. id. Text. View 06); } 32
Example 1. Displaying Accelerometer and Orientation Data n n n n @Override protected void on. Resume() { super. on. Resume(); sensor. Manager. register. Listener(this, sensor. Manager. get. Default. Sensor(Sensor. TYPE_ACCELEROMETER), sensor. Manager. SENSOR_DELAY_GAME); sensor. Manager. register. Listener(this, sensor. Manager. get. Default. Sensor(Sensor. TYPE_ORIENTATION), sensor. Manager. SENSOR_DELAY_GAME); } @Override protected void on. Stop() { super. on. Stop(); sensor. Manager. unregister. Listener(this, sensor. Manager. get. Default. Sensor(Sensor. TYPE_ACCELEROMETER)); sensor. Manager. unregister. Listener(this, sensor. Manager. get. Default. Sensor(Sensor. TYPE_ORIENTATION)); } 33
Example 1. Displaying Accelerometer and Orientation Data n n n n n public void on. Sensor. Changed(Sensor. Event event) { synchronized (this) { switch (event. sensor. get. Type()){ case Sensor. TYPE_ACCELEROMETER: output. X. set. Text("x: "+ Float. to. String(event. values[0])); output. Y. set. Text("y: "+ Float. to. String(event. values[1])); output. Z. set. Text("z: "+ Float. to. String(event. values[2])); break ; case Sensor. TYPE_ORIENTATION: output. X 2. set. Text("x: "+ Float. to. String(event. values[0])); output. Y 2. set. Text("y: "+ Float. to. String(event. values[1])); output. Z 2. set. Text("z: "+ Float. to. String(event. values[2])); break ; } } } @Override public void on. Accuracy. Changed( Sensor sensor, int accuracy) {} } 34
Example 2. Creating a G-Forcemeter n n n n Create a simple device to measure g-force using the accelerometers to determine the current force being exerted on the device. Forceometer Activity & Layout (main. xml) <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout xmlns: android="http: //schemas. android. com/apk/res/android" android: orientation="vertical“ android: layout_width="fill_parent" android: layout_height="fill_parent"> <Text. View android: id="@+id/acceleration“ android: gravity="center" android: layout_width="fill_parent“ android: layout_height="wrap_content" android: text. Style="bold“ android: text. Size="32 sp" android: text="CENTER“ android: editable="false" android: single. Line="true“ android: layout_margin="10 px“ /> <Text. View android: id="@+id/max. Acceleration“ android: gravity="center" android: layout_width="fill_parent“ android: layout_height="wrap_content" android: text. Style="bold“ android: text. Size="40 sp" android: text="CENTER“ android: editable="false" android: single. Line="true“ android: layout_margin="10 px“ /> </Linear. Layout> 35
Example 2. Creating a G-Forcemeter n n n Within Forceometer Activity class, create instance variables Sensor. Manager sensor. Manager; Text. View acceleration. Text. View; Text. View max. Acceleration. Text. View; float current. Acceleration = 0; float max. Acceleration = 0; Within Forceometer Activity class, create a new Sensor. Event. Listener implementation private final Sensor. Event. Listener sensor. Event. Listener = new Sensor. Event. Listener() { double calibration = Sensor. Manager. STANDARD_GRAVITY; public void on. Accuracy. Changed(Sensor sensor, int accuracy) { } public void on. Sensor. Changed(Sensor. Event event) { double x = event. values[0]; double y = event. values[1]; double z = event. values[2]; double a = Math. round(Math. sqrt(Math. pow(x, 2) + Math. pow(y, 2) + Math. pow(z, 2))); current. Acceleration = Math. abs((float)(a-calibration)); if (current. Acceleration > max. Acceleration) max. Acceleration = current. Acceleration; } }; 36
Example 2. Creating a G-Forcemeter n n n n Update the on. Create method to register your new Listener for accelerometer updates using the Sensor. Manager. @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main); acceleration. Text. View = (Text. View)find. View. By. Id(R. id. acceleration); max. Acceleration. Text. View = (Text. View)find. View. By. Id(R. id. max. Acceleration); sensor. Manager = (Sensor. Manager)get. System. Service(Context. SENSOR_SERVICE); Sensor accelerometer = sensor. Manager. get. Default. Sensor(Sensor. TYPE_ACCELEROMETER); sensor. Manager. register. Listener(sensor. Event. Listener, accelerometer, Sensor. Manager. SENSOR_DELAY_FASTEST); } 37
Example 2. Creating a G-Forcemeter n n n n Create a new update. GUI method that synchronizes with the GUI thread based on a Timer before updating the Text Views private void update. GUI() { run. On. Ui. Thread(new Runnable() { public void run() { String current. G = current. Acceleration/Sensor. Manager. STANDARD_GRAVITY + "Gs"; acceleration. Text. View. set. Text(current. G); acceleration. Text. View. invalidate(); String max. G = max. Acceleration/Sensor. Manager. STANDARD_GRAVITY + "Gs"; max. Acceleration. Text. View. set. Text(max. G); max. Acceleration. Text. View. invalidate(); } }); }; 38
Example 2. Creating a G-Forcemeter n n n n Update the on. Create method to start a timer that’s used to update the GUI every 100 ms: @Override public void on. Create(Bundle saved. Instance. State) { super. on. Create(saved. Instance. State); set. Content. View(R. layout. main); acceleration. Text. View = (Text. View)find. View. By. Id(R. id. acceleration); max. Acceleration. Text. View = (Text. View)find. View. By. Id(R. id. max. Acceleration); sensor. Manager = (Sensor. Manager)get. System. Service(Context. SENSOR_SERVICE); Sensor accelerometer = sensor. Manager. get. Default. Sensor(Sensor. TYPE_ACCELEROMETER); sensor. Manager. register. Listener(sensor. Event. Listener, accelerometer, Sensor. Manager. SENSOR_DELAY_FASTEST); Timer update. Timer = new Timer("g. Force. Update"); update. Timer. schedule. At. Fixed. Rate(new Timer. Task() { public void run() { update. GUI(); } }, 0, 100); } 39
Example 3. Compass App n n n n package com. example. android. apis. graphics; import android. content. Context; import android. graphics. *; import android. hardware. Sensor. Event; import android. hardware. Sensor. Event. Listener; import android. hardware. Sensor. Manager; import android. os. Bundle; import android. util. Config; import android. util. Log; import android. view. View; public class Compass extends Graphics. Activity { private static final String TAG = "Compass"; private Sensor. Manager m. Sensor. Manager; private Sensor m. Sensor; private Sample. View m. View; private float [] m. Values; 40
Example 3. Compass App n n n private final Sensor. Event. Listener m. Listener = new Sensor. Event. Listener () { public void on. Sensor. Changed(Sensor. Event event) { if (Config. DEBUG) Log. d (TAG , "sensor. Changed (" + event. values [0] + ", " + event. values [1] + ", " + event. values [ 2 ] + ")" ); m. Values = event. values ; if (m. View!= null) { m. View. invalidate (); } } public void on. Accuracy. Changed (Sensor sensor , int accuracy ) { } }; @Override protected void on. Create (Bundle icicle) { super. on. Create ( icicle ); m. Sensor. Manager = (Sensor. Manager) get. System. Service(Context. SENSOR_SERVICE); m. Sensor = m. Sensor. Manager. get. Default. Sensor (Sensor. TYPE_ORIENTATION); m. View = new Sample. View (this); set. Content. View (m. View); } 41
Example 3. Compass App n n n n @Override protected void on. Resume () { if (Config. DEBUG) Log. d(TAG, "on. Resume"); super. on. Resume(); m. Sensor. Manager. register. Listener(m. Listener, m. Sensor, Sensor. Manager. SENSOR_DELAY_GAME); } @Override protected void on. Stop() { if (Config. DEBUG) Log. d(TAG, "on. Stop"); m. Sensor. Manager. unregister. Listener(m. Listener); super. on. Stop(); } private class Sample. View extends View { private Paint m. Paint = new Paint(); private Path m. Path = new Path(); private boolean m. Animate ; public Sample. View(Context context) { super(context); 42
Example 3. Compass App n n n n // Construct a wedge-shaped path m. Path. move. To(0, - 50); m. Path. line. To(-20, 60); m. Path. line. To(0, 50); m. Path. line. To(20, 60); m. Path. close(); } @Override protected void on. Draw(Canvas canvas) { Paint paint = m. Paint; canvas. draw. Color(Color. WHITE); paint. set. Anti. Alias(true); paint. set. Color(Color. BLACK); paint. set. Style(Paint. Style. FILL); int w = canvas. get. Width(); int h = canvas. get. Height(); int cx = w / 2; int cy = h / 2 ; 43
Example 3. Compass App n n n n canvas. translate(cx, cy); if (m. Values != null) {canvas. rotate(- m. Values[0]); } canvas. draw. Path(m. Path, m. Paint); } @Override protected void on. Attached. To. Window () { m. Animate = true; if (Config. DEBUG) Log. d(TAG, "on. Attached. To. Window. m. Animate=" + m. Animate); super. on. Attached. To. Window(); } @Override protected void on. Detached. From. Window () { m. Animate = false; if (Config. DEBUG) Log. d(TAG, "on. Detached. From. Window. m. Animate=" + m. Animate); super. on. Detached. From. Window(); } } } 44
References n App Development for Smart Devices n http: //www. cs. odu. edu/~cs 495/ 45
- Slides: 45