Nico Hernandez Torres Nico Hernandez Torres - 1 year ago 76
Android Question

Check internet connection constantly

I'm developing an Android app with ionic framework and need to check the internet connection, but steadily. For example if the user is logged in and then has no connection, I would like to display a message or any message. I had thought something like

<div class="bar bar-subheader" id="alerta_no_internet" ng-show="!online">
<p>Not connected to Internet </p>

What they do not do is any service or if there is something to be constantly asking about the connection.

Answer Source

There are a few ways of going about this:

  1. You can store an asset (maybe a 1px x 1px GIF image) on your server and constantly keep polling for this (continuous requests every x seconds). Of course you wanna make sure this image is not cached. If the request fails, you can assume that the network is not available. This is easy to implement, but is not efficient because polling sends tons of HTTP headers over the wire.
  2. This is much more efficient - implement a WebSocket connection in your client and server and open a socket upon opening the app. If the socket drops, you can display the Connectivity Lost message. This doesn't require sending of HTTP requests repeatedly. This is much more efficient, but more work will be required to implement this.

You can write services for either of these in Ionic.

At it's simplest, option #1 can be:

setInterval(ajaxCall, 3000); //3000 MS == 3 sec

function ajaxCall() {
  $.ajax('/testConnectivityUrl').then(function(response) {
    console.log("Still connected");
  }, function(err) {
    console.log("Lost connection");

I've used jQuery, but you can do this with vanilla JS or Angular or Ionic services or factories.