将环境光传感器添加到cordova-2.5.0.js - phonegap中

时间:2013-04-21 12:39:15

标签: android cordova phonegap-plugins

我必须使用phongap开发一个Android应用程序,从设备中检索传感器数据。

我必须听的传感器之一是环境光传感器。这个传感器在phoneGap中没有实现,所以我必须将它作为插件添加到PhoneGap。

我知道如何添加插件,我知道如何从Java访问ALS数据 - 但为了确保我正在实现它,我想实现它,因为PhoneGap实现了其他传感器,如Accelerometer。因此我在java中编写了一个ALSManager类,我发现这里实现了Accelerometer:

  

https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/AccelListener.java

并添加了lightSensor和lightValues模块,如加速器模块和加速模块。

但是当我运行此应用程序时,我收到以下错误消息:

  

TypeError:Object#没有方法'getCurrentLight'

(在lightSensor模块中我有getCurrentLight方法)。

有没有人可以建议我缺少什么?或者我该怎么做?

提前致谢,


我在cordova-2.5.0.js中添加的代码。如果这还不够,请告诉我:

    // file: lib/common/plugin/LightValues.js
define("cordova/plugin/LightValues", function(require, exports, module) {

var Acceleration = function(lux, timestamp) {
    this.lux = lux;
    this.timestamp = timestamp || (new Date()).getTime();
};

module.exports = LightValues;

});
// file: lib/common/plugin/lightSensor.js
define("cordova/plugin/lightSensor", function(require, exports, module) {

/**
 * This class provides access to device accelerometer data.
 * @constructor
 */
var argscheck = require('cordova/argscheck'),
    utils = require("cordova/utils"),
    exec = require("cordova/exec"),
    LightValues = require('cordova/plugin/LightValues');

// Is the accel sensor running?
var running = false;

// Keeps reference to watchAcceleration calls.
var timers = {};

// Array of listeners; used to keep track of when we should call start and stop.
var listeners = [];

// Last returned acceleration object from native
var light = null;

// Tells native to start.
function start() {
    exec(function(a) {
        var tempListeners = listeners.slice(0);
        light = new LightValues(a.lux, a.timestamp);
        for (var i = 0, l = tempListeners.length; i < l; i++) {
            tempListeners[i].win(light);
        }
    }, function(e) {
        var tempListeners = listeners.slice(0);
        for (var i = 0, l = tempListeners.length; i < l; i++) {
            tempListeners[i].fail(e);
        }
    }, "Light", "start", []);
    running = true;
}

// Tells native to stop.
function stop() {
    exec(null, null, "Light", "stop", []);
    running = false;
}

// Adds a callback pair to the listeners array
function createCallbackPair(win, fail) {
    return {win:win, fail:fail};
}

// Removes a win/fail listener pair from the listeners array
function removeListeners(l) {
    var idx = listeners.indexOf(l);
    if (idx > -1) {
        listeners.splice(idx, 1);
        if (listeners.length === 0) {
            stop();
        }
    }
}

var lightSensor = {
    /**
     * Asynchronously acquires the current acceleration.
     *
     * @param {Function} successCallback    The function to call when the acceleration data is available
     * @param {Function} errorCallback      The function to call when there is an error getting the acceleration data. (OPTIONAL)
     * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
     */
    getCurrentLight: function(successCallback, errorCallback, options) {
        //argscheck.checkArgs('fFO', 'lightSensor.getCurrentLight', arguments);

        var p;
        var win = function(a) {
            removeListeners(p);
            successCallback(a);
        };
        var fail = function(e) {
            removeListeners(p);
            errorCallback && errorCallback(e);
        };

        p = createCallbackPair(win, fail);
        listeners.push(p);

        if (!running) {
            start();
        }
    },

    /**
     * Asynchronously acquires the acceleration repeatedly at a given interval.
     *
     * @param {Function} successCallback    The function to call each time the acceleration data is available
     * @param {Function} errorCallback      The function to call when there is an error getting the acceleration data. (OPTIONAL)
     * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
     * @return String                       The watch id that must be passed to #clearWatch to stop watching.
     */
    watchLight: function(successCallback, errorCallback, options) {
        //argscheck.checkArgs('fFO', 'lightSensor.watchLight', arguments);
        // Default interval (10 sec)
        var frequency = (options && options.frequency && typeof options.frequency == 'number') ? options.frequency : 10000;

        // Keep reference to watch id, and report accel readings as often as defined in frequency
        var id = utils.createUUID();

        var p = createCallbackPair(function(){}, function(e) {
            removeListeners(p);
            errorCallback && errorCallback(e);
        });
        listeners.push(p);

        timers[id] = {
            timer:window.setInterval(function() {
                if (light) {
                    successCallback(light);
                }
            }, frequency),
            listeners:p
        };

        if (running) {
            // If we're already running then immediately invoke the success callback
            // but only if we have retrieved a value, sample code does not check for null ...
            if (light) {
                successCallback(light);
            }
        } else {
            start();
        }

        return id;
    },

    /**
     * Clears the specified accelerometer watch.
     *
     * @param {String} id       The id of the watch returned from #watchAcceleration.
     */
    clearWatch: function(id) {
        // Stop javascript timer & remove from timer list
        if (id && timers[id]) {
            window.clearInterval(timers[id].timer);
            removeListeners(timers[id].listeners);
            delete timers[id];
        }
    }
};

module.exports = lightSensor;

});

2 个答案:

答案 0 :(得分:0)

我想问题可能是您要将插件代码添加到cordova-2.5.0.js文件中。相反,您应该为每个JavaScript文件创建一个独立的JS文件,然后在HTML页面中为那些要使用该功能的文件创建cordova.require()

因此,在www文件夹中的某处创建LightValues.jsLightSensor.js作为单独的文件。然后在HTML文件中,确保包含JS文件:<script type="text/javascript" src="path-to-lightSensor.JS-file">(您只需要包含这一个文件,因为它需要()是第二个文件。)

接下来,在deviceReady()功能中,您可以使用var lightSensor = cordova.require("cordova/plugin/lightSensor")调用光线传感器。请注意, cordova / plugin / lightSensor 不是JS文件的路径,而是您在编写插件时在define()部分中声明的模块名称。

在此之后你应该可以调用lightSensor.getCurrentLight()。如果你console.log(lightSensor),你会期望看到你写的所有可用方法。

请注意,cordova.requirecordova.define在cordova-2.5中工作并不是肯定的。我希望他们能做到this page sort of suggests it may not be supported until 2.6。如果在分割文件后遇到问题,可能是因为这个原因。

答案 1 :(得分:0)

我刚开发了一个光传感器插件,幸运的是成功了。我刚刚阅读了上面的代码并发现了一些关于标识符的小错误,例如“var Acceleration = function(lux,timestamp)”变量应该是LightValues而不是Acceleration。因此,请首先检查代码以消除一些重要错误。然后,我首先使用“lux”作为变量的名称,但在调试程序时我得到了一个未定义的光值。所以我将“lux”改为“x”,它确实有效!

应该注意6个文件:“LightListener.java”,“LightValues.js”,“LightSensor.js”,“cordova_plugin.js”,“index.html”和“config.xml”。如果配置所有6个文件,程序应该可以正常工作。