Coder Social home page Coder Social logo

network-connection-class's Introduction

Network Connection Class Network Connection Class

Network Connection Class is an Android library that allows you to figure out the quality of the current user's internet connection. The connection gets classified into several "Connection Classes" that make it easy to develop against. The library does this by listening to the existing internet traffic done by your app and notifying you when the user's connection quality changes. Developers can then use this Connection Class information and adjust the application's behaviour (request lower quality images or video, throttle type-ahead, etc).

Network Connection Class currently only measures the user's downstream bandwidth. Latency is also an important factor, but in our tests, we've found that bandwidth is a good proxy for both.

The Network Connection Class library takes care of spikes using a moving average of the incoming samples, and also applies some hysteresis (both with a minimum number of samples and amount the average has to cross a boundary before triggering a bucket change): Bandwidth Averaging

Integration

Download

Download the latest JARs or grab via Gradle:

compile 'com.facebook.network.connectionclass:connectionclass:1.0.1'

or Maven:

<dependency>
  <groupId>com.facebook.network.connectionclass</groupId>
  <artifactId>connectionclass</artifactId>
  <version>1.0.1</version>
</dependency>

Calculate Connection Class

Connection Class provides an interface for classes to add themselves as listeners for when the network's connection quality changes. In the subscriber class, implement ConnectionClassStateChangeListener:

public interface ConnectionClassStateChangeListener {
  public void onBandwidthStateChange(ConnectionQuality bandwidthState);
}

and subscribe with the listener:

ConnectionClassManager.getInstance().register(mListener);

Alternatively, you can manually query for the current connection quality bucket with getCurrentBandwidthQuality().

ConnectionQuality cq = ConnectionClassManager.getInstance().getCurrentBandwidthQuality();

The main way to provide the ConnectionClassManager data is to use the DeviceBandwidthSampler. The DeviceBandwidthSampler samples the device's underlying network stats when you tell it you're performing some sort of network activity (downloading photos, playing a video, etc).

// Override ConnectionClassStateChangeListener
ConnectionClassManager.getInstance().register(mListener);
DeviceBandwidthSampler.getInstance().startSampling();
// Do some downloading tasks
DeviceBandwidthSampler.getInstance().stopSampling();

If the application is aware of the bandwidth downloaded in a certain time frame, data can be added to the moving average using:

ConnectionClassManager.addBandwidth(bandwidth, time);

See the connectionclass-sample project for more details.

Improve Connection Class!

See the CONTRIBUTING.md file for how to help out.

License

Connection Class is BSD-licensed. We also provide an additional patent grant.

network-connection-class's People

Contributors

nipuns avatar rrong avatar seyelenteco avatar tasomaniac avatar zlern2k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

network-connection-class's Issues

The library doesn't listen to the existing internet traffic done by a specific app

Hi, Checking out 1.0.1 release branch.
In DeviceBandwidthSampler.java line 92
long newBytes = TrafficStats.getTotalRxBytes();

This method returns number of bytes received since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot.

It is not app specific as there might be another background task or sync service running/started by another app at the same time.

Connection class doesn't change even when offline

The connection class doesn't change from what it used to be, when the phone goes offline. I traced the issue to this in line 91 in ConnectionClassManager.java:

    //Ignore garbage values.
    if (timeInMs == 0 || (bytes) * 1.0 / (timeInMs) * BYTES_TO_BITS < BANDWIDTH_LOWER_BOUND) {
      return;
    }

