开发者

Constantly monitor a sensor in Android

开发者 https://www.devze.com 2023-02-05 15:18 出处:网络
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 monito

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 comm开发者_如何学Gounity. 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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消