我正在开发一个 android 应用程序,我需要在其中播放在运行时查找连接的带宽。我找到了一个关于堆栈溢出本身的解决方案,说我可以从服务器下载一个文件,然后通过计算大小与时间的关系,我可以获得连接速度。
Check the bandwidth rate in Android
这是获得准确结果的最佳方式(唯一方式)吗? 感谢分享知识。
最佳答案
您不能只查询此信息。您的互联网速度由您的 ISP
决定和控制,而不是由您的网络接口(interface)或路由器决定和控制。
因此,获得(当前)连接速度的唯一方法是从足够近的位置下载文件并计算检索文件所需的时间。例如:
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 为单位返回下载文件的速度。
关于android - 在运行时检查 android 移动应用程序中的用户连接带宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30837992/