Determine Network Connection Bandwidth (speed) wifi and mobile data

∥☆過路亽.° 提交于 2019-12-04 12:13:01

问题


I want to get Network Connection Bandwidth in kbps or mbps. if the device is connected to wifi then it should returns the network bandwidth(speed) as well as mobile data.

it will returns wifi capablity rate but i want exact data transfer rate.

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

回答1:


You can't just query for this information. Your Internet speed is determined and controlled by your ISP, not by your network interface or router.

So the only way you can get your (current) connection speed is by downloading a file from a close enough location and timing how long it takes to retrieve the file. For example:

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 sightly modified (you need mContext to be a valid context) and executed from inside an AsyncTask or a worker thread, will download a remote file and return the speed in which the file was downloaded in Kbps.



来源:https://stackoverflow.com/questions/27543291/determine-network-connection-bandwidth-speed-wifi-and-mobile-data

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