我正在使用加速计传感器来检测我的设备是否平放在 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 度),如下图所示:
因此,仅当 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/