Phonegap事件在线/离线不工作

我正在使用phonegap(cordova)3.0.0编写应用程序,而“在线”和“离线”事件不起作用。 当我尝试事件“简历”,这个事件是好的。 我正在使用XCode 4.5和IOS。

这是我phonegap项目的主要JavaScript文件:

var app = { 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); document.addEventListener('online', this.onDeviceOnline, false); document.addEventListener('resume', this.onDeviceResume, false); }, onDeviceReady: function() { app.receivedEvent('deviceready'); }, onDeviceOnline: function() { app.receivedEvent('deviceonline'); }, onDeviceResume: function() { app.receivedEvent('deviceresume'); }, 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); } }; 

感谢您的build议

如果要显示在线/离线状态,则需要先使用命令提示符添加networking信息插件

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

添加该插件后,您的在线/离线事件应该工作,它为我工作正常

这些事件必须在“onDeviceReady”内部进行绑定,它们在DeviceReady事件之前不会工作。 选中此事件一旦deviceready事件触发,附加一个事件监听器

 bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); document.addEventListener('resume', this.onDeviceResume, false); }, onDeviceReady: function() { app.receivedEvent('deviceready'); document.addEventListener('online', this.onDeviceOnline, false); }, 

请注意,在应用程序启动时,线上/离线事件不会被触发,这些事件只有在连接状态改变时才会被触发。 比方说,当应用程序启动在线模式,直到它离线,脱机事件将不会触发,在线事件相同。

要检查当前的连接,您需要使用下面的代码

 onDeviceReady: function() { app.receivedEvent('deviceready'); document.addEventListener('online', this.onDeviceOnline, false); if((navigator.network.connection.type).toUpperCase() != "NONE" && (navigator.network.connection.type).toUpperCase() != "UNKNOWN") { this.onDeviceOnline(); } } 

在corodova(不是phonegap)中,你必须以这种方式添加插件:
cordova plugin add org.apache.cordova.network-information

你应该添加连接插件到你的项目,然后这个事件将被解雇。

添加连接插件使用以下命令:

 CMD> phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-network-information.git 

在phonegap文件夹项目中:

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

index.js

 var app = {}; app.initialize = function() { document.addEventListener("online", function(){alert('online : true') }, false); document.addEventListener("offline", function(){alert('online : false') }, false); }; 

index.html ,某处:

 <script type="text/javascript"> app.initialize(); </script>