自Android2.0版后,在Sensor这块的API接口较之前的1.5/1.6有了些许变化,主要反映在Sensor,SensorManager,SensorEvent这几个Class里。

使用Accelerometer的步骤如下:

  1. 得到SensorManager的reference
    SensorManager sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
  2. 得到要操作的Sensor的Reference
    List<Sensor> sensorList = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
    Sensor acceSensor = sensorList.get(0);
  3. 注册该Sensor的Listener,在这里例子里该Listener的变量是myAcceEventListener
    sm.registerListener(myAcceEventListener, acceSensor, SensorManager.SENSOR_DELAY_UI);
  4. 实现该Listener,即myAcceEventListener

    SensorEventListener myAcceEventListener = new SensorEventListener(){

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
             Log.i("myAcceEventListener"+"::onAccuracyChanged", "accuracy =" + accuracy);
        }  

        @Override
        public void onSensorChanged(SensorEvent event) {
            Log.i("myAcceEventListener"+"::onSensorChanged", "event.sensor.name =" + event.sensor.getName());
            Log.i("myAcceEventListener"+"::onSensorChanged", "xAxis acce speed = " + event.values[SensorManager.DATA_X]);
            Log.i("myAcceEventListener"+"::onSensorChanged", "yAxis acce speed = " + event.values[SensorManager.DATA_Y]);
            Log.i("myAcceEventListener"+"::onSensorChanged", "zAxis acce speed = " + event.values[SensorManager.DATA_Z]);
        }

    };

    主要有两个接口函数:onAccuracyChanged,onSensorChanged;顾名思义,一个是精度变化时收到的通知,另一个就是当Sensor的值变化时收到的通知。

下面的一篇文章要介绍Android的另一个非常有意思的Sensor,寻找手机朝向的Orientation Sensor。

Advertisements