• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

How can I get the values from the "public void onSensorChanged(SensorEvent event) " to another?

lugopaco

Newbie
Hi!! I'm making an application on Android and I'm using the accelerometer sensor of my phone.

Part of the code is:
Code:
    public class OtroacelbtActivity extends Activity implements SensorEventListener {
    private float x = 0, y = 0, z = 0;
    
     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    }
    
    @Override
        protected void onResume() {
            super.onResume();
            SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
            List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
            if (sensors.size() > 0) {
             sm.registerListener(this, sensors.get(0), SensorManager.SENSOR_DELAY_UI );
            }
    }
    
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    
    @Override
    public void onSensorChanged(SensorEvent event) {
            synchronized (this) {
                
            String message=null;
           
                
                x = event.values[0];
                y = event.values[1];
                z = event.values[2];
    }
    }
}
I want to use the x,y and z values on another method, but even they are global variables, if I call them just like that on the other method, thee only give the "null" value (cause it's a void method).

How can I do it???

Thanks.
 
If you look at the AcceleratorPlay in the api-10 samples as part of the SDK you can see how they did it.

Simply define some class level variables e.g.
Code:
private float mSensorX;
private float mSensorY;
And in the onSensorChanged method

Code:
switch (mDisplay.getOrientation()) {
case Surface.ROTATION_0:
    mSensorX = event.values[0];
    mSensorY = event.values[1];
    break;
case Surface.ROTATION_90:
    mSensorX = -event.values[1];
    mSensorY = event.values[0];
    break;
case Surface.ROTATION_180:
    mSensorX = -event.values[0];
    mSensorY = -event.values[1];
    break;
case Surface.ROTATION_270:
     mSensorX = event.values[1];
     mSensorY = -event.values[0];
     break;
}
 
Back
Top Bottom