Skip to content

Instantly share code, notes, and snippets.

@shouse
Created October 26, 2017 15:16
Show Gist options
  • Select an option

  • Save shouse/531547d45ed8eb198c3170de671ac1e3 to your computer and use it in GitHub Desktop.

Select an option

Save shouse/531547d45ed8eb198c3170de671ac1e3 to your computer and use it in GitHub Desktop.
/*
* Below is the background service to monitor the health of the app internet connection.
* It'll set a variable to tell any other controller what's going on with the current connection.
* 1 = Everything's good.
* 2 = Poor connectivity, but still have a connection.
* 3 = We have internet, but are having problems with the API.
* 4 = No internet.
*/
function appConnectionHealth() {
connectionHealthApi = new Api();
// console.log('Checking connection health ...');
// First, check for internet.
if (!Ti.Network.online) {
console.log('No internet detected!');
return requeue(4);
}
// Second, check for access to the API and measure loadtime.
var startTime = new Date().getTime();
var webClient = Titanium.Network.createHTTPClient({
timeout: 10000
});
webClient.open("GET", connectionHealthApi.host);
webClient.send();
// Handles a success being returned.
webClient.onload = function () {
if (this.status == 200) {
var endTime = new Date().getTime();
var loadTime = endTime - startTime;
if (loadTime < 5000) {
requeue(1);
} else {
console.log('Poor connectivity detected!');
console.log('Load Time: ' + loadTime);
requeue(2);
}
} else {
requeue(3);
}
};
// Handles an error being returned.
webClient.onerror = function () {
console.log('onerror');
console.log('Status: ' + this.status);
console.log('Response: ' + this.responseText);
requeue(3);
};
// Re-queue to run again shortly.
function requeue(connectionStatus) {
if (connectionStatus != storage.get('connectionStatus')) {
Ti.App.fireEvent('connectionStateChange', {data: {connectionStatus: connectionStatus}});
}
storage.set('connectionStatus', connectionStatus);
setTimeout(function () {
appConnectionHealth();
}, config.get('APP_HEALTH_THREAD_TIME'));
}
};
appConnectionHealth();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment