How do I use the Android Accelerometer?

前端 未结 3 1732
逝去的感伤
逝去的感伤 2020-11-30 23:22

I\'m trying to build an app for reading the values from the accelerometer on my phone, which supports Android 2.1 only.

How do I read from the accelerometer using 2

相关标签:
3条回答
  • 2020-12-01 00:18

    Start with this:

    public class yourActivity extends Activity implements SensorEventListener{
     private SensorManager sensorManager;
     double ax,ay,az;   // these are the acceleration in x,y and z axis
     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
            sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
       }
       @Override
       public void onAccuracyChanged(Sensor arg0, int arg1) {
       }
    
       @Override
       public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
                ax=event.values[0];
                        ay=event.values[1];
                        az=event.values[2];
                }
       }
    }
    
    0 讨论(0)
  • 2020-12-01 00:21

    A very good example for accelerometer app.

    http://www.techrepublic.com/blog/app-builder/a-quick-tutorial-on-coding-androids-accelerometer/472

    0 讨论(0)
  • 2020-12-01 00:25

    This isn't easily explained in a few paragraphs. You should try to read:

    • Sensor Overview
    • SensorManager description

    These show a framework on how to access sensors:

     public class SensorActivity extends Activity implements SensorEventListener {
         private final SensorManager mSensorManager;
         private final Sensor mAccelerometer;
    
         public SensorActivity() {
             mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
             mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
         }
    
         protected void onResume() {
             super.onResume();
             mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
         }
    
         protected void onPause() {
             super.onPause();
             mSensorManager.unregisterListener(this);
         }
    
         public void onAccuracyChanged(Sensor sensor, int accuracy) {
         }
    
         public void onSensorChanged(SensorEvent event) {
         }
     }
    

    In the onSensorChanged callback you can query the sensor's values through the SensorEvent.

    0 讨论(0)
提交回复
热议问题