【发布时间】:2010-08-18 17:25:20
【问题描述】:
现在 SENSOR_ORIENTATION 已被弃用,获取指南针航向的最佳做法是什么?老方法就是这么简单。
【问题讨论】:
标签: android
现在 SENSOR_ORIENTATION 已被弃用,获取指南针航向的最佳做法是什么?老方法就是这么简单。
【问题讨论】:
标签: android
以下是获取指南针方向并将其显示在 TextView 中的基本示例。它通过实现 SensorEventListener 接口来实现。您可以通过更改以下代码行中的常量来更改事件传递到系统的速率(即“mSensorManager.registerListener(this, mCompass, SensorManager.SENSOR_DELAY_NORMAL);”)(参见 OnResume() 事件);但是,该设置只是对系统的建议。此示例还使用 onReuse() 和 onPause() 方法通过在不使用时注册和取消注册侦听器来延长电池寿命。希望这会有所帮助。
package edu.uw.android.thorm.wayfinder;
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 CSensorActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mCompass;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutsensor);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mCompass = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
mTextView = (TextView) findViewById(R.id.tvSensor);
}
// The following method is required by the SensorEventListener interface;
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// The following method is required by the SensorEventListener interface;
// Hook this event to process updates;
public void onSensorChanged(SensorEvent event) {
float azimuth = Math.round(event.values[0]);
// The other values provided are:
// float pitch = event.values[1];
// float roll = event.values[2];
mTextView.setText("Azimuth: " + Float.toString(azimuth));
}
@Override
protected void onPause() {
// Unregister the listener on the onPause() event to preserve battery life;
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mCompass, SensorManager.SENSOR_DELAY_NORMAL);
}
}
以下是相关的 XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tvSensor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
【讨论】:
SensorManager.getOrientation(float[] R, float[] values) 是从 API 级别 3 开始使用的标准 API 调用。
【讨论】:
getOrientation(...),你需要同时注册Sensor.TYPE_ACCELEROMETER和@ 987654324@ events... 或者至少是上面提供的示例代码中显示的内容。这使得注册两个传感器而不是一个!