Search code examples
angularjsiphonecordovaionic-frameworkcordova-plugins

Late broadcast from Network Information plugin Cordova/Ionic


Hi I had a lot of testing rounds on this but not able to get exact solution so posting for help.

I am having my app in Ionic not Ionic2

Using plugin for network is "Network Information" cordova-plugin-network-information 1.3.0 "Network Information" Link

Scenario:

When user minimizes app and goes to background and turn off the network source like WiFi, Mobile Data and comes back to app home page the plugin. methods returns true for network in first place and after some time getting Broadcast saying now network is offline

Expected behaviour:

Should receive Broadcast on turning network source like WiFi, Mobile Data On or Off, so I can handle in app.

My source code for Broadcast who responded to network events in $ionicPlatform.ready in app.js is mentioned below:

//listen for Online event
        $rootScope.$on('$cordovaNetwork:online', function (event, networkState) 
        {
            console.log("BR got inside online -- App " + networkState);
            $rootScope.isonlineState = true;
            console.log("BR got inside online getNetwork-- App " + $cordovaNetwork.getNetwork());
            console.log("BR got inside online isOnline-- App " + $cordovaNetwork.isOnline());
        })

    // listen for Offline event
    $rootScope.$on('$cordovaNetwork:offline', function (event, networkState) 
     {
        console.log("BR got inside offline  -- App " + networkState);
            $rootScope.isonlineState = false;
        console.log("BR got inside offline getNetwork-- App " + $cordovaNetwork.getNetwork());
        console.log("BR got inside offline isOnline-- App " + $cordovaNetwork.isOnline());
        })

I debugged this scenario so many times but still not able to get right behaviour only on iPhone.

Please share your experiences on this so would help me to solve the issue. Thanks in advance.


Solution

  • Finally after couple of days of struggle I figured out that there is no way in this plugin to notify you other than it's BrodcastReceivers, thats fine but When in off network your app comes from background to Foreground and you call APIs then you see your app's page is trying to call APIs(because plugin methods returning isOnline to true) but they should not as there is no network and after few seconds you receive Broadcast saying You are offline now.

    Solution

    So the best way is to call the update to your pages from Background to Foreground is from BroadcastReceiver.. call another your Local BrodacstReceiver to update the page based on network events.

    I posted question on Ionic forum as well but I didn't receive anything constructive.

    Hope this helps to other facing same issue and needs solutions on that... :)