Detailed Android sensor Development complete parsing _android

Source: Internet
Author: User

Well, thanks to the recent development requirements for smart hardware, so the recent days to share the blog is roughly linked to intelligent hardware, like a piece of Bluetooth sharing, I believe that many readers have seen, then today I bring you the knowledge of the Android sensor introduction and use of methods, for the use of sensors , different versions of the Android phone may have larger hardware differences, but same, this article will be through the most common sensors, the infiltration of the church how to use these sensors, lead us to complete this part of the advanced improvement. Let each Android developer be comfortable with the use of the sensor.

Three types of 1.Android sensors

The Android sensor is broadly divided into three types of sensors: Motion (Motion) sensor, Environment (environmental) sensor, Position (Position) sensor.

(1) Motion sensor

This type of sensor measures the acceleration and rotation angles on three axes (x, Y, z). includes several sensors as follows:

Acceleration (accelerometer) sensor, gravity (gravity) sensor, gyroscope (gyroscope) sensor, rotation vector (rotational vector) sensor
Let's look at the coordinates of the sensor world:

The coordinate system of the sensor world

is not already feeling a bit.

(2) Environmental sensors

Such sensors can measure parameters in different environments, such as ambient air temperature and pressure, light intensity and humidity. includes several sensors as follows:

Humidity (barometer) sensor, light (photometer) sensor, temperature (thermometer) sensor

(3) Position sensor

This type of sensor can measure the physical location of the device. includes several sensors as follows:

Directional (orientation) sensors, magnetic (magnetometer) sensors

Once we get to work on the sensor's programming, we'll look at the sensor framework that Android provides for us (the Android Sensor framework, ASF for short).

2.Android Sensor Frame

The Android SDK provides ASF for us to access the sensors built into the current Android device. ASF provides a number of classes and interfaces to help us accomplish a variety of sensor-related tasks. For example:

1 determine which sensors are currently built into the Android device.

2 Determine the technical specifications of a sensor.

3 Obtain the data returned by the sensor, and define the accuracy of the sensor return data.

4 registers and logs out sensor event listeners, which are used to monitor changes in the sensor, and typically data that is returned from the sensor needs to be performed using these listeners.

ASF allows us to access a number of sensor types, some of which are hardware-based sensors, and some are software-based sensors. hardware-based sensors are embedded directly into the Android device in a chip form, and these sensors get data directly from the external environment. software-based sensors are not real hardware chips, and the data returned by software-based sensors is essentially based on hardware-based sensors, which are typically processed two of times. So software-based sensors can also be called virtual or synthetic (synthetic) sensors.

Android has abstracted sensors for each device, where the Sensormanger class is used to control sensors, sensor to describe specific sensors, and sensoreventlistener to monitor changes in sensor values.

(1) Sensormanager class

The instance used to create the sensor service. This class provides a number of methods for accessing and enumerating sensors, registering and unregistering sensor listeners. It also provides constants related to sensor accuracy, scanning frequency, and calibration.

(2) Sensor class

The sensor class provides us with some methods for obtaining sensor technical parameters. such as version, type, manufacturer, etc. For example, the type types of all sensors are as follows:
Note: 1-8 is a hardware sensor, 9 is a software sensor, where the data from the direction sensor comes from gravity and magnetic field sensors, and 10-12 is hardware or software sensors.

Serial Number sensor type constants defined in the Sensor class
1 Acceleration Sensor Type_accelerometer
2 Temperature sensor Type_ambient_temperature
3 Gyro sensor Type_gyroscope
4 Light sensor Type_light
5 magnetic field Sensor Type_magnetic_field
6 Pressure Transducer Type_pressure
7 Proximity sensor Type_proximity
8 Humidity sensor Type_relative_humidity
9 Directional sensor Type_orientation
10 Gravity sensor Type_gravity
11 Linear acceleration Sensor Type_linear_acceleration
12 Rotation vector sensor Type_rotation_vector

(3) Sensorevent class

The system uses this class to create a sensor event object. This object can provide information about the sensor event. The Sensor event object includes information about the original sensor postback data, the sensor type, the precision of the data, and when the event was triggered.

(4) Sensoreventlistener interface

The interface contains two callback methods, which are called when the sensor's return value or precision changes.

