2011-06-22 51 views
6

我正在研究iPhone中的傳感器動作,我想知道是否有人會知道如何在android中實現啓動和停止傳感器動作。我搜索了這個論壇,但沒有找到明確的東西。有沒有人有線索和線索?實現啓動和停止傳感器android

回答

12

上的活動使用傳感器很容易。基本上你需要:

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º您必須initializate所有的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ºI F你需要節省CPU等,你可以使用一個unlistener的onPause和再註冊的onResume

 mSensorManager.unregisterListener(this); 

我希望這有助於啓動.....所有你需要知道,HERE

+0

你先生是救生員:)非常感謝! – user788511

+3

如果我有機會給100'+1,我會爲你做,在這整個SO中,從來沒有人說過使用'unregisterListener' – VenomVendor