传感器的种类1.动作传感器
加速度传感器、重力传感器和陀螺仪传感器等
2.位置传感器
方向传感器和磁力传感器
3.环境传感器
温度传感器、压力传感器和亮度传感器等
使用传感器的方法
1.获取SensorManager对象;
2.执行SensorManager对象的getDefaultSensor()方法获取Sensor对象;
3.获取Sensor对象的各种属性;
main.xml:
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="fill_parent"
5 android:orientation="vertical" >
6
7 <Button
8 android:id="@+id/sensorButton"
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 android:text="@string/sensorButton" />
12
13 </LinearLayout>
strings.xml:
1 <?xml version="1.0" encoding="utf-8"?>
2 <resources>
3
4 <string name="hello">Hello World, MainActivity!</string>
5 <string name="app_name">05_01_sensor01</string>
6 <string name="sensorButton">获取当前设备所支持的传感器</string>
7
8 </resources>
MainActivity.java:
1 package org.gaolei.sensor01;
2
3 import java.util.List;
4
5 import android.app.Activity;
6 import android.content.Context;
7 import android.hardware.Sensor;
8 import android.hardware.SensorManager;
9 import android.os.Bundle;
10 import android.view.View;
11 import android.widget.Button;
12
13 public class MainActivity extends Activity {
14 private Button sensorButton;
15
16 // SensorManager用于管理手机当中所有的传感器对象
17 private SensorManager sensorManager;
18
19 @Override
20 public void onCreate(Bundle savedInstanceState) {
21 super.onCreate(savedInstanceState);
22 setContentView(R.layout.main);
23
24 // 得到SensorManager对象
25 sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
26
27 sensorButton = (Button) findViewById(R.id.sensorButton);
28 sensorButton.setOnClickListener(new OnClicklistener());
29 }
30
31 private final class OnClicklistener implements View.OnClickListener {
32
33 @Override
34 public void onClick(View v) {
35
36 // 通过调用getSensorList方法,得到当前手机当中所有的传感器
37 List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
38
39 for (Sensor sensor : sensors) {
40 // System.out.println(sensor.getMaximumRange());
41 // System.out.println(sensor.getMinDelay());
42 System.out.println(sensor.getName());
43 // System.out.println(sensor.getPower());
44 // System.out.println(sensor.getResolution());
45 // System.out.println(sensor.getType());
46 // System.out.println(sensor.getVendor());
47 // System.out.println(sensor.getVersion());
48
49 // 通过调用getDefaultSensor方法。获取某一类型的默认传感器
50 // Sensor sensor =
51 // sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
52 }
53
54 }
55
56 }
57 }