确定网络连接带宽(速度)wifi和移动数据

No *_*ame 6 java android bandwidth wifimanager

我想获得以kbps或mbps为单位的网络连接带宽.如果设备连接到wifi,那么它应该返回网络带宽(速度)以及移动数据.

它将返回wifi功能率,但我想要精确的数据传输率.

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

mit*_*nia 4

您不能只查询此信息。您的互联网速度由您的 ISP 决定和控制,而不是由您的网络接口或路由器决定和控制。

因此,获得(当前)连接速度的唯一方法是从足够近的位置下载文件并计时检索该文件所需的时间。例如:

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);
}
Run Code Online (Sandbox Code Playgroud)

这段代码,当稍微修改(你需要 mContext 是一个有效的上下文)并从一个AsyncTask或一个工作线程内部执行时,将下载一个远程文件并返回文件下载的速度(以 Kbps 为单位)。