Here, when bytes is 0 (because there's no byte diff), it just fails to add this bandwidth. Is this by design?

P.S: My app is running code from release 1.0.1 (commit).

Upload speed

Hi,
Nice API. Can I use it to sample upload speed as well? Actually I want to use it to profile download speed, upload speed, along with time stamp and GPS info and save to a .csv file. Does it allow me enough flexibility to do that?

Gradle error when importing the sample project

I have this error in gradle when I am importing the sample project to Android Studio.

Error:(16, 0) SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

Calculate upload speed

I could not figure out how to calculate the upload speed, Is there any way this is possible?

OutofMemoryException while sampling

Sampling using DeviceBandwidthSampler.getInstance().startSampling() leading to oom on several devices

Fatal Exception: java.lang.OutOfMemoryError
Failed to allocate a 12 byte allocation with 0 free bytes and 3GB until OOM
keyboard_arrow_up
android.os.StrictMode.allowThreadDiskReads (StrictMode.java:1022)
arrow_right
com.facebook.network.connectionclass.QTagParser.parseDataUsageForUidAndTag (SourceFile:75)
com.facebook.network.connectionclass.DeviceBandwidthSampler$SamplingHandler.addSample (SourceFile:117)
com.facebook.network.connectionclass.DeviceBandwidthSampler$SamplingHandler.handleMessage (SourceFile:100)
android.os.Handler.dispatchMessage (Handler.java:102)
android.os.Looper.loop (Looper.java:148)
android.os.HandlerThread.run (HandlerThread.java:61)

Cutomization of bandwidth

Can we have way to customize bandwidth range instead of fixed? So developer can customize it like for poor under 50Kbps depends on their need.

Contribution page 'pull request' guidelines can be more clear and better formatted

To sum up the bug
a. There is room for Formatting improvement
b. Point 4 "Make sure your code lints" makes lesser sense than
"Make sure your code lints (grunt lint) - we've done our best to make sure these rules match our internal linting guidelines." (This test is from react project)

Currently, pull request guidelines looks like blob of text.
"We actively welcome your pull requests. 1. Fork the repo and create your branch from master. 2. If you've added code that should be tested, add tests 3. If you've changed APIs, update the documentation. 4. Ensure the test suite passes. 5. Make sure your code lints. 6. If you haven't already, complete the Contributor License Agreement ("CLA").
Link: https://github.com/facebook/network-connection-class/blob/master/CONTRIBUTING.md#pull-requests

I suggest we make it clearer and more neater like in react project
eg: https://github.com/swannodette/react/blob/master/CONTRIBUTING.md#pull-requests

Speed in Mbps

Hi all I am using this library to get the speed in Mbpsin my app. the function getDownloadKBitsPerSecond() resturns me unexpected values. For instance speeds higher than my internet connection even. I am just trying to download an image file as a task .Please help me out with what I am doing wrong or I can get connection speed. I am not using wifi but mobile data instead.

Will appreciate help in advance.

Thanks
Sal

startSampling stopSampling for every network request?

Currently I develop a movie app which loads a lot of cover images. Especially in the overview where I show the cover images in a grid and the app has to load lots of images in parallel.

Should I start / stop sampling for every image request or can I start sampling with app start and stop it when the app goes to background?

Currently I have a NetworkInterceptor for OkHttp to do start / stop but I'm not sure if it is a good idea :-(

private static class DeviceBandwidthSamplerInterceptor implements Interceptor {

    private final DeviceBandwidthSampler deviceBandwidthSampler;

    DeviceBandwidthSamplerInterceptor(final DeviceBandwidthSampler deviceBandwidthSampler) {
        this.deviceBandwidthSampler = deviceBandwidthSampler;
    }

    @Override
    public Response intercept(final Chain chain) throws IOException {
        deviceBandwidthSampler.startSampling();
        final Response response = chain.proceed(chain.request());
        deviceBandwidthSampler.stopSampling();
        return response;
    }
}

Question: Is it possible to use it with WebSocket?

I have a WebSocket connection in my app. I call DeviceBandwidthSampler.getInstance().startSampling() right after the connection is established but my ConnectionClassStateChangeListener is never called. :(
If I use the Sampler before any http request, it works as in the example.

method "mapBandwidthQuality" doesn't receive any argument in double average

Hello,
I have to develop an android application to check internet quality like speed, ping , jitter
I am using this library. when i run my application i always get first return . It means double average is not having any values so loop is not executing.
For Example :
case 1. output "Negative"

private ConnectionQuality mapBandwidthQuality(double average) {
if (average < 0) {
return ConnectionQuality.NEGATIVE;
}
if (average < DEFAULT_POOR_BANDWIDTH) {
return ConnectionQuality.POOR;
}
if (average < DEFAULT_MODERATE_BANDWIDTH) {
return ConnectionQuality.MODERATE;
}
if (average < DEFAULT_GOOD_BANDWIDTH) {
return ConnectionQuality.GOOD;
}
return ConnectionQuality.EXCELLENT;
}

case 2. output "GOOD"

private ConnectionQuality mapBandwidthQuality(double average) {
if (average < DEFAULT_GOOD_BANDWIDTH) {
return ConnectionQuality.GOOD;
}
if (average < 0) {
return ConnectionQuality.NEGATIVE;
}
if (average < DEFAULT_POOR_BANDWIDTH) {
return ConnectionQuality.POOR;
}
if (average < DEFAULT_MODERATE_BANDWIDTH) {
return ConnectionQuality.MODERATE;
}

    return ConnectionQuality.EXCELLENT;
}

What is the possible solution please .
optional solution to create app to check internet quality in android is also appreciated
Thanks
Jitendra

ConnectionQuality is always unknown

I tried doing the following:

`ConnectionQuality cq = ConnectionClassManager.getInstance().getCurrentBandwidthQuality();
            switch (cq) {
                case EXCELLENT: //Bandwidth over 2000 kbps.
                    Toast.makeText(MainActivity.this, "EXCELLENT", Toast.LENGTH_SHORT).show();
                    break;
                case GOOD: //Bandwidth between 550 and 2000 kbps.
                    Toast.makeText(MainActivity.this, "GOOD", Toast.LENGTH_SHORT).show();
                    break;
                case MODERATE: //Bandwidth between 150 and 550 kbps.
                    Toast.makeText(MainActivity.this, "MODERATE", Toast.LENGTH_SHORT).show();
                    break;
                case POOR: //Bandwidth under 150 kbps.
                    Toast.makeText(MainActivity.this, "POOR", Toast.LENGTH_SHORT).show();
                    break;
                case UNKNOWN: //unknown
                    Toast.makeText(MainActivity.this, "UNKNOWN", Toast.LENGTH_SHORT).show();
                   break;

              }`

And keep getting Unknown.

IndexOutOfBoundsException in ConnectionClassManager

ConnectionClassManager sometimes throws IndexOutOfBoundException here: https://github.com/facebook/network-connection-class/blob/master/connectionclass/src/main/java/com/facebook/network/connectionclass/ConnectionClassManager.java#L245

Access to mListenerList is not synchronized and it is accessed from at least two different threads: ParseThread handler thread and thread where register/remove listener methods called (usually main thread).

This sometimes causes crashes:

Fatal Exception: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
       at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
       at java.util.ArrayList.get(ArrayList.java:308)
       at com.facebook.network.connectionclass.ConnectionClassManager.notifyListeners(ConnectionClassManager.java:1205)
       at com.facebook.network.connectionclass.DeviceBandwidthSampler$SamplingHandler.addSample(DeviceBandwidthSampler.java:121)
       at com.facebook.network.connectionclass.DeviceBandwidthSampler$SamplingHandler.handleMessage(DeviceBandwidthSampler.java:100)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:136)
       at android.os.HandlerThread.run(HandlerThread.java:61)

Not listening for network bandwidth when using with socket in a Service

HI
I am using this library in one my background service. I have a separate handler thread which will queue up the messages. I am doing a network action in "handlemessage". I am calling startSampling() and calling stopSampling() after the network communication is completed.

My netwok coomunication is based on SSL socket.
But my Listener is never invoked. I am doing ConnectionClassManager.getInstance().register in the onCreate of my Service.

Did this library cant monitor the network communication in TCP

[Question] Is this project still maintained?

Hello! I'm just wondering, is this cool project still maintained?

Last commit dated 9. Sep 2015, there are 19 issues opened, and some users complaining that library doesn't work on newer Android version.

Do you have any plans to continue to support this cool library?

how to get all the parameter speed (KB/s) and time (minutes.second)

How do i get all the parameter speed and time? how much the data speed (KB/s) and time (minutes.second) for some image. the app just says: EXCELLENT. which is did not says something detail. i need the parameter data time and speed. thanks in advanced if you someone reply.

always showing internet quality POOR

DeviceBandwidthSampler.getInstance().startSampling();
// Calling API network operation and after success or error from volley response
DeviceBandwidthSampler.getInstance().stopSampling();
mUtils.showInternetQualityIfPoor(); // Now checking bandwidth and showing message

even though when I was in Very god internet quality, it is always showing POOR connection, help me out how can I modify to get exact connection quality

Regards
Vinod

ConnectionClassManager.getDownloadKBitsPerSecond() returns bits/second instead?

ConnectionClassManager.getDownloadKBitsPerSecond() returns ExponentialGeometricAverage.getAverage(). Each measurement used to determine the average is converted to bits per second by ConnectionClassManager.addBandwidth(). So is getDownloadKBitsPerSecond() misnamed?

ConnectionClassManager.addBandwidth() -
double bandwidth = (bytes) * 1.0 / (timeInMs) * BYTES_TO_BITS;
mDownloadBandwidth.addMeasurement(bandwidth);

Bug: StartSampling updates mLastTimeReading while not make any read

If mHandler will start execute addSample() at least 1ms after updating mLastTimeReading in startSampling() then IF in addSample will not work and we will add sample with incorrectly small time

if (timeInMs == 0 || ...

public void startSampling() { if (mSamplingCounter.getAndIncrement() == 0) { mHandler.startSamplingThread(); mLastTimeReading = SystemClock.elapsedRealtime(); } }

[Question] What is the approriate value of network connection timeout

I'm applying your library into my application. My application mostly fetches images from server.
I wanna to know what is the network connection timeout value for each network quality?
How many network threads do you set?
Sorry that it seems not be related to this library. Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.