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

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

它将返回wififunction率,但我想要精确的数据传输率。

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

您不能只查询此信息。 您的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下载文件的速度。