Search code examples
androidandroid-sensors

How to poll sensors slowly?


I'm writing an app which copies sensor data to a text file over a long period of time. So I would like to use as little battery as possible, hence the requirement of a slower polling time.

Currently I have this as my listener:

sMgr.registerListener(this,sProximity,5000000);

which I believe should poll the sensor every 5,000,000 microseconds. However, it seems to be polling it at ~4 times a second. This actually doesn't change no matter what value I put in.

At the moment I'm just displaying the sensor data in the app with the onSensorChanged method override - could this be why it is polling the sensor so frequently?


Solution

  • You can't "poll sensors slowly".

    According to the docs:

    samplingPeriodUs
    The rate sensor events are delivered at. This is only a hint to the system. Events may be received faster or slower than the specified rate. Usually events are received faster.

    Also polling every 5 seconds doesn't give you any benefits over polling faster in terms of battery usage, since either will prevent the device from entering sleep mode.

    If this is only for testing purposes and eventually you're looking at much longer periods than 5 seconds, i.e. 15 or 30 minutes, then a way to do this is to use AlarmManager to set a repeating alarm that starts a Service, which registers a listener for the sensor, stores the value, and unregisters the listener until the next alarm is triggered.

    If you do indeed want to poll every 5 seconds and you're only concerned about storage space for the faster polling you can just store a timestamp for the last stored value and just discard every value received faster than your desired polling period, but as I said before, this won't help you with battery consumption.