How to show a slow internet connection to the user when the network is connected Note: Not a network type (2G,3G,4G, WIFI)
9 Answers
Determining your Network Speed - (Slow Internet Speed)
Using NetworkInfo class, ConnectivityManager and TelephonyManager to determine your Network Type.
Download any file from the internet & calculate how long it took vs number of bytes in the file. ( Only possible way to determine Speed Check )
I have tried the below Logic for my projects, You have also look into this, Hope it helps you.
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
NetworkCapabilities nc = cm.getNetworkCapabilities(cm.getActiveNetwork());
int downSpeed = nc.getLinkDownstreamBandwidthKbps();
int upSpeed = nc.getLinkUpstreamBandwidthKbps();
-
2
-
7
-
2getLinkUpstreamBandwidthKbps and getLinkDownstreamBandwidthKbps in differente network always return same value. Why? Jan 23, 2020 at 13:22
-
6I too got the same values. I think this will not work, as it may only return the maximum bandwidth supported by the network. In my case, it returns 1048576, i.e. 1Gbps, that is not possible in the network to which I connected. Second thing, the class name "NetworkCapabilities" itself says that capabilities of the network, so it's telling the maximum capabilities of that network. Mar 3, 2020 at 12:36
-
3This does not work as they have said it returns the maximum upload and download speed of the network Apr 19, 2021 at 6:52
Check internet speed for mobile network to use this code
ConnectivityManager connectivityManager = (ConnectivityManager)this.getSystemService(CONNECTIVITY_SERVICE);
NetworkCapabilities nc = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
var downSpeed = nc.getLinkDownstreamBandwidthKbps();
var upSpeed = nc.getLinkUpstreamBandwidthKbps();
If check internet speed for wifi network to use this code
public int getWifiLevel()
{
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int linkSpeed = wifiManager.getConnectionInfo().getRssi();
int level = WifiManager.calculateSignalLevel(linkSpeed, 5);
return level;
}
And more details refer this link
https://android.jlelse.eu/designing-android-apps-to-handle-slow-network-speed-dedc04119aac
I hope this can help you!
Thank You.
Requires minimum api:21. I use ConnectivityManager
combined with NetworkCapabilities
to get both the downstream and upstream bandwidth. Works just fine. You can decide whether speed is 2G,3G or 4G level based on the speed in kbps.
ConnectivityManager cm = (ConnectivityManager)this.getSystemService(CONNECTIVITY_SERVICE);
NetworkCapabilities nc = cm.getNetworkCapabilities(cm.getActiveNetwork());
var downSpeed = nc.getLinkDownstreamBandwidthKbps();
var upSpeed = nc.getLinkUpstreamBandwidthKbps();
- 2G GSM ~14.4 Kbps
- G GPRS ~26.8 Kbps
- E EDGE ~108.8 Kbps
- 3G UMTS ~128 Kbps
- H HSPA ~3.6 Mbps
- H+ HSPA+ ~14.4 Mbps-23.0 Mbps
- 4G LTE ~50 Mbps
- 4G LTE-A ~500 Mbps
Downloading a file is over-engineering the solution because after all, you aren't responsible for the users internet connection - they are (or rather their service provider is)! Giving them info based on their current status is more than enough for most use cases. This gives you a speedy way of checking current link speed before performing operations.
-
-
i was pretty sure of the answer att, feel free to edit it with a source if it's incorrect now Sep 12 at 0:38
UPDATE - DEPRECATED LIBRARY - no longer mainteined
original post:
You can use Network Connection Class by Facebook.
Its ConnectionClassStateChangeListener has a method called onBandwidthStateChange
that returns an instance of ConnectionQuality class:
public interface ConnectionClassStateChangeListener {
public void onBandwidthStateChange(ConnectionQuality bandwidthState);
}
ConnectionQuality class is an enum class defined as below:
public enum ConnectionQuality {
/**
* Bandwidth under 150 kbps.
*/
POOR,
/**
* Bandwidth between 150 and 550 kbps.
*/
MODERATE,
/**
* Bandwidth between 550 and 2000 kbps.
*/
GOOD,
/**
* EXCELLENT - Bandwidth over 2000 kbps.
*/
EXCELLENT,
/**
* Placeholder for unknown bandwidth. This is the initial value and will stay at this value
* if a bandwidth cannot be accurately found.
*/
UNKNOWN
}
-
7Sorry for the downvote :(. The library you pointed to hasn't been updated since 2015 and has reported issues with Android 9+. I would advise AGAINST using this library unless it's updated in the future (if it ever is, I'll remove my downvote. Promise :) )– Psest328Jan 16, 2020 at 13:57
-
i did converted this repo into kotlin and it's work in android 10. check it out here Jun 9, 2021 at 10:07
-
-
1
You can't directly check it.
However, you could either ping a server and see if the response takes very long or doesn't come back at all.
You could also do a speedtest. In most applications this would not make much sense though, because it's a hog on the user's data.
-
-
A code snippet for pinging? Or do you mean one for a speedtest to then calculate the download kbps?– jalakoDec 19, 2020 at 11:49
The most basic thing you can do is to probe an URL whose uptime is almost 100% like, let's say, www.google.com
. From the time you start the request, to the time it has completed, you can just measure the amount of data you have downloaded for the request. So you have the data (space) and time spent. Just divide space by time to get network speed. This is somewhat imprecise, because it also depend on the URL you probe.
It seem that android doesn't allow this directly. You can try to download some file to determine the speed of your internet. Below are the list of the connection qualities:
- POOR // Bandwidth under 150 kbps.
- MODERATE // Bandwidth between 150 and 550 kbps.
- GOOD // Bandwidth over 2000 kbps.
- EXCELLENT // Bandwidth over 2000 kbps.
- UNKNOWN // connection quality cannot be found.
You can check detail in this article https://android.jlelse.eu/designing-android-apps-to-handle-slow-network-speed-dedc04119aac
Get network speed and network type
class NetworkUtils {
companion object {
// returns 102 Mbps
fun getNetworkSpeed(context: Context): String {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val nc = cm.getNetworkCapabilities(cm.activeNetwork)
val downSpeed = (nc?.linkDownstreamBandwidthKbps)?.div(1000)
"${downSpeed ?: 0} Mbps"
} else {
"-"
}
}
// returns 2G,3G,4G,WIFI
fun getNetworkClass(context: Context): String {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val info = cm.activeNetworkInfo
if (info == null || !info.isConnected) return "-" // not connected
if (info.type == ConnectivityManager.TYPE_WIFI) return "WIFI"
if (info.type == ConnectivityManager.TYPE_MOBILE) {
return when (info.subtype) {
TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN, TelephonyManager.NETWORK_TYPE_GSM -> "2G"
TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP, TelephonyManager.NETWORK_TYPE_TD_SCDMA -> "3G"
TelephonyManager.NETWORK_TYPE_LTE, TelephonyManager.NETWORK_TYPE_IWLAN, 19 -> "4G"
else -> "?"
}
}
return "?"
}
}
}
There are two ways to solve this problem.
Write a code to programmatically check how long it takes download a small file and determine your bandwidth - I have used this and it is fairly accurate considering server location. I used google image on google server of course. However, the larger the file, the more accurate the result.
Use JSpeedTest - I have not tried this but it should work ok. Note, it uses 1mb file.
For solution 1:
public static float bandwidth( Context context) {
int len;
int size = 1024;
byte[] buf;
String imageurl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
InputStream is = null;
long start = System.currentTimeMillis();
long end = 0L;
float bandwidth=0.0f;
try{
Log.d("Network", imageurl);
URL url = new URL(imageurl);
URLConnection urlConn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.connect();
is = httpConn.getInputStream();
if (is instanceof ByteArrayInputStream) {
size = is.available();
buf = new byte[size];
len = is.read(buf, 0, size);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
buf = new byte[size];
while ((len = is.read(buf, 0, size)) != -1)
bos.write(buf, 0, len);
buf = bos.toByteArray();
}
Log.d("Network", "ImageSize:"+buf.length);
end = System.currentTimeMillis();
Log.d("Network", "time:"+end);
// Bandwidth : size(B/1000)=KB
//That is KiloBytes per secs
float kilobytesDownloaded = buf.length/1000;
//Get the duration, convert milliseconds to seconds
float diff = end-start;
float duration = (float)(diff/1000);
Log.d("Network", "duration in secs:"+duration);
bandwidth = (float)kilobytesDownloaded / duration;
Log.d("Network", "difference:"+(end-start));
Log.d("Network", "bandwidth:"+bandwidth+"kb/s");
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return bandwidth;
}
Your sample result should look something like this:
- ImageSize:5969 bytes
- time difference:129ms
- duration in secs:0.129s
- bandwidth:38.759693kb/s
For solution 2: click on the link, the implementation is on the page. You can get both download and upload speed with it.