I’m trying to make an application that uses the on-board accelerometer.
When I’m setting up my sensors I get an error message when I use the TYPE_MAGNETIC_FIELD, it says: TYPE_MAGNETIC_FIELD cannot be resolved to a variable.
TYPE_ACCELERATOR works fine, tho.
Here’s my code:
@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);
}
these are defined in my mainactivity:
SensorManager sensMan;
Sensor accelerometer, magFieldSens;
SensorEventListener sensListen;
TextView orientationView;
in this class, the TYPE_MAGNETIC_FIELD can be used as expected:
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]);
}
}
}
Cheers
/M
You can just write
TYPE_MAGNETIC_FIELD its a static constant integer of Sensor.