LibGDX - 检查罗盘是否需要校准

LibGDX - check if compass needs calibration

如何在LibGDX(在Android)中检查罗盘是否校准好。我已经找到了如何在原生 Android:

上执行此操作

In Android can I programmatically detect that the compass is not yet calibrated?

但无法找到是否在 LibGDX 中实施。

wiki 文章 Interfacing with platform specific code 中描述了您想要的内容。 LibGDX 没有任何功能,因为它不常见并且对其他后端没有任何意义。

core 模块中,您将拥有如下内容:

public interface GameListener {
    void calibrateCompassIfNeeded()
}

public class Application extends ApplicationAdapter {

    private GameListener listener;    

    public Application(GameListener listener) {
        this.listener = listener;
    }

    @Override
    public void create() {
        // Call listener.calibrateCompassIfNeeded() whenever needed.
    }

    public void onCompassChanged(float[] values) {
        // Do something...
    }
}

并且在 android 模块中:

public class AndroidLauncher extends AndroidApplication implements GameListener, SensorEventListener {
    private static final int COMPASS_ACCURACY_UNKNOWN = -1;

    private Application app;
    private int compassAccuracy = COMPASS_ACCURACY_UNKNOWN;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);

        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor compassSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        sensorManager.registerListener(this, compassSensor, SensorManager.SENSOR_DELAY_GAME)

        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        app = new Application(this);
        initialize(app, config);
    }

    @Override
    public void calibrateCompassIfNeeded() {
        if (compassAccuracy != COMPASS_ACCURACY_UNKNOWN && compassAccuracy < SENSOR_STATUS_ACCURACY_MEDIUM) {
            // Calibrate only if accuracy is below medium.
            // Show whatever is needed so user calibrates the compass.
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            app.onCompassChanged(event.values);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
       compassAccuracy = accuracy;
    }
}

我还没有尝试过,我以前也从未使用过指南针,但我很确定这会很好用。