android 注册 sensor 代码
头文件
import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager;
监听对象
SensorEventListener mAccListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { //Log.d(TAG, "onSensorChanged: event.values[0]" + event.values[0] + " ,event.values[1]" + event.values[1]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } };
定义sensor
private static final String TAG = "AccSensor"; private SensorManager sensorManager; private Sensor acc_sensor; private Sensor gyro_sensor;
初始化(加速度sensor)
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); acc_sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
注册及取消注册
sensorManager.registerListener(mAccListener, acc_sensor, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.unregisterListener(mAccListener);
SensorManager.SENSOR_DELAY_NORMAL 为调用频率