First Android App - How to Access the Compass

I am making my first Android app. As a toy problem, in order to study the system, I want to create a simple application displayed as text, in the direction the phone is pointing, using the built-in compass.

How can I access the compass from my code and find out that my code knows the direction changes?

I believe that I will need the SensorManager class , but I'm confused about how to use it. How can I say that I need a compass sensor? How can I say to perform an action (update text) when changing directions?

+3
source share
3 answers
// 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);

, , ; , , . , True North Magnetic North. , , True North, GeomagneticField.getDeclination().

+11

API. , , . , , .

:

/android-sdk-linux_86/samples/android-8/ApiDemos/src/com/example/android/apis/os/sensor.java

, .

+5

,

PackageManager m = getPackageManager();
if(!m.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)) {
        Log.d("COMPASS_SENSOR", "Device has no compass");
}
0
source

Source: https://habr.com/ru/post/1765391/


All Articles