在运行时检查用户连接在Android移动应用程序中的带宽

时间:2015-06-15 05:36:58

标签: android bandwidth

我正在开发一个Android应用程序,我需要在运行时找到连接的带宽。我找到了堆栈溢出本身的解决方案,说我可以从服务器下载文件,然后通过计算大小与时间,我可以得到连接的速度。

Check the bandwidth rate in Android

这是获得准确结果的最佳方式(唯一方法)吗? 感谢您分享知识。

2 个答案:

答案 0 :(得分:4)

您无法查询此信息。您的Internet速度由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);
}

此代码,如果被修改(您需要mContext成为有效的上下文)并从AsyncTask或工作线程内执行,将下载远程文件并返回其中的速度文件以Kbps下载。

答案 1 :(得分:3)

Facebook为此发布了一个库:你可以试试这个

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