通过Android中的Javascript访问加速度计?

Jef*_*amb 18 javascript android accelerometer

有没有办法在Android的浏览器上使用Javascript访问加速度计数据?我知道它支持"onorientationchange",但我想得到一切.

澄清:我问的是如何在网站上做到这一点,而不是原生应用.

Bam*_*rza 17

从ICS,Android 4.0开始,您可以通过JavaScript事件监听器使用"devicemotion"事件来访问加速度计数据.请参阅W3C文档,了解如何访问它 - http://dev.w3.org/geo/api/spec-source-orientation.html.

注 - W3C文档标题以"设备方向"命名,但规范确实包含"devicemotion"事件文档.


Joe*_*el 14

对此线程进行更新.

HTML5让别人这样做.检测加速度计是否存在很容易.

    if (window.DeviceMotionEvent == undefined) {
        //No accelerometer is present. Use buttons. 
        alert("no accelerometer");
    }
    else {
        alert("accelerometer found");
        window.addEventListener("devicemotion", accelerometerUpdate, true);
    }
Run Code Online (Sandbox Code Playgroud)

在您定义为接收加速度计事件的函数中,您可以查看该accelerationIncludingGravity成员.

function accelerometerUpdate(e) {
   var aX = event.accelerationIncludingGravity.x*1;
   var aY = event.accelerationIncludingGravity.y*1;
   var aZ = event.accelerationIncludingGravity.z*1;
   //The following two lines are just to calculate a
   // tilt. Not really needed. 
   xPosition = Math.atan2(aY, aZ);
   yPosition = Math.atan2(aX, aZ);
}
Run Code Online (Sandbox Code Playgroud)

更多信息可以在这里找到:http://dev.w3.org/geo/api/spec-source-orientation.html


sys*_*out 5

您可以尝试使用PhoneGap,它提供API以从javascript访问加速度计.

这里是文档.