Search code examples
androidandroid-wifiwifimanager

android wifi active data transfer


Using Android TelephonyManager an application can obtain the state of data activity over the cellular network. For example, activity is coming in, going out, or both. I am wondering if anyone knows of a way to obtain the same information for when the device is connected using Wifi? In Ice Cream Sandwich (4.0.3, I think) they have this information available for both Wifi and Telephone, but prior to that it is only for the phone (WifiManager wasn't updated with this information until the Ice Cream Sandwich release).

Basically, I want to be able to check if data is actively being transferred by the phone/tablet when connected to a Wifi network (not just that the Wifi is connected). This data does not have to be initiated by me; I just want to know if data is actively moving.

Does anyone have any ideas how this can be achieved? I am fairly new to Android and would like this information to make sure my application doesn't do anything bad. Thanks in advance for any thoughts.


Solution

  • I too have been looking for this and I haven't got a perfect answer, but you can get some sort of approximate data using the TrafficStats API.

    I have a piece of code which is fired off occasionally by a timer and a couple of class variables called totalDownload and totalUpload...

    long newTotalDownload = TrafficStats.getTotalTxBytes();
    long newTotalUpload = TrafficStats.getTotalRxBytes();
    
    long incDownload = newTotalDownload - totalDownload;
    long incUpload = newTotalUpload - totalUpload;
    
    if (incUpload > 0)
    {
        //data was being uploaded in the last time period
    }
    if (incDownload > 0)
    {
        //data was being downloaded in the last time period
    }
    //set up for the next iteration
    totalDownload = newTotalDownload;
    totalUpload = newTotalUpload;
    

    it works, though I would like a better answer if you find one.