草庐IT

java - 收集特定时间段的android传感器并计算平均值

coder 2023-12-12 原文

我正在尝试编写一种方法来收集特定时间段内的加速度计传感器值并返回该时间段内传感器读数的平均值。

它应该是同步的,即阻塞方法,一旦被调用就会阻塞调用线程一段时间,然后返回传感器平均值

我确实检查了以下类似的问题,但似乎没有适合我的案例的有效解决方案:

SensorEventListener in separate thread

Android - how to run your sensor ( service, thread, activity )?

Android sensors and thread

A method for waiting for sensor data

我还尝试使用类似于 this questionExecutors ,但无法让它按我的意愿工作。

下面是我的代码框架,其中方法 sensorAverage 是一个阻塞方法,它将计算加速度计传感器在一段时间内的平均值等于 timeout 参数

Average average = new Average(); // Some class to calculate the mean

double sensorAverage(long timeout){
    Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
    sensorManager.registerListener(this, sensor,SensorManager.SENSOR_DELAY_NORMAL);

    // This does not work
    Thread.sleep(timeout);

    sensorManager.unregisterListener(this);

    return average.value();
}

public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
        double x2 = Math.pow(event.values[0], 2);
        double y2 = Math.pow(event.values[1], 2);
        double z2 = Math.pow(event.values[2], 2);
        average.add(Math.sqrt((x2 + y2 + z2)));
    }
}

编辑: 我知道我需要另一个线程,但问题是我只需要在特定时期内运行它,到目前为止我找不到合适的工作解决方案。因为当我使用另一个线程时,我总是得到传感器平均值 0

最佳答案

我设法实现了一个完全符合我要求的解决方案。

一种阻塞方法,它收集特定时间段的传感器值并返回所有传感器读数的统计数据,即均值和方差。

可以简单地存储所有传感器的值,然后计算均值和方差;但是,如果长时间收集高频传感器,您可能会耗尽内存。

我找到了一个更好的解决方案,可以使用下面的 RunningStat 类实时计算数据流的均值和方差(即不存储传感器值)

示例代码:

// Calculate statistics of accelerometer values over 300 ms (a blocking method)
RunningStat[] stats = SensorUtils.sensorStats(context, 
                                                  Sensor.TYPE_ACCELEROMETER, 300)
double xMean = stats[0].mean();
double xVar  = stats[0].variance();

完整类代码:

public class SensorUtils {

// Collect sensors data for specific period and return statistics of 
// sensor values e.g. mean and variance for x, y and z-axis
public static RunningStat[] sensorStats(Context context, int sensorType,
        long timeout) throws Exception {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<RunningStat[]> future = executor.submit(new SensorTask(context,
            sensorType, timeout));

    RunningStat[] stats = future.get();
    return stats;

}

private static class SensorTask implements Callable<RunningStat[]> {
    private final Context context;
    private final long timeout;
    private final int sensorType;
    // We need a dedicated handler for the onSensorChanged
    HandlerThread handler = new HandlerThread("SensorHandlerThread");

    public SensorTask(Context context, int sensorType, long timeout) {
        this.context = context;
        this.timeout = timeout;
        this.sensorType = sensorType;
    }

    @Override
    public RunningStat[] call() throws Exception {
        final SensorCollector collector = new SensorCollector(context);
        handler.start();
        Thread sensorThread = new Thread() {
            public void run() {
                collector.start(sensorType,
                        new Handler(handler.getLooper()));
            };
        };
        sensorThread.start();
        Thread.sleep(timeout);
        return collector.finishWithResult();
    }
}

private static class SensorCollector implements SensorEventListener {
    protected Context context;
    protected RunningStat[] runningStat;
    protected SensorManager sensorManager;
    protected int sensorType;

    public SensorCollector(Context context) {
        this.context = context;
    }

    protected void start(int sensorType, Handler handle) {
        if (runningStat == null) {
            runningStat = new RunningStat[3];
            runningStat[0] = new RunningStat(3);
            runningStat[1] = new RunningStat(3);
            runningStat[2] = new RunningStat(3);
        } else {
            runningStat[0].clear();
            runningStat[1].clear();
            runningStat[2].clear();
        }
        this.sensorType = sensorType;
        sensorManager = (SensorManager) context
                .getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(sensorType);
        sensorManager.registerListener(this, sensor,
                SensorManager.SENSOR_DELAY_NORMAL, handle);
    }

    public RunningStat[] finishWithResult() {
        if (sensorManager != null) {
            sensorManager.unregisterListener(this);
        }
        return runningStat;
    }

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

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == sensorType) {
            runningStat[0].push(event.values[0]);
            runningStat[1].push(event.values[1]);
            runningStat[2].push(event.values[2]);
        }
    }
}

}

