android statistic 3g traffic for each APP, how?

RRTW picture RRTW · Sep 27, 2012 · Viewed 10.6k times · Source

For statistic network traffic per APP, what I'm using now is Android TrafficStats

That I can get result like following :

  • Youtube 50.30 MBytes
  • Facebook 21.39 MBytes
  • Google Play 103.38 MBytes
  • (and more...)

As I know, the "Android Trafficstats" just a native pointer to a c file. (maybe an .so ?)

But it mixed Wifi & 3g traffic, is there any way to only get non-WiFi traffic statistic ?

Answer

RRTW picture RRTW · Oct 11, 2012

Evening all, I got some way to do that...

First I have to create a class which extends BroadcasrReceiver, like this:

Manifest definition:

<receiver android:name=".core.CoreReceiver" android:enabled="true" android:exported="false">
  <intent-filter>
    <action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
    <action android:name="android.net.wifi.STATE_CHANGE" />
  </intent-filter>
</receiver>

Codes:

/**
 * @author me
 */
public class CoreReceiver extends BroadcastReceiver {
  public void onReceive(Context context, Intent intent) {
    if (Constants.phone == null) {
      // Receive [network] event
      Constants.phone=new PhoneListen(context);
      TelephonyManager telephony=(TelephonyManager) 
      context.getSystemService(Context.TELEPHONY_SERVICE);
      telephony.listen(Constants.phone, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
    }

    WifiManager wifi=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
    boolean b=wifi.isWifiEnabled();
    if (Constants.STATUS_WIFI != b) {
       // WiFi status changed...
    }
  }
}

And a phone stats listener below...

public class PhoneListen extends PhoneStateListener {
  private Context context;    
  public PhoneListen(Context c) {
     context=c;
  }    
  @Override
  public void onDataConnectionStateChanged(int state) {
    switch(state) {
      case TelephonyManager.DATA_DISCONNECTED:// 3G
        //3G has been turned OFF
      break;
      case TelephonyManager.DATA_CONNECTING:// 3G
        //3G is connecting
      break;
      case TelephonyManager.DATA_CONNECTED:// 3G
        //3G has turned ON
      break;
    }
  }
}

Finally, here's my logic

  1. Collect count into SQLite DB.
  2. Collect all app network usage via TrafficStats every 1 minute, only when 3G is ON.
  3. If 3G is OFF, then stop collecting.
  4. If both 3G & WiFi are ON, stop collecting.

As I know, network traffic will go through WiFi only, if both 3G & WiFi are available.