作者:裘德超
目前,大多数Android手机手机都内置了很多传感器,大家熟知的有重力传感器,亮度传感器,加速度传感器等。本文将为大家介绍Android系统中的运动传感器。
Android系统为用户提供了多个运动传感器,其中,加速度传感器和陀螺仪传感器经常是由硬件实现,而重力传感器,线形加速度传感器,旋转向量传感器一般是由软件实现出来的,由软件实现的模拟传感器从一个或多个硬件传感器中获取数据来模拟该虚拟传感器。对于每一个传感器事件,运动传感器都返回一个多维数组,其中包含了传感器感知的数据。下表总结了Android平台中的所有运动传感器:
与传感器有关的类主要包含在android.hardware包中。
SensorManager:可以用来管理Android设备中指出的所有的传感器。
Sensor:具体的传感器,例如重力传感器,陀螺仪传感器。
通过SensorManager类的registerListener方法可以监听某一个传感器,当被监测的传感器的检测到数据变化时就会产生一个事件,回调该传感器的监听器,我们可以在回调方法中执行相应的操作应对数据的变化。
下面是测试程序的布局:首先是一个用于显示当前机器包含的所有硬件传感器和软件传感器的列表。然后分别是重力传感器,加速度传感器(包括重力),线性加速度传感器(不包括重力),陀螺仪传感器,旋转向量传感器的检测到的数据的显示窗口。
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fadingEdge="vertical"
android:scrollbars="vertical" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/metaPromt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="metaPromt" />
<TextView
android:id="@+id/gravityPromt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="gravityPromt" />
<TextView
android:id="@+id/accelerometerPromt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="accelerometerPromt" />
<TextView
android:id="@+id/linearAccelerometerPromt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="linearAccelerometerPromt" />
<TextView
android:id="@+id/gyroscopePromt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="gyroscopePromt" />
<TextView
android:id="@+id/rotatio