Offline and online events not getting Called in cordova 3.5.0

梦想的初衷 提交于 2019-12-06 07:47:34

I had the same problem: the online/offline event was not firing, and sometimes when it went offline, the app crashed...

THE SOLUTION: - The appropriate permission tag must bem IMMEDIATELY after the tag , in the AndroidManifest.xml file... it may appear ridiculous, but otherwise the event was not firing.

In the end, your file will look like:

<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" android:windowSoftInputMode="adjustPan" package="br.com.burkard.app" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />

Scope.

document.addEventListener("offline", this.onOffline, false);
document.addEventListener("online", this.onOnline, false);

I avoid using the network types, as I found they do not work consistently on all platforms.

Instead I use:

 isOnline = function() {
    try {
    if (!navigator.onLine){
        return false;
    } else {
        return true;
    }
    }
    catch(e) {
        alert('An error has occurred: '+e.message);
    }
    };

I would do to things.

  • First add the online and offline eventlisteners only in the onDeviceReady function,
  • Second, add scope to the onOffline and onOnline method calls in the event listeners.

Something like this:

if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
    document.addEventListener('deviceready', this.onDeviceReady, false);
} else {
    this.onDeviceReady();
}

},

onDeviceReady: function() {
    StatusBar.overlaysWebView(false);
    app.receivedEvent('deviceready');

    document.addEventListener("offline", app.onOffline, false);
    document.addEventListener("online", app.onOnline, false);
},

onOnline:function(){
    console.log("Online");
}.
onOffline: function(){
    console.log("Offline");
},
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!