java - 如何知道 Android 设备是否平放在 table 上

标签 java android accelerometer android-sensors

我正在使用加速计传感器来检测我的设备是否平放在 table 上。奇怪的是,即使我将手机放平或侧放,该值始终在 90 到 100 之间!这不应该是正确的!我错过了什么吗?这是我的代码:

   float[] values = event.values;
    // Movement
    float x = values[0];
    float y = values[1];
    float z = values[2];
    float norm_Of_g =(float) Math.sqrt(x * x + y * y + z * z);

    // Normalize the accelerometer vector
    x = (x / norm_Of_g);
    y = (y / norm_Of_g);
    z = (z / norm_Of_g);
    int inclination = (int) Math.round(Math.toDegrees(Math.acos(y)));
    Log.i("tag","incline is:"+inclination);

    if (inclination < 25 || inclination > 155)
    {
        // device is flat
        Toast.makeText(this,"device flat - beep!",Toast.LENGTH_SHORT);
    }

编辑:我正在使用此代码:How to measure the tilt of the phone in XY plane using accelerometer in Android

最佳答案

您使用的是 y 轴而不是 the answer you linked 中使用的 z 轴.

当参数接近 1 时,acos 的值将接近于零(或接近负 1 时接近 180 度),如下图所示:

Arccos(x)

因此,仅当 y 轴归一化为大约 1 或负 1 时,例如当它与重力平行时,您的倾角才会接近 0(或 180)度(因此,设备“直立”) .

如果没有其他错误,只需切换:

int inclination = (int) Math.round(Math.toDegrees(Math.acos(y)));

int inclination = (int) Math.round(Math.toDegrees(Math.acos(z)));

应该这样做。

关于java - 如何知道 Android 设备是否平放在 table 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30948131/

相关文章:

java - 可以在商业应用程序中使用 SimpleXML for Android 吗?

java - equalsIgnoreCase() 方法内有多个参数

Java JDBC : connect cannot be resolved error

android - 注册为自定义文件类型的默认应用

android - AccelerationSensor.accelerationchanged()使应用变慢

ios - 使用加速度计和陀螺仪时的系统性能和电池使用

android - 使用摇动 Action 从加速度计获取方向

java - Cordova 插件 - 添加第三方 sdk

java - Retrofit 的动态响应

android - 自动重新连接 socket 从 wifi 到 4G