这里是 RunningStat 代码,这是一个非常方便的类,可以计算数据流的均值和方差,而无需存储数据本身(非常适合计算内存占用非常小的高频传感器)

//See Knuth TAOCP vol 2, 3rd edition, page 232
public class RunningStat {
private int n;
private double oldM, newM, oldS, newS;
private int precision = -1;

// An estimate for the t-value (can be read from the t-distribution table)
private static final double T_THRESHOLD = 1.68;

public RunningStat(int precision) {
    this.precision = precision;
}

public RunningStat() {
}

public void clear() {
    n = 0;
}

public void push(double x) {
    n++;


    if (n == 1) {
        oldM = newM = x;
        oldS = 0.0;
    } else {
        newM = oldM + (x - oldM) / n;
        newS = oldS + (x - oldM) * (x - newM);

        // set up for next iteration
        oldM = newM;
        oldS = newS;
    }
}

public int count() {
    return n;
}

public double mean() {
    double mean = (n > 0) ? newM : 0.0;
    if (precision > 0) {
        return round(mean, precision);
    }
    return mean;
}

// The upper bound of the mean confidence interval
public double meanUpper() {
    double mean = (n > 0) ? newM : 0.0;
    double stdError = stdDeviation() / Math.sqrt(n);
    double upperMean = mean + T_THRESHOLD * stdError;
    if (precision > 0) {
        return round((n > 0) ? upperMean : 0.0, precision);
    }
    return upperMean;
}

// The lower bound of the mean confidence interval
public double meanLower() {
    double mean = (n > 0) ? newM : 0.0;
    double stdError = stdDeviation() / Math.sqrt(n);
    double lowerMean = mean - T_THRESHOLD * stdError;
    if (precision > 0) {
        return round((n > 0) ? lowerMean : 0.0, precision);
    }
    return lowerMean;
}

public double variance() {
    if (precision > 0) {
        return round(((n > 1) ? newS / (n - 1) : 0.0), precision);
    }
    return ((n > 1) ? newS / (n - 1) : 0.0);
}

public double stdDeviation() {
    if (precision > 0) {
        return round(Math.sqrt(variance()), precision);
    }
    return Math.sqrt(variance());
}

public void setPrecision(int precision) {
    this.precision = precision;
}

    public static double round(double value, int precision) {
         BigDecimal num = new BigDecimal(value);
         num = num.round(new MathContext(precision, RoundingMode.HALF_UP));
         return num.doubleValue();
    }

// A small test case
public static void main(String[] args) {
    int n = 100;
    RunningStat runningStat = new RunningStat();
    double[] data = new double[n];
    double sum = 0.0;
    for (int i = 0; i < n; i++) {
        data[i] = i * i;
        sum += data[i];
        runningStat.push(data[i]);
        System.out.println(runningStat.mean() + " - "
                + runningStat.variance() + " - "
                + runningStat.stdDeviation());
    }

    double mean = sum / n;
    double sum2 = 0.0;

    for (int i = 0; i < n; i++) {
        sum2 = sum2 + (data[i] - mean) * (data[i] - mean);
    }

    double variance = sum2 / (n - 1);
    System.out.println("\n\n" + mean + " - " + variance + " - "
            + Math.sqrt(variance));
}
}

关于java - 收集特定时间段的android传感器并计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22365905/

有关java - 收集特定时间段的android传感器并计算平均值的更多相关文章

  1. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  2. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  3. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  4. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  5. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  6. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

  7. STM32读取串口传感器数据(颗粒物传感器,主动上传) - 2

    文章目录1.开发板选择*用到的资源2.串口通信(个人理解)3.代码分析(注释比较详细)1.主函数2.串口1配置3.串口2配置以及中断函数4.注意问题5.源码链接1.开发板选择我用的是STM32F103RCT6的板子,不过代码大概在F103系列的板子上都可以运行,我试过在野火103的霸道板上也可以,主要看一下串口对应的引脚一不一样就行了,不一样的就更改一下。*用到的资源keil5软件这里用到了两个串口资源,采集数据一个,串口通信一个,板子对应引脚如下:串口1,TX:PA9,RX:PA10串口2,TX:PA2,RX:PA32.串口通信(个人理解)我就从串口采集传感器数据这个过程说一下我自己的理解,

  8. Ruby - 如何在读取文件时跳过/忽略特定行? - 2

    在读取/解析文件(使用Ruby)时忽略某些行的最佳方法是什么?我正在尝试仅解析Cucumber.feature文件中的场景,并希望跳过不以Scenario/Given/When/Then/And/But开头的行。下面的代码有效,但它很荒谬,所以我正在寻找一个聪明的解决方案:)File.open(file).each_linedo|line|line.chomp!nextifline.empty?nextifline.include?"#"nextifline.include?"Feature"nextifline.include?"Inorder"nextifline.include?

  9. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  10. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

随机推荐