// First, get an instance of the SensorManager
SensorManager sman = Context.getSystemService(Context.SENSOR_SERVICE)
// Second, get the sensor you're interested in
Sensor magnetfield = sman.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
// Third, implement a SensorEventListener class
SensorEventListener magnetlistener = new SensorEventListener() {
void onAccuracyChanged(Sensor sensor, int accuracy) {
// do things if you're interested in accuracy changes
}
void onSensorChanged(SensorEvent event) {
// implement what you want to do here
}
}
// Finally, register your listener
sman.registerListener(magnetlistener, magnetfield, SensorManager.SENSOR_DELAY_NORMAL)
However, please note that this is actually a magnetic sensor; therefore if you have magnetic interference around you, it may be pointing to the wrong direction. Also, you need to know the difference between True North and Magnetic North. Since this coded uses magnetic sensor, you obtain the Magnetic North, if you need to calculate the True North, you would need to do some adjustments with GeomagneticField.getDeclination().