我正在从这个tutorial开发一个指南针应用程序,但是有一些与教程不同的东西,例如我不想绘制指南针,只是将值放在EditText中,那就是不工作或真的我不知道发生了什么......我尝试调试应用程序,但传感器没有响应,日志没有显示任何错误...这是我尝试:
public class MainActivity extends Activity implements SensorEventListener {
float azimut;
private SensorManager mSensorManager;
Sensor accelerometer;
Sensor magnetometer;
float[] mGravity;
float[] mGeomagnetic;
private EditText edTLatitud;
private EditText edTLongitud;
private EditText edTCompass;
private EditText edTDirecc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edTCompass = (EditText)this.findViewById(R.id.edTxtBrujula);
edTDirecc = (EditText)this.findViewById(R.id.edTxtBrujdireccion);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
@Override
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];
UpdateCompassOnScreen(azimut);
edTCompass.setText((int)azimut);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// Show the value on the application of the compass with the direction
public void UpdateCompassOnScreen(float value)
{
if (value >= 338 && value <= 22.9999)
{
edTDirecc.setText("° N");
}
else if(value >= 23 && value <= 67.9999)
{
edTDirecc.setText("° NE");
}
else if (value >= 68 && value <= 112.9999)
{
edTDirecc.setText("° E");
}
else if(value >= 113 && value <= 157.9999)
{
edTDirecc.setText("° SE");
}
else if(value >= 158 && value <= 202.9999)
{
edTDirecc.setText("° S");
}
else if(value >= 203 && value <= 247.9999)
{
edTDirecc.setText("° SW");
}
else if(value >= 248 && value <= 292.9999)
{
edTDirecc.setText("° W");
}
else if (value >= 293 && value <= 337.9999)
{
edTDirecc.setText("° NW");
}
edTCompass.setText(String.valueOf(value));
}
感谢您的建议。
答案 0 :(得分:0)
我认为getRotationMatrix返回一个Matrix。
下面。 API演示中有些东西。 Pro Android 2也有东西。
public void onSensorChanged(SensorEvent event){
float[] mIdentityMatrix = new float[16];
mIdentityMatrix[0] = 1;
mIdentityMatrix[4] = 1;
mIdentityMatrix[8] = 1;
mIdentityMatrix[12] = 1;
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if (counter++ % 10 == 0) {
gravityMatrix = event.values.clone();
sensorReady = true;
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
geomagneticMatrix = event.values.clone();
if (sensorReady)
SensorManager.getRotationMatrix(mRotationMatrix,
mIdentityMatrix, gravityMatrix, geomagneticMatrix);
}