android 获取网速

来源:互联网 发布:linux nginx 全局变量 编辑:程序博客网 时间:2024/05/10 09:02

今天看项目源码发现获取android网速有问题,就此改了一下,做个笔记留给自己看。

下面代码放在工具类里:

public static long getNetworkSpeed(Context context) {ProcessBuilder cmd;long readBytes = 0;BufferedReader bufferReader = null;try {String[] args = { "/system/bin/cat", "/proc/net/dev" };cmd = new ProcessBuilder(args);Process process = cmd.start();bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = bufferReader.readLine()) != null) {if (line.contains("wlan0") && isWiFiNetworkAvailable(context)) {String[] delim = line.split(":");if (delim.length >= 2) {String values = delim[1].trim();values = nSpace2one(values);String[] numbers = values.split(",");// 提取数据readBytes = Long.parseLong(numbers[0].trim());readBytes += Long.parseLong(numbers[8].trim());break;}}if (line.contains("eth0") && isEthernetNetworkAvailable(context)) {String[] delim = line.split(":");if (delim.length >= 2) {String values = delim[1].trim();values = nSpace2one(values);String[] numbers = values.split(",");readBytes = Long.parseLong(numbers[0].trim());readBytes += Long.parseLong(numbers[8].trim());break;}}}bufferReader.close();} catch (Exception ex) {ex.printStackTrace();} finally {if (bufferReader != null) {try {bufferReader.close();} catch (IOException e) {e.printStackTrace();}}}return readBytes;}//处理字符串数据的private static String nSpace2one(String s) {String regEx = "[' ']+"; // 一个或多个空格Pattern p = Pattern.compile(regEx);Matcher m = p.matcher(s);String ret = m.replaceAll(",").trim();return ret;}public static boolean isWiFiNetworkAvailable(Context context) {boolean netSataus = false;ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo netinfo = cm.getActiveNetworkInfo();if (netinfo != null && netinfo.getType() == ConnectivityManager.TYPE_WIFI) {netSataus = netinfo.isAvailable();}return netSataus;}public static boolean isNetworkAvailable(Context context) {boolean netSataus = false;ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo netinfo = cm.getActiveNetworkInfo();if (netinfo != null) {netSataus = netinfo.isAvailable();}return netSataus;}

在Activity或fragment中调用上述工具类的方法:

private long lastTimeSpeed = 0;private TextView showNetWorkSpeed;private Handler mHandler = new Handler();private Runnable updateCurrentNetWorkSpeed = new Runnable() {public void run() {long getDataFlow = Utility.getNetworkSpeed(xxxActivity.this) / 1024;//xxxActivity是你当前的Activityif(lastTimeSpeed==0){lastTimeSpeed = getDataFlow;}long showSpeed = getDataFlow - lastTimeSpeed;lastTimeSpeed = getDataFlow;showNetWorkSpeed.setText(showSpeed+"k/s");mHandler.postDelayed(updateCurrentNetWorkSpeed, 1000);}}

其实这里的getNetworkSpeed方法返回的并非当前网速,而是流量总值~~~

获取流量的方法并不是我写的。欢迎各位大神指出问题,指导下哈~~~


0 0
原创粉丝点击