Search code examples
androidcompass-geolocation

First Android App - How to Access the Compass


I'm making my first Android application. As a toy problem to learn the system I want to make a simple app that display as text which direction the phone is pointing using the built in compass.

How do I access the compass from my code, and have my code be aware of direction changes?

I believe I'll need the SensorManager class but I'm confused how to use it. How do I tell it I want the compass sensor? How do I tell it to do an action (update text) on a direction change?


Solution

  • // First, get an instance of the SensorManager
    SensorManager sMan = (SensorManager) 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() {
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // do things if you're interested in accuracy changes
        }
        public 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 code uses magnetic sensor, you obtain the Magnetic North, but if you need to calculate the True North, you would need to do some adjustments with GeomagneticField.getDeclination().