[英]Phonegap events online/offline not working
我正在使用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);
}
};
謝謝你的建議
如果要顯示在線/離線狀態,則需要首先使用命令提示符添加網絡信息插件
$ 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
您應該將Connection插件添加到項目中,然后將觸發此事件。
添加Connection插件使用以下命令:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.