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?
// 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()
.
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.
First you should check if a compass sensor is present on the system
PackageManager m = getPackageManager();
if(!m.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)) {
Log.d("COMPASS_SENSOR", "Device has no compass");
}
精彩评论