我正在研究iPhone上的传感器操作,想知道如何在Android中实现启动和停止传感器操作。我在这个论坛上搜索过,但没有找到确定的答案。有人有什么线索吗?
我正在研究iPhone上的传感器操作,想知道如何在Android中实现启动和停止传感器操作。我在这个论坛上搜索过,但没有找到确定的答案。有人有什么线索吗?
在活动中使用传感器很容易,基本上你需要:
1º 声明你需要的传感器。
// Sensor static
static private SensorManager mSensorManager;
static private List<Sensor> deviceSensors;
static private Sensor mAccelerometer;
static private Sensor mGravity;
static private Sensor mGyroscope;
static private Sensor mLinearAcceleration;
static private Sensor mRotationVector;
static private Sensor mOrientation;
static private Sensor mMagneticField;
static private Sensor mProximity;
static private Sensor mPressure;
static private Sensor mLight;
2º 您必须在所有onCreate中初始化,就像这样:
// Add sensor manager STATIC (only 1 time)
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
// Load default Sensors
loadDefaultSensors();
// Set Sensor Listener
setAllSensorListener();
loadDefaultSensors 的第三个参数类似于这样:
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGravity = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mLinearAcceleration = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
mRotationVector = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
mMagneticField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mPressure = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
第四步,设置监听器:
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mGravity, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mLinearAcceleration, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mRotationVector, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mOrientation, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mMagneticField, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mPressure, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
如果您需要节省CPU等资源,可以在onPause中取消监听器,然后在onResume中重新注册。
mSensorManager.unregisterListener(this);
我希望这有助于开始...... 你需要知道的一切,在这里
100
个+1,我会这样做。在整个SO中,没有人曾经说过要使用unregisterListener
。 - VenomVendor