/**
 * Sensor accuracy Change callback
/@Override public
void onaccuracychanged (Sensor Sensor, int accuracy) {
}
/**
 * Callback when sensor data changes
/@Override public
void Onsensorchanged (Sensorevent event) {
}

When we get here, we can work on sensor development.

3. Obtain the Sensor technical parameter

Down we'll write code to get the sensor technical parameters for our phone.

TextView tvsensors = (TextView) Findviewbyid (r.id.tv_sensors);
Get sensor Sensormanager Object
sensormanager Sensormanager = (sensormanager) getsystemservice (sensor_service);
list<sensor> sensors = sensormanager.getsensorlist (sensor.type_all);
for (Sensor sensor:sensors) {
  tvsensors.append (sensor.getname () + "\ n");
}

Run it first to see the effect:

Looks like my cell phone sensor still a lot of, haha. Note that the entity machine test must be used here.

Let's take a look at the composition and usage of the motion sensor, environment sensor and position sensor respectively.

4. Motion sensor's composition and the use method

All motion sensors return three floating-point values (via an array of length 3), but for different sensors, these three are just different meanings. For example, for an acceleration sensor, data from three axes is returned. For gyro sensors, the rotational angular speed of the three axes is returned.

Note: The motion sensor itself is not normally used to monitor the location of the device, and the location of the device needs to be monitored by other types of sensors, such as a magnetic field sensor.

(1) Acceleration sensor

Acceleration sensors need to be used in conjunction with gravity sensors to reduce acceleration by gravity. First you need to implement the Sensoreventlistener interface, add a callback method, then get the Sensor Sensormanager object, register the sensor, and then we can monitor the sensor changes. The sample code is as follows:

public class Sensoractivity extends Appcompatactivity implements Sensoreventlistener {private TextView Tvaccelerometer
  ;
  Private Sensormanager Msensormanager;
  Private float[] Gravity = new float[3];
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_sensor);
    Tvaccelerometer = (TextView) Findviewbyid (r.id.tv_accelerometer);
  Get Sensor Sensormanager Object Msensormanager = (Sensormanager) getsystemservice (Sensor_service); /** * Callback/@Override public void onaccuracychanged (Sensor Sensor, int accuracy) {}/** * sensing when sensor accuracy changes Callback/@Override public void onsensorchanged (Sensorevent event) {//Judge Sensor class switch (event.sensor.getTy) when data changes
        PE ()) {case Sensor.type_accelerometer://Acceleration Sensor final float alpha = (float) 0.8;
        GRAVITY[0] = Alpha * Gravity[0] + (1-alpha) * event.values[0]; GRAVITY[1] = Alpha * Gravity[1] + (1-alpha) * EVENT.VALUES[1];

        GRAVITY[2] = Alpha * gravity[2] + (1-alpha) * event.values[2]; String Accelerometer = "acceleration sensor \ n" + "x:" + (Event.values[0]-gravity[0]) + "\ n" + "Y:" + (EVENT.V
        ALUES[1]-gravity[1]) + "\ n" + "Z:" + (Event.values[2]-gravity[2]);
        Tvaccelerometer.settext (accelerometer);
      The gravitational acceleration 9.81m/s^2, only under the action of gravity, the free falling acceleration break;
        Case sensor.type_gravity://gravity sensor gravity[0] = event.values[0];//Unit m/s^2 gravity[1] = event.values[1];
        GRAVITY[2] = event.values[2];
      Break
    Default:break;
    }/** * Interface to get focus, button can be clicked when callback/protected void Onresume () {super.onresume (); Register Acceleration Sensor Msensormanager.registerlistener (This, msensormanager.getdefaultsensor (sensor.type_accelerometer),// Sensor type type SENSORMANAGER.SENSOR_DELAY_UI)//Acquisition frequency//Registration Gravity Sensor Msensormanager.registerlistener (this, MS Ensormanager.getdefaultsensor (sensor.type_gravity), sensormanager.sensor_delay_fastest);
    /** * Suspend activity, interface gain focus, button can be clicked when callback/@Override protected void OnPause () {super.onpause ();
  Msensormanager.unregisterlistener (this);

 }

}

We put the phone level face up on the table and look at the effect chart:

We can see positive and negative values, so what's the positive? What is a negative value?

The device is pushed along the x-axis, and the x-axis acceleration is positive.

The device pushes along the y-axis, and the y-axis acceleration is positive.

If you push along the z-axis, the phone is positioned relative to the table horizontally upward, and the z-axis acceleration is positive. Driven by a m/s^2 acceleration at the bottom toward the top, the z-axis has an acceleration of a + 9.81, so if the actual acceleration is calculated (offsetting the gravitational acceleration), it needs to be reduced by 9.81.

5. The composition of the position sensor and the use method

Android provides a magnetic field sensor and a directional sensor to determine the location of the device, as well as a sensor (proximity sensor) to measure the distance from the front of the device to a nearby object.

Proximity sensors are common in mobile phones. When you answer the phone, the screen is the adjacent sensor used. The directional sensor is software-based, and the return data of the sensor comes from the accelerometer and the magnetic field sensor.

Position sensors are useful for determining the physical location of a device in the real world. For example, a magnetic field sensor and an accelerometer can be combined to measure the position of the device relative to the geomagnetic North Pole, and a directional sensor can be used to determine the position of the current device relative to its own reference frame.

Both the magnetic field sensor and the directional sensor return a value of 3 values (sensorevent.values), while the proximity sensor returns only 1 values.

Let's take a specific look at their return values:

Direction sensor:

    • Sensorevent.values[0]: The angle of rotation around the z axis. If the y-axis (the direction of the cell phone is normal) is pointing north, the value is 0, if the y-axis points south, the 180,y axis points to the east, the value is 90, and if the y-axis points to the West, the value is 270.
    • SENSOREVENT.VALUES[1]: The degree of rotation around the x axis. When the positive direction of the y-axis is directed from the z-axis, the value is positive. Conversely, a negative value. The value changes between 180 and 180.
    • SENSOREVENT.VALUES[2]: The degree of rotation around the y axis. When the positive direction of the x-axis is directed from the z-axis, the value is positive. Conversely, a negative value. The value changes between 180 and 180.

magnetic field Sensor:

    • Sensorevent.values[0]: Magnetic force along the x-axis (Μt,millitesla)
    • SENSOREVENT.VALUES[1]: Magnetic force along the y-axis (Μt,millitesla)
    • SENSOREVENT.VALUES[2]: Magnetic force along the y-axis (Μt,millitesla)

Proximity sensor:

SENSOREVENT.VALUES[0]: Cell phone frontal distance from proximity to physical distance (CM)

(1) Proximity sensor

Here the proximity sensor works as a sample project, and other sensors are similar.

public class Sensoractivity extends Appcompatactivity implements Sensoreventlistener {private TextView tvproximity;
  Private Sensormanager Msensormanager;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_motion_sensor);
    Tvproximity = (TextView) Findviewbyid (r.id.tv_proximity);
  Get Sensor Sensormanager Object Msensormanager = (Sensormanager) getsystemservice (Sensor_service); /** * Callback/@Override public void onaccuracychanged (Sensor Sensor, int accuracy) {}/** * sensing when sensor accuracy changes Callback/@Override public void onsensorchanged (Sensorevent event) {//Judge Sensor class switch (event.sensor.getTy) when data changes
        PE ()) {case sensor.type_proximity://Proximity sensor Tvproximity.settext (string.valueof (event.values[0));
      Break
    Default:break;
    }/** * Interface to get focus, button can be clicked when callback/protected void Onresume () {super.onresume (); Register Proximity Sensor MsenSormanager.registerlistener (This, msensormanager.getdefaultsensor (sensor.type_proximity), SensorManager.SE
  NSOR_DELAY_UI);
    /** * Suspend activity, interface gain focus, button can be clicked when callback/@Override protected void OnPause () {super.onpause ();
  Msensormanager.unregisterlistener (this);

 }

}

Run the program, I interrupted the proximity of the sensor, look at the effect of the picture:

0.0 is when I block the value of the proximity sensor, 8.0 is the value when I move my hand away.

Here we look at a comparison of the sensor, and nature is closely related.

6. Environment sensor composition and use method

Android provides sensors for detecting different external environments. For example, you can detect ambient air humidity, light, air pressure and temperature, these sensors are hardware-based sensors. In addition to light sensors, other sensors are rare in common Android devices. So if you are using an ambient sensor, it is best to run the sensor that the current Android device supports.

(1) The return value of the environment sensor

Most motion sensors and position sensors return multiple values, and all ambient sensors return only one value:

sensor Type value return value units
Temperature sensor Type_ambient_temperature Event.values[0] °c
Pressure Transducer Type_pressure Event.values[0] Hpa
Light sensor Type_light Event.values[0] Lx
Humidity sensor Type_relative_humidity Event.values[0] RH (%)

Note: The values returned by the ambient sensor are rarely disturbed by the noise, and the action and position sensors often need to eliminate the effects of the noise. For example, the acceleration sensor eliminates the effect of gravity on its return value.

(2) light sensor return data

The strongest light intensity (estimated only in the desert area to reach this value) public
static final float Light_sunlight_max = 120000.0f;
The intensity of direct sunlight in cloudless skies public
static final float light_sunlight = 110000.0f;
There is sunshine, but the intensity of some rays is offset by clouds public
static final float light_shade = 20000.0f;
Cloudy light intensity public  
static final float light_overcast = 10000.0f;
The light intensity of the sun just Rising (sunrise) is public
static final float light_sunrise = 400.0f;
In rainy days, the intensity of light when there is no sun public
static final float light_cloudy = 100.0f;
The intensity of light at night when there is a moon public
static final float light_fullmoon = 0.25f;
At night there is no moon when the intensity of light (of course, there can be no street lamp, is dark) public
static final float light_no_moon = 0.001f;

The use of environmental sensors and motion, position sensors are similar, in the time no longer repeat.

I believe that through this study, everyone's development standards will have a certain improvement, and everyone's improvement is my most gratifying things. We also hope that we can support the cloud-dwelling community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.