views:

259

answers:

2

Hi all,

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?

+2  A: 
// 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().

Lie Ryan
What's going on in the section "implement a SensorEventListener class" of your code? I'm somewhat new to Java, I haven't seen that syntax before.
Greg
@Greg: That's called anonymous class (you can google "anonymous class java"). SensortEventListener is an "interface", and we can write a class that "implements" an interface. Since this is only a small example, I used anonymous class; however, if your SensorEventListener class is more complex, you should use a named class instead.
Lie Ryan
+2  A: 

Have a look at the API demos. There is an application that has already been written which access the compass and accelerometer. Maybe that will give you a better idea on how you can go about your task.

you shall find it in /android-sdk-linux_86/samples/android-8/ApiDemos/src/com/example/android/apis/os/sensor.java

hope it helps.

Shouvik