我需要将电话方向从1-360拉为整数,而不使用OrientationEventListener来检查onOrientationChanged()

能做到吗?我做了很多谷歌搜索,并且走得还很远。

谢谢

最佳答案

您可能需要使用加速度计来获得精确的角度。以下内容摘自Vogella:

public class SensorTestActivity extends Activity implements SensorEventListener {
  private SensorManager sensorManager;
  private boolean color = false;
  private View view;
  private long lastUpdate;


/** Called when the activity is first created. */

  @Override
  public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    view = findViewById(R.id.textView);
    view.setBackgroundColor(Color.GREEN);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    lastUpdate = System.currentTimeMillis();
  }

  @Override
  public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      getAccelerometer(event);
    }

  }

  private void getAccelerometer(SensorEvent event) {
    float[] values = event.values;
    // Movement
    float x = values[0];
    float y = values[1];
    float z = values[2];

    float accelationSquareRoot = (x * x + y * y + z * z)
        / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
    long actualTime = System.currentTimeMillis();
    if (accelationSquareRoot >= 2) //
    {
      if (actualTime - lastUpdate < 200) {
        return;
      }
      lastUpdate = actualTime;
      Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT)
          .show();
      if (color) {
        view.setBackgroundColor(Color.GREEN);

      } else {
        view.setBackgroundColor(Color.RED);
      }
      color = !color;
    }
  }

  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }

  @Override
  protected void onResume() {
    super.onResume();
    // register this class as a listener for the orientation and
    // accelerometer sensors
    sensorManager.registerListener(this,
        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    // unregister listener
    super.onPause();
    sensorManager.unregisterListener(this);
  }
}


至于采取什么角度,这可能会有所帮助:


  方位角(围绕z轴的旋转度)。这是角度
  在磁北和设备的y轴之间。例如,如果
  设备的y轴与磁北对齐,该值为0,如果
  设备的y轴指向南方,该值为180。同样,
  当y轴指向东时,此值为90;当为
  向西指向此值是270。
  
  螺距(绕x轴旋转的角度)。当z轴的正向y轴旋转时,此值为正,
  当正z轴朝向旋转时为负
  负y轴。值的范围是180度到-180度。
  
  滚动(绕y轴的旋转度)。当z轴的正向x轴旋转时,此值为正,
  当正z轴朝向旋转时为负
  负x轴。值的范围是90度到-90度。


参考:
http://www.vogella.com/tutorials/AndroidSensor/article.html
http://developer.android.com/guide/topics/sensors/sensors_position.html

07-24 09:29