Android重力感应模拟器实现与实例开发

原址 http://wxmijl.blog.163.com/blog/static/13245928201062734631474/
Sensor Simulator是重力感应模拟器,下载地址如下:
http://code.google.com/p/openintents/downloads/detail?name=sensorsimulator-1.0.0-beta1.zip&can=2&q=



在你的就应用里怎样使用 SensorSimulator
如果你从没使用过,请在你的模拟器中安装OpenIntents.apk

Add the external JAR openintents-lib-n.n.n.jar into your project.
Replace the following code in onCreate():
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
by this code
// Before calling any of the Simulator data,
// the Content resolver has to be set !!
Hardware.mContentResolver = getContentResolver();

// Link sensor manager to OpenIntents Sensor simulator
mSensorManager = (SensorManager) new SensorManagerSimulator((SensorManager)
                              getSystemService(SENSOR_SERVICE));
By default this still passes the original sensor values, so to activate sensors you have to first call (to set the sensor settings):
Intent intent = new Intent(Intent.ACTION_VIEW,
Hardware.Preferences.CONTENT_URI);
startActivity(intent);
and then
// first disable the current sensor
mSensorManager.unregisterListener(mGraphView);

// now connect to simulator
SensorManagerSimulator.connectSimulator();

// now enable the new sensors
mSensorManager.registerListener(this,
           SensorManager.SENSOR_ACCELEROMETER |
           SensorManager.SENSOR_MAGNETIC_FIELD |
           SensorManager.SENSOR_ORIENTATION,
           SensorManager.SENSOR_DELAY_FASTEST);
All other code stays untouched. You can find reference code for how to implement sensors in the API demos / OS / Sensors.java.
Usually one would (un)register the sensors in onResume() and onStop():
    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this,
                SensorManager.SENSOR_ACCELEROMETER |
                SensorManager.SENSOR_MAGNETIC_FIELD |
                SensorManager.SENSOR_ORIENTATION,
                SensorManager.SENSOR_DELAY_FASTEST);
    }
  
    @Override
    protected void onStop() {
        mSensorManager.unregisterListener(mGraphView);
        super.onStop();
    }
Then just implement the standard Android SensorListener (there is no OI counterpart necessary).
class MySensorActivity extends Activity implements SensorListener {
    public void onSensorChanged(int sensor, float[] values) {
        // do something with the sensor values.
    }
}
Note 1: The OpenIntents class SensorManagerSimulator is derived from the Android class SensorManager and implements exactly the same functions (see Android SensorManager). For the callback, the standard Android SensorListener is used. The only new functions are connectSimulator() and disconnectSimulator().
Note 2: Whenever you are not connected to the simulator, you will get real device sensor data: the org.openintents.hardware.SensorManagerSimulator class transparently calls the SensorManager returned by the system service in this case.

你可能感兴趣的:(android,Google,Blog,OS)