现在SENSOR_ORIENTATION已被弃用,那么获取指南针方向的最佳实践是什么?旧的方式非常简单。
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 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
和 Sensor.TYPE_MAGNETIC_FIELD
事件……或者至少在上面提供的示例代码中是这样显示的。这意味着需要注册两个传感器而不是一个! - JM Lord