为什么没有检测到网络连接更改?

时间:2013-12-28 04:07:12

标签: android cordova network-connection

我正在尝试在连接状态发生变化时显示并发出警报但我的代码根本没有效果(下面的警报没有被执行)。

就是这样:

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');

        document.addEventListener("online", onOnline, false);
        document.addEventListener("offline", onOffline, false); 
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }


};

function onOffline() {
    alert("on");
}

function onOffline() {
    alert("off");
}

我的PhoneGap版本是3.3.0-0.18.0。我的目标是Android,所以我生成了这样的项目:

phonegap create my-app
cd my-app
phonegap run android

我缺少什么?

1 个答案:

答案 0 :(得分:7)

从3.0版开始,您不必手动向AndroidManifest.xml添加权限。 在页面http://docs.phonegap.com/en/3.3.0/cordova_connection_connection.md.html#Connection上,您可以阅读:

从版本3.0开始,Cordova将设备级API实现为插件。使用命令行界面中描述的CLI插件命令为项目添加或删除此功能:

$ cordova plugin add org.apache.cordova.network-information

如果您不使用phonegap build service,则可以使用cordova代替phonegap(建立在cordova之上)。

希望这有帮助。