简体   繁体   English

从android加速度计获取倾斜角度

[英]Get tilt angle from the android accelerometer

I have a class that implements SensorEventListener and I would like to get the tilt Angle of my device using the Accelerometer . 我有一个实现SensorEventListener的类,我想使用Accelerometer来获取设备的tilt Angle

I looked for examples on the internet but they use Sensor.TYPE_MAGNETIC_FIELD . 我在互联网上查找了示例,但他们使用了Sensor.TYPE_MAGNETIC_FIELD

I believe my device doesn't have this sensor because when I do the following check 我相信我的设备没有这个传感器,因为当我做以下检查时
manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() , I get zero . manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() ,我得

Is there a way to get the tilt Angle by just using Sensor.TYPE_ACCELEROMETER values? 有没有办法通过使用Sensor.TYPE_ACCELEROMETER值来获得tilt Angle

As people suggested you can use the accelerometer and magnetic sensor to do this. 正如人们建议你可以使用加速度计和磁传感器来做到这一点。

Here is a blog post with a complete solution. 这是一篇包含完整解决方案的博客文章。

http://www.ahotbrew.com/how-to-detect-forward-and-backward-tilt/ http://www.ahotbrew.com/how-to-detect-forward-and-backward-tilt/

Try this, 试试这个,

SensorManager sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);        

        final SensorEventListener mEventListener = new SensorEventListener() {
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
            }


            public void onSensorChanged(SensorEvent event) {
                // TODO Auto-generated method stub
                switch (event.sensor.getType()) {
                case Sensor.TYPE_ACCELEROMETER:
                    System.arraycopy(event.values, 0, mValuesAccel, 0, 3);
                    break;

                case Sensor.TYPE_MAGNETIC_FIELD:
                    System.arraycopy(event.values, 0, mValuesMagnet, 0, 3);
                    break;
                }
            };
        };

        setListners(sensorManager, mEventListener);

SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet);
                SensorManager.getOrientation(mRotationMatrix, mValuesOrientation);
                final CharSequence test;
                test = ","+mValuesOrientation[0] +","+mValuesOrientation[1]+ ","+ mValuesOrientation[2];

You can use the accelerometer to get a tilt reading. 您可以使用加速度计获得倾斜读数。 If you set up an accelerometer you will notice it includes the force of gravity. 如果您设置加速度计,您会注意到它包含重力。 So if you phone is face-up on a table the z-axis will register somewhere close to 9.81 (the force of gravity) and the x and y axes will be at 0. As you tilt the phone the force of gravity will be projected onto the x and/or y axis. 因此,如果你的手机正面朝上,那么z轴会在接近9.81(重力)的位置注册,x和y轴将为0.当你倾斜手机时,重力会被投射出来在x和/或y轴上。 Thus you the x and y values will tell you the tilt of the phone. 因此,x和y值将告诉您手机的倾斜度。

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

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