适用于Android的PhoneGap加速度计应用程序像疯了一样滞后,我的代码有什么问题?



我使用的是一个由PhoneGap编译并部署到Android的示例应用程序。明显滞后——我的刷新时间设置为100毫秒,但你可以感觉到加速度读数只会以一种相当"跳跃"的方式每1-2秒更新一次。这款手机是一款运行android 2.xx操作系统的单核HTC手机。(没有更多细节-现在没有电话)。

加速示例

<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
var watchID = null;
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready, start watching
function onDeviceReady() {
    startWatch();
}
// Start watching the acceleration
function startWatch() {
    // Update acceleration every 3 seconds
    var options = { frequency: 100};
    watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, 
         options);
}
// Stop watching the acceleration
function stopWatch() {
    if (watchID) {
        navigator.accelerometer.clearWatch(watchID);
        watchID = null;
    }
}
// onSuccess: Get a snapshot of the current acceleration
function onSuccess(acceleration) {
    var element = document.getElementById('accelerometer');
    element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
                        'Acceleration Y: ' + acceleration.y + '<br />' +
                        'Acceleration Z: ' + acceleration.z + '<br />' + 
                        'Timestamp: '      + acceleration.timestamp + '<br />';
}
// onError: Failed to get the acceleration
//
function onError() {
    alert('oooops!');
}
</script>

正在等待加速度计。。。停止监视

我不知道这是否有帮助,但似乎只使用值更改innerHTML而不是整个string可以获得更好的性能。

查看此jsperf:http://jsperf.com/innerhtml-perf

您是在设备上测试还是在模拟器上测试?

模拟器在osx上总是有一个滞后。

你可以尝试为模拟器分配更多的内存,或者寻找一种更有效的方法来编码你的应用程序。

最新更新