Android--sensor sensor

Source: Internet
Author: User

Objective

Android provides support for device sensors, and as long as the Android device's hardware provides these sensors, Android apps can access the device's external conditions through sensors, including the phone's running status, the current orientation, and so on. The Android system also provides drivers to manage these sensor hardware, which can be used by listeners to monitor changes in the external environment perceived by the sensor hardware. This blog mainly explains how to use the sensor under Android, and finally a simple demo.

Developing sensor application Steps

Developing an application for sensor support is simple, as long as the developer assigns a listener to the sensor to be monitored in the Sensor manager Sensormanager, and when the external environment changes, the Android system obtains data from the external environment via the sensor. The data is then passed to the listener's listener callback method. The steps are as follows:

    1. Gets the sensor service.
    2. Gets the sensor of the specified type from the sensor service.
    3. Add a sensor's listener using the sensor service.
    4. After you are done, log off the sensor's listener.

Get sensor service

There are many system-level services built into Android that are used for developers, and sensors are managed through sensor services, Sensormanager. Instead, get the system service in the Android component, use the method Context.getsystemservice (String), and its parameters are defined in the context in static final mode. The acquisition of Sensormanager requires an incoming context.sensor_service.

1         Manager= (Sensormanager) Getsystemservice (Sensor_service);

Obtaining a sensor of the specified type from the sensor service

The sensor service manages all the sensors on the device, so you need to specify the sensor to be monitored. To get the sensor to be monitored, you need to use the Sensormanager.getdefaultsensor () method, and its full signature is as follows:

    Sensor getdefaultsensor (int type)

Sensors in Android require sensor support, and the Getdefaultsensor () method obtains the corresponding sensor from the specified type parameter. The type parameter is defined in a static final way inside the sensor, allowing developers to use it directly. The following describes the type of several common sensors:

    • Sensor.type_orientation: direction sensor.
    • Sensor.type_accelerometer: Gravity sensor.
    • Sensor.type_light: Light sensor.
    • Sensor.type_magnetic_field: magnetic field sensor.

To add a sensor's listener using the sensor service

Once you have obtained the Sensormanager and sensor objects, you can register the listener for their sensor. Registering the listener for the sensor, using the Sensormanager.registerlistener () method, has multiple overloaded methods, but some methods are obsolete, and the signature of a common method is provided below:

Boolean Registerlistener (Sensoreventlistener listener,sensor sensor,int rateus)

The meaning of the above method parameter: Listener: Sensor's listener, sensors: sensor to be monitored, rateus: sample rate of the sensor.

As can be seen from the Registerlistener () method, it needs to pass a Sensoreventlistener object, which is the sensor listener, which contains two methods that need to be implemented by the developer:

    • void onaccuracychanged (sensor sensor,int accuracy): callback when sensor accuracy is changed.
    • void Onsensorchanged (Sensorevent event): Callback when the sensor-induced value changes.

For the above two methods, the accuracy of the sensor is generally not changed, so we generally the main amount of code in onsensorchanged ().

The Registerlistener () method also has a Rateus parameter, which indicates the sampling rate of the monitor sensor change, which is the frequency at which the value is obtained from the sensor. It is defined in the form of static final defined in Sensormanager, which is convenient for us to use directly, and defines several options as follows:

    • Sensormanager.sensor_delay_fastest: Fastest, least latency.
    • Sensormanager.sensor_delay_game: The frequency for the game.
    • Sensormanager.sensor_delay_normal: Normal frequency.
    • SENSORMANAGER.SENSOR_DELAY_UI: The frequency of UI changes for normal user interfaces.

Android provides us with these sample rate parameters that are convenient for us to use. But for the choice of that sampling rate, not the faster the better, to refer to the actual development of the application situation, the larger the sampling rate, the more resources, including the power, CPU, etc., so to choose according to the actual situation, after all, the powerful application, if the device can reduce the battery life, it will be users do not like.

After use, log off the sensor's listener

After the sensor is used, the listener needs to be unregistered because the sensor's listener does not release the resource itself due to the end of the application, requiring the developer to log out at the appropriate time. The logoff sensor listener uses the Sensormanager.unregisterlistener () method, and, like the listener's registration method, it has several overloaded methods, but some are deprecated, and a common full signature is described below:

void Unregisterlistener (Sensoreventlistener listener)

Compass Demo

The steps and specifics of using the sensor in the application are explained above, and a simple demo is shown below to illustrate how to use the sensor. Monitor the direction sensor in the demo to make its angle change to the direction of operation, simulating the effect of a compass.

Rewrite the listener's onsensorchanged () method, where event gets the parameters of the current listener event, you can use values[0] to get the angle that the sensor is sensing to the current direction. Referring to the official documentation, it can be seen that it represents a 360° angle, the rules are: 0=north, 90=east, 180=south, 270=west.

The following direct code, the comments are all, no longer repeat, will use the content of the tweened animation, to tween the animation does not know the friend, you can see another blog: Android--tween tween animation. Another thing to note is that the sensor's demo needs to be tested on the real machine because the sensor hardware does not exist on the emulator.

1  PackageCom.example.sensormanagerdemo;2 3 ImportAndroid.hardware.Sensor;4 Importandroid.hardware.SensorEvent;5 ImportAndroid.hardware.SensorEventListener;6 ImportAndroid.hardware.SensorManager;7 ImportAndroid.os.Bundle;8 Importandroid.view.animation.Animation;9 Importandroid.view.animation.RotateAnimation;Ten ImportAndroid.widget.ImageView; One Importandroid.app.Activity; A  -  Public classMainactivityextendsActivity { -     PrivateImageView Iv_compass; the     PrivateSensormanager Manager; -     Private floatStartdegree =0f; -  - @Override +     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); + Setcontentview (r.layout.activity_main); A  atIv_compass =(ImageView) Findviewbyid (r.id.iv_compass); -         //Get the sensor manager -Manager =(Sensormanager) Getsystemservice (sensor_service); -  -     } -  in @Override -     protected voidOnresume () { to         Super. Onresume (); +         //registering listeners for direction sensors - Manager.registerlistener (Listener, the Manager.getdefaultsensor (sensor.type_orientation), * sensormanager.sensor_delay_ui); $ Panax Notoginseng     } -  the     PrivateSensoreventlistener listener =NewSensoreventlistener () { +  A @Override the          Public voidonsensorchanged (Sensorevent event) { +             if(Event.sensor.getType () = =sensor.type_orientation) { -                 //gets the angle that the current sensor obtains $                 floatdegree =-event.values[0]; $                 //rotates from the last angle by the motion tween rotation angle -Rotateanimation RA =Newrotateanimation (startdegree, Degree, -Animation.relative_to_self, 0.5f, theAnimation.relative_to_self, 0.5f); -Ra.setduration (200);Wuyi iv_compass.startanimation (RA); the                 //record the angle after the current rotation -Startdegree =degree; Wu             } -         } About  $ @Override -          Public voidOnaccuracychanged (sensor sensor,intaccuracy) { -  -         } A     }; +  the @Override -     protected voidOnStop () { $         //to unregister a listener for a sensor the Manager.unregisterlistener (listener); the         Super. OnStop (); the     } the}

Effect Show:

SOURCE download

Summarize

This blog explains how to use the sensor under Android, just a brief introduction, for the sensor to obtain the values, are in the event.values array, but the different sensors get different values, specific situation specific analysis, here is no longer discussed in depth.

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.