Build an Android Compass with the Magnetometer
Android phones contain the sensors needed for a digital compass, making this a useful exercise in sensor handling, display rotation and responsive interface work. Read the magnetic field, combine it with gravity data, and convert the orientation into a heading people can interpret at a glance.
This guide follows that path in Kotlin while keeping each stage testable. It also covers the compromises that matter outdoors: magnetic interference, tilt, calibration and the difference between magnetic north and true north.
Understanding magnetic bearings and sensor data
Android exposes the magnetometer as Sensor.TYPE_MAGNETIC_FIELD. Its X, Y and Z readings describe the magnetic field around the device, usually in microtesla. Those values include Earth’s field plus anything nearby that generates a magnetic signal, so a parked car, steel structure or speaker can change the reading.
The accelerometer supplies the gravity vector used to establish which way the phone is facing. Together, gravity and magnetic-field readings feed a rotation matrix. Android’s orientation angles come from that matrix, with azimuth representing rotation around the vertical axis and forming the basis of the compass heading.
Magnetic and true north are different, and declination varies across Australia. A correction calculated in Sydney may be wrong in Melbourne or Perth. GeomagneticField estimates local declination from coordinates and time; apply it as a correction to magnetic bearing.
Preparing the Android project
Create an Android Studio project with Kotlin and AppCompat, then use a custom view for the dial. No third-party compass library is required. Keep sensor calculations separate from drawing code so numerical errors are easier to diagnose.
Declare magnetometer hardware as optional in the manifest, because a device without it should reach a clear unsupported state rather than crash:
<uses-feature
android:name="android.hardware.sensor.compass"
android:required="false" />
Also declare android.permission.ACCESS_COARSE_LOCATION only if the app will request coordinates for declination.
Use getDefaultSensor and registerListener with SENSOR_DELAY_UI in onResume, then call unregisterListener in onPause; otherwise the app wastes power and may calculate while hidden. Check both sensor values at runtime and show an unsupported message when either is missing.
Porting sensor code from a Windows/.NET prototype can introduce a different platform concern: this background on COM initialisation explains that older environment, whereas Android sensor APIs require no COM setup.
Calculating a stable device heading
Begin with low-pass filtering for each sensor vector. The following listener keeps the latest filtered gravity and magnetic data, then requests a heading only when both are available:
private val gravity = FloatArray(3)
private val magnetic = FloatArray(3)
private var haveGravity = false
private var haveMagnetic = false
override fun onSensorChanged(event: SensorEvent) {
when (event.sensor.type) {
Sensor.TYPE_ACCELEROMETER -> {
lowPass(event.values, gravity)
haveGravity = true
}
Sensor.TYPE_MAGNETIC_FIELD -> {
lowPass(event.values, magnetic)
haveMagnetic = true
}
else -> return
}
if (haveGravity && haveMagnetic) updateHeading()
}
private fun lowPass(input: FloatArray, output: FloatArray) {
for (i in output.indices) {
output[i] = 0.15f * input[i] + 0.85f * output[i]
}
}
The rotation matrix must also be remapped when the screen rotates. In portrait, use the X and Y axes; for 90-, 180- and 270-degree rotations, remap to Y/negative X, negative X/negative Y and negative Y/X respectively. Then convert the orientation’s azimuth from radians to a normalised degree value:
private fun updateHeading() {
val matrix = FloatArray(9)
if (!SensorManager.getRotationMatrix(matrix, null, gravity, magnetic)) return
val adjusted = FloatArray(9)
SensorManager.remapCoordinateSystem(
matrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, adjusted
)
val orientation = SensorManager.getOrientation(adjusted, FloatArray(3))
heading =
(Math.toDegrees(orientation[0].toDouble()).toFloat() + 360f) % 360f
}
For landscape support, choose the axis pair from the current display rotation inside updateHeading rather than hard-coding portrait.
Filtering makes the needle calmer, but averaging angles with ordinary arithmetic can cause a false swing from 359 to 1 degrees. Unwrap the difference around zero or use a circular moving average. An update rate around 10 to 15 times per second is usually responsive enough without making the display look frantic.
If true north is required, obtain coordinates with an appropriate location source and add the positive-east declination. Location access adds permission and privacy handling, so retain a magnetic-only mode when coordinates are unavailable:
val field = GeomagneticField(
latitude,
longitude,
altitude,
System.currentTimeMillis()
)
val trueBearing = (heading + field.declination + 360f) % 360f
Building a clear compass interface
A compass view needs a bezel labelled north, east, south and west plus a needle or rotating dial. Draw the north marker with Canvas.rotate(-heading): canvas angles turn clockwise, while the marker must move counter-clockwise as the phone’s heading increases. Confirm this relationship in portrait and landscape rather than assuming the default orientation.
Use a large degree readout and include the cardinal direction as text, such as “243° WSW”. Do not communicate direction through colour alone, and provide an accessibility description that changes with the bearing. A TextView is enough for an early version, while a custom View gives finer control over the marks, shadow and centre pin.
Calibration feedback should be based on the magnetometer’s accuracy callback. When accuracy is low, explain that the phone is near metal or a strong electrical source and invite the user to move it away. A remembered calibration offset can be stored in SharedPreferences. If the app also records readings, the site’s SQLite join example shows how calibration and reading records can be combined without duplicating data.
Testing the compass in Australian conditions
Test against a known mapped bearing at an open point in Sydney’s Centennial Park, then repeat with the phone held upright, flat and at several angles. Melbourne’s tram precincts and lifts can distort the field, while Sydney’s underground platforms can leave too little signal for a reliable comparison. During an arvo walk beside the Yarra, the result may differ from the same compass used inside a vehicle or beside steelwork.
Google Play is the primary Android storefront used by Australian consumers, so test on Samsung, Pixel and lower-memory models rather than one handset. A magnetic-only compass should work offline; users on metered mobile data should not need a network request just to turn the needle. Keep location optional and explain its purpose in the Play listing.
Practical release checks
- Compare the display with a trusted bearing at several open locations.
- Exercise portrait, landscape and reverse-portrait orientations.
- Stop sensor updates whenever the activity is paused.
- Show a warning when magnetometer accuracy is poor.
- Test without location permission and with location enabled.
- Make the needle, direction text and accessibility labels understandable without colour.
| Heading source | Sensors used | Main advantage | Main limitation | Best fit |
|---|---|---|---|---|
| Rotation vector | Magnetometer and gyroscope, depending on device | Smooth, tilt-compensated orientation | Less direct control over fusion | A polished everyday compass |
| Magnetic field plus gravity | Magnetometer and accelerometer | Explicit control over every calculation | Requires filtering and axis remapping | Learning and custom sensor logic |
| Movement over ground | GNSS receiver | Independent of nearby magnetic objects | Needs movement and a clear sky | Route or travel logging |