连接到移动网络时如何获得连接速度?

时间:2019-04-11 11:54:25

标签: java android

我正在尝试获取移动和WiFi连接的连接速度。我有WiFi工作。现在,我需要帮助来确定移动连接。

这是我到目前为止所拥有的

public void internetConnectionSpeed(Context context) {
    Boolean isConnected = false;
    getConnectionStatus = "Not Connected!";

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
      if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED || (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)) {
          isConnected = true;
          getConnectionStatus = "Connected!";

          if (isConnected.equals(true)) {
              WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
              WifiInfo wifiInfo = wifiManager.getConnectionInfo();
              int speedMbps = wifiInfo.getLinkSpeed();
              getConnectionStatus = Integer.toString(speedMbps) + " Mbps";

              //Now I need equivalent code for Mobile Network...
          }

      }else {
          isConnected = false;
          getConnectionStatus = "Not Connected!";
      }
}

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    boolean   connected = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED;

if(connected){//todo}
  

您无法像wifimanager所提供的那样直接获得网络速度。你需要   ping一个地址并计算响应时间。请遵循以下步骤:   https://github.com/bertrandmartel/speed-test-lib