Today's smartphones are equipped with a wide variety of sensors, this article describes the sensor development interface provided by the Android SDK, and shows how to use these interfaces with a simple example.
Andriod SDK Sensor related classes
The Android SDK provides sensor-related classes (located in the Android.hardware package):
Sensor: A class of sensors that holds information such as sensor name, manufacturer, version, accuracy, etc.;
Sensorevent: Indicates the sensor event, it can save the sensor value, sensor type, timestamp and other information;
Sensoreventlistener: Used to receive notifications from a sensor from Sensormanager, which contains two callback functions when the sensor changes.
Sensormanager:sensormanager gives you access to all the sensors on your device (mobile). Lets you access the device ' s sensors.
You can get an instance of the class by calling Context.getsystemservice () with the Android.content.Context.SENSOR_SERVICE argument.
Note : It should always be guaranteed to disable the sensor when the sensor is not needed, especially when your activity is paused. Failure to do so will result in a battery that can only be used for a few hours. Remember, the system does not automatically disable the sensor when the screen is turned off.
Sensorlistener: Abolished, no longer introduced.
Sensorevent API-Defined coordinate system
The Android Sensorevent API defines the coordinate system: The x-axis is horizontal to the right, the y-axis is vertically upward, and the z-axis is outward along the screen. In this coordinate system, the z-value behind the screen is negative. As shown in the following:
The following describes how the Android sensor-related API is used.
Demo
Demo from Doc
A simple demo is given in Sensormanager's doc:
public class Sensoractivity extends Activity, implements Sensoreventlistener { private final Sensormanager Msensormanager; Private final Sensor Maccelerometer; Public sensoractivity () { Msensormanager = (sensormanager) getsystemservice (sensor_service); Maccelerometer = Msensormanager.getdefaultsensor (Sensor.type_accelerometer); } protected void Onresume () { super.onresume (); Msensormanager.registerlistener (This, maccelerometer, sensormanager.sensor_delay_normal); } protected void OnPause () { super.onpause (); Msensormanager.unregisterlistener (this); } public void onaccuracychanged (sensor sensor, int. accuracy) { } public void Onsensorchanged (Sensorevent event) { } }
This demo is short, but a basic framework for sensor development has been given, and the corresponding sensor has been disabled when activity is paused (it can be saved by the official version).
Another demo--sensortest
Here is a sensor test demo that will test your Android phone to support those sensors and display the sensor values in real time.
The layout file is as follows:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: context= "Com.example.sensortest.MainActivity" > <button android:id= "@+id/btnnext" Android:layout_wi Dth= "Wrap_content" android:layout_height= "wrap_content" android:text= "Next"/> <button Andro Id:id= "@+id/btnpause" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Androi D:layout_alignbaseline= "@+id/btnnext" android:layout_alignbottom= "@+id/btnnext" android:layout_torightof= "@+ Id/btnnext "android:text=" Pause "/> <textview Android:id= "@+id/txtinfo" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_alignleft= "@+id/btnnext" android:layout_below= "@+id/btnnext" android:layout_marginleft= " 15DP "android:layout_margintop=" 18DP "android:text=" Sensor informations "/> <textview androi D:id= "@+id/txtdetails" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Andro id:layout_alignleft= "@+id/txtinfo" android:layout_below= "@+id/txtinfo" android:layout_margintop= "14DP" android:text= "Sensor Values"/></relativelayout>
The activity code is as follows:
Package Com.example.sensortest;import Java.util.list;import Java.util.concurrent.atomic.atomicinteger;import Android.support.v7.app.actionbaractivity;import Android.hardware.sensor;import android.hardware.SensorEvent; Import Android.hardware.sensoreventlistener;import Android.hardware.sensormanager;import Android.os.Bundle;import Android.util.log;import Android.view.menu;import Android.view.menuitem;import Android.view.View;import Android.widget.button;import Android.widget.textview;public class Mainactivity extends Actionbaractivity {private Final String TAG = "Sensortest"; Sensormanager Sensormanager; Sensoreventlistener Listener; list<sensor> allsensors;volatile int currentindex =-1; Button Btnnext; Button Btnpause; TextView Txtinfo; TextView txtvalues; Atomicinteger showdetail = new Atomicinteger (1);p rivate void init () {Sensormanager = (Sensormanager) getsystemservice ( Sensor_service); allsensors = Sensormanager.getsensorlist (Sensor.type_all); Initviews (); InitSensorsListener ();} Privatevoid Initviews () {btnnext = (button) Findviewbyid (r.id.btnnext); btnpause = (Button) Findviewbyid (R.id.btnpause); Txtinfo = (TextView) Findviewbyid (r.id.txtinfo); txtvalues = (TextView) Findviewbyid (r.id.txtdetails); Btnnext.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {currentindex = ( Currentindex + 1)% allsensors.size (); Sensor sensor = Allsensors.get (currentindex), int type = Sensor.gettype (); Txtinfo.settext (String.Format ("%d:%s,%s", Currentindex + 1,sensortypetostring (Sensor.gettype ()), sensor.tostring ()); LOG.D (Tag,string.format ("%d:%s,%s", Currentindex + 1,sensortypetostring (Sensor.gettype ()), sensor.tostring ()));}); Btnpause.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) { Showdetail.incrementandget (); LOG.D (TAG, "showDetails:" + ShowDetail + ", idx:" + currentindex); if (Showdetail.get ()% 2 = = 1) {Btnpause.settext ("Pause ");} else {btnpause.settext ("Start");}});} private void Initsensorslistener () {if (allseNsors.size () > 0) {listener = new Sensoreventlistener () {Long lasttime = System.currenttimemillis (); long time; @Overrid epublic void Onsensorchanged (Sensorevent event) {time = System.currenttimemillis (); if (Showdetail.get ()% 2 = = 1) {Sensor Sensor = event.sensor;if (currentindex >= 0 && sensor.gettype () = = Allsensors.get (currentindex). GetType ()) { StringBuffer str = new StringBuffer ();//for (int i=0; i<event.values.length; i++) {//float value = event.values[i];for (Float value:event.values) {Str.append (value + "\ n");} Txtvalues.settext (str), if (Time-lasttime > +) {//true | | LOG.D (TAG, "type:" + sensortypetostring (Event.sensor.getType ()) + ", Values:" + str.tostring () + ", Time:" + Time ";}} }lasttime = time;} @Overridepublic void onaccuracychanged (sensor sensor, int accuracy) {LOG.D (TAG, "onaccuracychanged sensor:" + sensor+ ", Accracy: "+ Accuracy);}}; for (sensor sensor:allsensors) {Sensormanager.registerlistener (Listener, sensor, Sensormanager.sensor_delay_normal);}}} string sensortypetostring (int type) {string res = Null;switch (type) {case Sensor.TYPE_ACCELEROMETER:res = "ACCELEROMETER "; Break;case Sensor.TYPE_AMBIENT_TEMPERATURE:res =" Ambient_temperature "; Break;case sensor.type_game_rotation_ Vector:res = "Game_rotation_vector"; break;case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:res = "Geomagnetic_rotation_ VECTOR "; Break;case Sensor.TYPE_GRAVITY:res =" GRAVITY "; break;case Sensor.TYPE_GYROSCOPE:res =" GYROSCOPE "; break;case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:res = "gyroscope_uncalibrated"; break;case Sensor.TYPE_HEART_RATE:res = "Heart_ Rate "; Break;case Sensor.TYPE_LIGHT:res =" Light "; break;case Sensor.TYPE_LINEAR_ACCELERATION:res =" Linear_ Acceleration "; break;case Sensor.TYPE_MAGNETIC_FIELD:res =" Magnetic_field "; Break;case sensor.type_magnetic_field_ Uncalibrated:res = "magnetic_field_uncalibrated"; break;case Sensor.TYPE_ORIENTATION:res = "ORIENTATION"; break;case Sensor.TYPE_PRESSURE:res = "pressure"; break;case Sensor.TYPE_PROXIMITY:res = "PROXIMITY "; Break;case Sensor.TYPE_RELATIVE_HUMIDITY:res =" humidity "; break;case Sensor.TYPE_ROTATION_VECTOR:res =" Rotation_vector "; break;default:res =" unknow "; break;} return res;} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); init ();} protected void Onresume () {super.onresume (); for (Sensor sensor:allsensors) {Sensormanager.registerlistener (liste NER, sensor, sensormanager.sensor_delay_normal);}} protected void OnPause () {super.onpause (); for (Sensor sensor:allsensors) {Sensormanager.unregisterlistener (liste NER, sensor);} } @Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action Bar if it is P Resent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar will//automatically handle clicks on the Home/up buttOn, so long//as you specify a parent activity in AndroidManifest.xml.int ID = item.getitemid (); if (id = = R.id.action_sett Ings) {return true;} return super.onoptionsitemselected (item);}}
The actual operation is as follows:
Android Sensor Development