android statistic 3g traffic for each APP, how?

前端 未结 4 1175
无人共我
无人共我 2020-12-13 15:37

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
4条回答
  •  -上瘾入骨i
    2020-12-13 16:15

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

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

    Manifest definition:

    
      
        
        
      
    
    

    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.

提交回复
热议问题