Determining the bandwidth (speed) of a wireless network and mobile data

I want to get the network bandwidth in kbps or mbps. if the device is connected to Wi-Fi, then it should return the bandwidth (speed) of the network, as well as mobile data.

it will return the Wi-Fi compatibility speed, but I want the exact data transfer speed.

public String getLinkRate() { WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE); WifiInfo wi = wm.getConnectionInfo(); return String.format("%d Mbps", wi.getLinkSpeed()); } 
+6
source share
1 answer

You cannot simply request this information. Your internet speed is determined and controlled by your ISP, not a network interface or router.

Thus, the only way to get your (current) connection speed is to download the file from a fairly close location and determine the time it takes to receive the file. For instance:

 static final String FILE_URL = "http://www.example.com/speedtest/file.bin"; static final long FILE_SIZE = 5 * 1024 * 8; // 5MB in Kilobits long mStart, mEnd; Context mContext; URL mUrl = new URL(FILE_URL); HttpURLConnection mCon = (HttpURLConnection)mUrl.openConnection(); mCon.setChunkedStreamingMode(0); if(mCon.getResponseCode() == HttpURLConnection.HTTP_OK) { mStart = new Date().getTime(); InputStream input = mCon.getInputStream(); File f = new File(mContext.getDir("temp", Context.MODE_PRIVATE), "file.bin"); FileOutputStream fo = new FileOutputStream(f); int read_len = 0; while((read_len = input.read(buffer)) > 0) { fo.write(buffer, 0, read_len); } fo.close(); mEnd = new Date().getTime(); mCon.disconnect(); return FILE_SIZE / ((mEnd - mStart) / 1000); } 

This code, when the visible change (you need the mContext to be a valid context) and executed from within AsyncTask or the workflow, downloads the remote file and returns the speed at which the file was downloaded in Kbps.

+4
source

Source: https://habr.com/ru/post/979840/


All Articles