gpt4 book ai didi

android - 使用 getOrientation() 函数获取设备角度

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:52:29 26 4
gpt4 key购买 nike

我使用 Sensor.TYPE_ORIENTATION 来确定设备的当前角度,但 TYPE_ORIENTATIONAPI 版本 8 上已弃用。在 SensorManager 手册中,它引用了 getOrientation() 函数以便使用 TYPE_ORIENTATION

Here is the manual


这是我的旧代码:

public void onSensorChanged(SensorEvent event) {
Log.d("debug","Sensor Changed");
if (event.sensor.getType()==Sensor.TYPE_ORIENTATION) {
Log.d("debug",Float.toString(event.values[0]));


float mAzimuth = event.values[0];
float mPitch = event.values[1];
float mRoll = event.values[2];

Log.d("debug","mAzimuth :"+Float.toString(mAzimuth));
Log.d("debug","mPitch :"+Float.toString(mPitch));
Log.d("debug","mRoll :"+Float.toString(mRoll));
}

}

我对使用 getOrientation() 函数真的很困惑,任何人都可以告诉我一个如何获得角度的例子吗?

最佳答案

您现在使用两个传感器(ACCELEROMETER 和 MAGNETIC_FIELD)来获取该信息。参见 blog post for more detail.

public class CompassActivity extends Activity implements SensorEventListener {

private SensorManager mSensorManager;
Sensor accelerometer;
Sensor magnetometer;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(mCustomDrawableView); // Register the sensor listeners
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}

protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
}

protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}

public void onAccuracyChanged(Sensor sensor, int accuracy) { }

float[] mGravity;
float[] mGeomagnetic;
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
azimut = orientation[0]; // orientation contains: azimut, pitch and roll
}
}
}
}

权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

关于android - 使用 getOrientation() 函数获取设备角度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20339942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com