Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constantly monitor a sensor in Android

I am trying to figure out the best way to monitor the accelerometer sensor with a polling rate of less than .25 milliseconds. I have implemented a UI option for the user to switch to a constant monitoring state and made it clear of the battery drain ramifications. Would a remote service be the best way over a daemon thread because of the way Android handles cleaning up memory and threads? The point is to make the accelerometer monitored as close to constantly as possible, battery drain be damned. And this monitoring needs to be long running, maybe even more than 24 hours straight, again I realize the power consumption consequences. Any suggested reading or code snippets will be appreciated.

Just a newbe looking for advice from the wisdom of the Android community. Thanks in advance,

-Steve

CLARIFICATION: I am trying to detect the instant there is a change in acceleration. My code discriminates by axis, but getting real time data from the accelerometer is my goal.

like image 321
Kingsolmn Avatar asked Jan 20 '11 20:01

Kingsolmn


2 Answers

We did this using Android Services - they can be started from an activity but remain running in the background. That's probably what you're looking for!
Some Howtos:

  1. http://developerlife.com/tutorials/?p=356
  2. http://developer.android.com/guide/topics/fundamentals.html#procthread
like image 123
Blitz Avatar answered Nov 06 '22 16:11

Blitz


Using a specific thread to monitor and wait is the best solution that gives you flexibility on the wait period. This is quite efficient as it does not requires any specific service.

class MonitorThread extends Thread {
    ...
    public void run() {
        for (;;) {
            long ms = 0;
            int nanos = 250000;
            ... // Do something or compute next delay to wait
            try {
                Thread.sleep(ms, nanos);
            } catch (InterruptedException ex) {
            }
        }
    }
}

See http://developer.android.com/reference/java/lang/Thread.html

You specify a very short delay (.250 ms) so this will be CPU intensive. You can probably use the result of the accelerometer to increase or reduce this delay. For example, if you detect that there is no acceleration, increase the delay (it's up to you but 100ms seems reasonable or even higher). As soon you detect something, reduce the delay. All this depends on your application.

like image 20
ciceron Avatar answered Nov 06 '22 15:11

ciceron