Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

How to access network speed when playing video in Android Platform

5.00/5 (4 votes)
25 Dec 2011CPOL 25K  
As MediaPlayer of Android has no API to know the buffering time, I just only access the speed of network via reading the linux proc file(/proc/net/dev) to enable the UI displaying the download speed
  1. The function of reading how many bytes have downloaded via wifi port:

    Java
    private long parserNumber(String line) throws Exception {
    		long ret=0;
    		String[] delim = line.split(" ");
    		if(delim.length >= 1){
    			ret = Long.parseLong(delim[0]);
    		}
    		return ret;
    	}
    	
    	public long syncFetchReceivedBytes() {
    		// TODO Auto-generated method stub
    		ProcessBuilder cmd;
    		long readBytes=0;
    		BufferedReader rd = null;
    		try {
    			String[] args = { "/system/bin/cat", "/proc/net/dev" };
    			cmd = new ProcessBuilder(args);
    			Process process = cmd.start();
    			rd = new BufferedReader(new InputStreamReader(
    					process.getInputStream()));
    			String line;
    			int linecount = 0;
    			while ((line = rd.readLine()) != null) {
    				linecount++;
    				if(line.contains("lan0")||line.contains("eth0")){
    					String[] delim = line.split(":");
    					if(delim.length>=2){
    						readBytes=parserNumber(delim[1].trim());
    						break;
    					}
    				}
    			}
    			rd.close();
    		} catch (Exception ex) {
    			ex.printStackTrace();
    		} finally {
    			if (rd != null) {
    				try {
    					rd.close();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    		}
    		return readBytes;
    	}

  2. Invoke the above function periodically (such as 1 second) to access network speed, for example:
    long curReadBytes=syncFetchReceivedBytes();
    String strSpeed=(curReadBytes-lastReadBytes)/1024 kbps
    lastReadBytes = curReadBytes;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)