How to read accelerometer data in Service with And

2019-06-22 08:10发布

问题:

Usually, in Android, we read the accelerometer data in an "Activity", by overriding the OnSensorChanged function.

I am curious how we can do it in a "Service".

Thanks, Vincent

回答1:

Actually OnSensorChanged(SensorEvent event) is method from interface SensorEventListener.

So if you want to do it in service; you make your new class that extends Service and implements SensorEventListener.



回答2:

You can do exactly the same in a Service as well.

public class BGHndlr extends Handler implements SensorEventListener {

    public BGHndlr(Looper looper) {
        super(looper);
     }

     @Override
     public void handleMessage(Message msg) {
         oSensorManager.registerListener(this, oAcceleroMeter, SensorManager.SENSOR_DELAY_FASTEST);
     }

    @Override
    public void onSensorChanged(SensorEvent event) {
         // do something
    }

    @Override
     public void onAccuracyChanged(Sensor sensor, int i) {}
}