First Android Application – how to access the compass

I'm making my first Android application. As a toy of the learning system, I want to make a simple application that uses the built-in compass to display the text in which direction the mobile phone points

How do I access the compass from my code and let my code know the direction change?

I believe I need the sensormanager class, but I'm confused about how to use it. How can I say I want a compass sensor? How do I tell it to take action on a direction change (update text)?

resolvent:

// 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);

But please note that this is actually a magnetic sensor; Therefore, if there is magnetic field interference around you, it may point in the wrong direction. In addition, you need to understand the difference between true north and magnetic north. Since this code uses magnetic sensors, you get the magnetic north, but if you need to calculate true north, you need to use geomagneticfield. Getdeclination() to make some adjustments

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>