Check the bandwidth rate in Android

时光怂恿深爱的人放手 提交于 2019-11-28 07:00:18

You can download a known-size file from your server, and calculate how long did it take to download it. Then you have your bandwidth. Simple but works :)

Sample, not tested :

//Download your image
long startTime = System.currentTimeMillis();
HttpGet httpRequest = new HttpGet(new URL(urlString).toURI());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
long endTime = System.currentTimeMillis();

HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity;
bufHttpEntity = new BufferedHttpEntity(entity);

//You can re-check the size of your file
final long contentLength = bufHttpEntity.getContentLength();

// Log
Log.d(TAG, "[BENCHMARK] Dowload time :"+(endTime-startTime)+" ms");

// Bandwidth : size(KB)/time(s)
float bandwidth = contentLength / ((endTime-startTime) *1000);

This will Returns the current link speed in LINK_SPEED_UNITS.

but this work for WIFI Only

WifiManager wifiManager = Context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null) {
    Integer linkSpeed = wifiInfo.getLinkSpeed(); //measured using WifiInfo.LINK_SPEED_UNITS
}

Try facebook network library class (library size = 16 KB)

We can fetch manually / network change listener also available.

Manual fetch code:

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

Github link - https://github.com/facebook/network-connection-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!