Cordova罗盘API(navigator.compass.watchHeading)不工作(错误代码3)

Cordova compass API (navigator.compass.watchHeading) not working (error code 3)

本文关键字:工作 错误代码 compass 罗盘 API navigator Cordova watchHeading      更新时间:2023-09-26

我正试图使用cordova指南针运行一个示例应用程序,但每次调用错误回调时都会返回错误代码3。

我使用cordova V4.0,当然我添加了插件org.apache.cordova.device-orientation

<!DOCTYPE html>
<html>
  <head>
    <title>Compass Example</title>
    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">
    // The watch id references the current `watchHeading`
    var gWatchID = null;
    // Wait for device API libraries to load
    document.addEventListener("deviceready", onDeviceReady, false);
    // device APIs are available
    function onDeviceReady() {
        startWatch();
    }
    // Start watching the compass
    function startWatch() {
        // Update compass every 3 seconds
        var options = { frequency: 3000 };
        if (!gWatchID)
            gWatchID = navigator.compass.watchHeading(onSuccess, onError, options);
    }
    // Stop watching the compass
    function stopWatch() {
        if (gWatchID) {
            navigator.compass.clearWatch(watchID);
            gWatchID = null;
        }
    }
    // onSuccess: Get the current heading
    function onSuccess(heading) {
        var element = document.getElementById('heading');
        element.innerHTML = 'Heading: ' + heading.magneticHeading;
    }
    // onError: Failed to get the heading
    function onError(compassError) {
        alert('Compass error: ' + compassError.code);
    }
    </script>
  </head>
  <body>
    <div id="heading">Waiting for heading...</div>
    <button onclick="startWatch();">Start Watching</button>
    <button onclick="stopWatch();">Stop Watching</button>
  </body>
</html>

应用程序已成功构建、部署和启动。但当它启动时,只显示错误代码3。

根据文档,只定义了两个错误代码:CompassError.COMPASS_INTERNAL_ERR=0;CompassError.COMPASS_NOT_SUPPORTED=20;

所以我想知道错误代码3是什么意思?我做错了什么?

谢谢你的回答,Dante

您的设备没有磁传感器,或者供应商没有在操作系统中实现对它的支持。

查看面向设备的插件的Android源代码,启动代码是这样写的(为简洁起见进行了修改):

List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
// If found, then register as listener
if (list != null)
    this.setStatus(CompassListener.STARTING);
// If error, then set status to error
else
    this.setStatus(CompassListener.ERROR_FAILED_TO_START);

不确定他们为什么在那里编写自己的错误代码(public static int ERROR_FAILED_TO_START = 3),但实际上他们应该按照文档中的定义报告COMPASS_NOT_SUPPORTED