简体   繁体   中英

Cannot access accelerometer in Cordova Android app

I'm attempting to access navigator.accelerometer in my Cordova [3.3.1-0.1.2] Android app, and navigator.accelerometer is undefined when running in the Android [4.0.3] emulator.

I followed this tutorial when setting up the Cordova app: http://www.techariv.in/2013/08/creating-android-hello-cordova.html

I added the following in www/config.xml inside of <widget> :

<plugin name="Accelerometer" value="org.apache.cordova.AccelListener" />

I've also tried

<plugin name="Accelerometer" value="CDVAccelerometer" />

Additionally, I have the following in www/js/index.js (which does load an execute):

onDeviceReady: function() {
    app.receivedEvent('deviceready');

    alert(navigator.accelerometer);
    navigator.accelerometer.getCurrentAcceleration(function() {
        alert('success');
    }, function() {
        alert('fail');
    });
},

When the app runs, I get one alert which simply says "undefined." Neither callback to getCurrentAcceleration() is called.

Note that onDeviceReady() is called via

document.addEventListener('deviceready', this.onDeviceReady, false)

(this is the standard "Hello World" app with no modifications besides adding the alerts and the accelerometer callback.

Adding plugin record to config.xml is not enough for adding plugin to cordova application. Some native code should be installed and linked to navigator by cordova or phonegap cli.

Here is a guide .

See accessing the feature section.

As you may notice, cordova cli will handle modification of config.xml for you.

Anyway, I would recommend you using of this nice grunt plugin . It can easily manage phonegap plugins via PluginID, or url to it. You may find information for your plugin for such case here and more plugins here

This is how I was able to access the accelerometer on android.

Install device motion plugin cordova plugin add org.apache.cordova.device-motion

Then in the onDeviceReady callback:

window.addEventListener("devicemotion", deviceMotionUpdate, true);

function deviceMotionUpdate(e){
    console.log("x: ", e.accelerationIncludingGravity.x);
    console.log("y: ", e.accelerationIncludingGravity.y);
    console.log("z: ", e.accelerationIncludingGravity.z);
}

You might want to change the console.logs to alerts if you do not have remote debugging setup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM