简体   繁体   English

如何使用传感器Android检测设备是否在移动

[英]How to detect device is moving or not using sensor android

I am using below code to identify the movement of the device, means I would like to know that device is moving or not. 我正在使用下面的代码来标识设备的移动,这意味着我想知道设备是否在移动。 I also use Google Activity APIs which provides different activity modes like WALKING, ON_FOOT, STILL, etc without using GPS. 我还使用Google Activity API,这些API提供了不同的活动模式,例如WALKING,ON_FOOT,STILL等,而无需使用GPS。 I would like to achieve the same with Sensors but I am not able to get it accurately. 我想通过传感器实现相同的目的,但是我无法准确地获得它。

The issue with the following code is that as soon as I move the device quickly like take it from the table then I am getting the result as moving whereas it's not actually moving. 以下代码的问题在于,一旦我像从桌子上拿起设备一样快速移动设备,就会得到移动的结果,而实际上并没有移动。

// calling method from onSensorChanged method and using TYPE_ACCELEROMETER sensor.
double speed = getAccelerometer(event.values);

// then checking the speed.
if(speed > 0.9 && speed < 1.1) {
   // device is not moving
} else {
   // device is moving.
}

/**
     * @return
     */
    private double getAccelerometer(float[] values) {
        // Movement
        float x = values[0];
        float y = values[1];
        float z = values[2];

        float accelerationSquareRoot =
                (float) ((x * x + y * y + z * z) / (9.80665 * 9.80665));

        return Math.sqrt(accelerationSquareRoot);
    }

Can anyone guide me how to make this logic accurate so that I can identify the device is moving or not? 谁能指导我如何使此逻辑准确,以便我可以识别设备是否在移动?

For the purpose, you need to use Activity Recognition API which will provide you some events like moving, stop, driving, etc, And activity recognize use some sensor data and also help of location service when is running. 为此,您需要使用活动识别API,该API将为您提供一些事件,例如移动,停止,行驶等。活动识别使用一些传感器数据,并在运行时提供定位服务的帮助。 For the more how we can use and what actually it. 更进一步,我们如何使用以及实际使用什么。 You can read from below link 您可以从下面的链接中阅读

https://developers.google.com/location-context/activity-recognition/ https://developers.google.com/location-context/activity-recognition/

The accelerometer is made to return acceleration data and according to Netwon's 2nd law if the acceleration is constant then the body is not moving or moving with constant speed(this is quite impossibile in your case). 加速度计可以返回加速度数据,并且根据Netwon的第二定律,如果加速度恒定,则身体将不会以恒定速度运动或移动(这在您的情况下是完全不可能的)。 Therefore if you keep reading the same data on all three axis(or better in a quite strict range) from accelerometer over time it means the phone is not moving otherwise it is. 因此,如果您随着时间的推移不断从加速度计的所有三个轴上(或在相当严格的范围内)读取相同的数据,则意味着手机不会移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM