Android盒子网络带宽分为2种情况,一种是以太网络,一种是无线网络。获取无线网络带宽比较简单,只要通过wifiInfo.getLinkSpeed()就可以获取得到,单位是”Mbps",即wifiInfo.LINK_SPEED_UNITS。获取以太网的带宽即获取以太网卡的带宽可以通过执行shell命令"cat /sys/class/net/eth0/speed"来获取。
public String getNetSpeed(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return null;//无连接
}
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isAvailable()) {
return null;//无连接
}
int type = networkInfo.getType();
if (type == ConnectivityManager.TYPE_WIFI) {
String speed = wifiInfo.getLinkSpeed() + wifiInfo.LINK_SPEED_UNITS;
return speed;
} else if (type == ConnectivityManager.TYPE_ETHERNET) {
String speed = runShellCommand("cat /sys/class/net/eth0/speed").trim() + "Mbps";
return speed;
}
return null;
}
//执行shell命令
public static String runShellCommand(String command) {
Runtime runtime;
Process proc = null;
StringBuffer stringBuffer = null;
try {
runtime = Runtime.getRuntime();
proc = runtime.exec(command);
stringBuffer = new StringBuffer();
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line + " ");
}
} catch (Exception e) {
System.err.println(e);
} finally {
try {
proc.destroy();
} catch (Exception e2) {
}
}
return stringBuffer.toString();
}