When developing mobile phones, we sometimes use sensors, especially in game development. Next I didn't come to learn how to get the sensor.
Here we need a real Android phone. I use Huawei c8650.
To obtain a sensor from a mobile phone, follow these steps:
- Get sensormanager object
- Run the getdefasensensor () method of the sensormanager object to obtain the Sensor Object. Here, the getdefasensensor () method must pass a parameter to specify the specific sensor type.
- Obtain attributes of a Sensor Object
Let's look at the running effect first:
Interface:
Click the button to get the data:
XML layout code:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/btnGetSensor" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/btngetsensorstr"/></LinearLayout>
Activity Code:
Package COM. nine. sensordemo; import Java. util. list; import android. app. activity; import android. content. context; import android. hardware. sensor; import android. hardware. sensormanager; import android. OS. bundle; import android. util. log; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; public class mainactivity extends activity implements onclicklistener {private button btngetsensor; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); initwedget ();} private void initwedget () {btngetsensor = (button) findviewbyid (R. id. btngetsensor); btngetsensor. setonclicklistener (this);} public void onclick (view v) {sensormanager manager = (sensormanager) getsystemservice (context. sensor_service); // obtain the list of all sensors on the mobile phone <Sensor> listsensor = manager. getsensorlist (sensor. type_all); int I = 1; for (sensor: listsensor) {log. D ("sensor" + I, sensor. getname (); I ++;} // call the getdefasensensor method to obtain the Default Sensor of a certain type. // sensor S = manager. getdefasensensor (sensor. type_light );}}
The next step is to obtain all the sensors on the mobile phone.