【问题标题】:Gyroscope: Rotational difference Android陀螺仪:旋转差 Android
【发布时间】:2016-03-10 01:49:40
【问题描述】:

我如何知道设备旋转了多少? 我的意思是如果我从一个初始位置开始,然后转了 90 度,我怎样才能让这段代码告诉我我已经转了 90 度?很抱歉这个问题的草率。这是我的代码:

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class AccessGyroscope extends Activity implements SensorEventListener
{
//a TextView
private TextView tv;
//the Sensor Manager
private SensorManager sManager;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //get the TextView from the layout file
    tv = (TextView) findViewById(R.id.tv);

    //get a hook to the sensor service
    sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}

//when this Activity starts
@Override
protected void onResume() 
{
    super.onResume();
    /*register the sensor listener to listen to the gyroscope sensor, use the 
     * callbacks defined in this class, and gather the sensor information as  
     * quick as possible*/
    sManager.registerListener(this, sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_FASTEST);
}

//When this Activity isn't visible anymore
@Override
protected void onStop() 
{
    //unregister the sensor listener
    sManager.unregisterListener(this);
    super.onStop();
}

@Override
public void onAccuracyChanged(Sensor arg0, int arg1) 
{
    //Do nothing
}

@Override
public void onSensorChanged(SensorEvent event) 
{
    //if sensor is unreliable, return void
    if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
    {
        return;
    }

    //else it will output the Roll, Pitch and Yawn values
    tv.setText("Orientation Z (Yaw) :"+ Float.toString(event.values[0]));
}
}

【问题讨论】:

    标签: java android gyroscope


    【解决方案1】:

    TYPE_ORIENTATION 传感器已弃用,请勿使用它,因为它不能很好地工作并且计算量很大。

    使用 [getRotationMatrix][1] 传入加速度计和磁场读数,然后在矩阵上使用 getRotation()。 这几乎是来自开发者参考的逐字记录:

    [1]:http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[],float[],float[],float[]) "getRotationMatrix()"

    【讨论】:

    • 感谢您花时间回答。我对在 android 中使用传感器相当陌生,所以如果你能给我一个示例代码来引导我朝着正确的方向前进,那会让我很清楚!谢谢!
    【解决方案2】:

    有时很难找到最简单的解决方案。

    我添加了 3 个按钮:1 个用于捕捉初始位置,1 个用于捕捉最终位置,以及一个用于减去两者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多