我正在尝试制作一个使用板载加速度计的应用程序。
当我设置我的传感器时,当我使用 TYPE_MAGNETIC_FIELD 时收到一条错误消息,它说:TYPE_MAGNETIC_FIELD 无法解析为变量。TYPE_ACCELERATOR 工作正常,寿。
这是我的代码:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
sensMan = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
magFieldSens = sensMan.getDefaultSensor(TYPE_MAGNETIC_FIELD);
accelerometer = sensMan.getDefaultSensor(TYPE_ACCELEROMETER);
sensListen = new MySensorEventListener();
orientationView = (TextView) findViewById(R.id.orientationView);
}
这些在我的主要活动中定义:
SensorManager sensMan;
Sensor accelerometer, magFieldSens;
SensorEventListener sensListen;
TextView orientationView;
在此类中,可以按预期使用 TYPE_MAGNETIC_FIELD:
class MySensorEventListener implements SensorEventListener
{
/*
* @see android.hardware.SensorEventListener#onAccuracyChanged(android.hardware.Sensor, int)
*/
@Override
public void onAccuracyChanged(Sensor sensor, int acc)
{
// Edit this method, macke
if(acc <= 1)
Toast.makeText(SensorActivity.this, "Shake in a figure eight pattern ", Toast.LENGTH_LONG).show();
}
@Override
public void onSensorChanged(SensorEvent sensorEvent)
{
int sensorEventType = sensorEvent.sensor.getType();
if (sensorEventType == Sensor.TYPE_ACCELEROMETER)
System.arraycopy(sensorEvent.values, 0, gravVals, 0, 3);
else if(sensorEventType == Sensor.TYPE_MAGNETIC_FIELD)
System.arraycopy(sensorEvent.values, 0, geoMagnetVals, 0, 3);
else
return;
if(SensorManager.getRotationMatrix(rotMatrix, null, gravVals, geoMagnetVals))
{
SensorManager.getOrientation(rotMatrix, orientation);
orientationView.setText("X: " + orientation[0] +
"\nY: " + orientation[1] +
"\nZ: " + orientation[2]);
}
}
}
干杯/M