我正在研究iphone中的传感器动作,我想知道是否有人知道如何在android中实现启动和停止传感器动作。我搜索了这个论坛,但未能找到确定的东西。有没有人有线索?
答案 0 :(得分:13)
在活动中使用传感器很容易。基本上你需要:
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();
3º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);
4,设置听众:
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);
5º如果需要保存CPU等,可以使用unlistener onPause并再次注册onResume
mSensorManager.unregisterListener(this);
我希望有助于开始.....所有你需要知道的,HERE