Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get Connection Strength in Phonegap

I am working on a phonegap application. I want to sync the data into application from the server, but it needs's a good connection strength.So I need to find out connection strength of the connection.

There are lots of documentation of internet to find connection type using phonegap, but I can't find any help regarding connection strength

Is there any way to find the connection strength in phonegap, I don't want to use any native platform code cause it will bw working on many platforms, So is there any way to find out the connection(2g, 3g, 4g, wifi etc...) strength in phonegap????

like image 587
Rohit Avatar asked Oct 21 '22 06:10

Rohit


1 Answers

There is no any standard way find out connection strength in android too, So I just use a javascript code to get the speed of internet connection, There is no issue with any platform android, ios or windows phone 8 etc, No need to develop a separate plugin for each platform.

Just use the following scripts :

var downloadSize = 244736;
var imageAddr = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg" + "?n=" + Math.random();
var startTime, endTime = 0;
var download = new Image();
download.onload = function () {
    endTime = ( new Date() ).getTime();
    showResults( startTime, endTime, imageAddr, downloadSize );
};

startTime = ( new Date() ).getTime();
download.src = imageAddr;

function isConnected() {
    var xhr = new XMLHttpRequest();
    var file = "http://api.androidhive.info/music/images/adele.png";
    var r = Math.round( Math.random() * 10000 );
    xhr.open( 'HEAD', file + "?subins=" + r, false );
    try {
        xhr.send();
        if ( xhr.status >= 200 && xhr.status < 304 ) {
            return true;
        } else {
            return false;
        }
    } catch ( e ) {
        return false;
    }
};

function showResults( startTime, endTime, imageAddr, downloadSize ) {
    if ( isConnected() ) {
        var duration = ( endTime - startTime ) / 1000; //Math.round()
        var bitsLoaded = downloadSize * 8;
        var speedBps = Number( ( bitsLoaded / duration ).toFixed( 2 ) );
        var speedKbps = Number( ( speedBps / 1024 ).toFixed( 2 ) );
        var finalSpeed = ( speedKbps / 10 );

        if ( finalSpeed < 40 ) {
            // Slow Internet

        } else if ( finalSpeed >= 40 && finalSpeed < 80 ) {
            // Avg Internet

        } else if ( finalSpeed >= 80 ) {
            // Fast Internet
        }
    } else {
        //No intenet
    }
}
like image 70
Rohit Avatar answered Oct 31 '22 11:10

Rohit