2

I am trying to calculate mobile data usage so I am using a broadcast that inform me about 3G connection then I run a Service to count data.

The problem is the calculating value is always less than the value calculated by the Android data usage default app.

Here is the code :

long now = TrafficStats.getMobileRxBytes();
long before  = now;
do {

    now = TrafficStats.getMobileRxBytes() ;
    Diffnow = now - before;

    SystemClock.sleep(500);


}while ((cm.getActiveNetworkInfo() != null) && (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE));

Log.i(TAG,"delta  = "+(float)Diffnow/(1024*1024));
Sufian
  • 6,405
  • 16
  • 66
  • 120
Soufiane
  • 368
  • 1
  • 3
  • 14
  • check this thread http://stackoverflow.com/questions/11939939/how-can-i-find-the-data-usage-on-a-per-application-basis-on-android – AndroidRuntimeException Sep 01 '16 at 16:08
  • i saw that before, i need just to calculate data usage for all apps. and i m doing the same work that is showen in answer but still there is a difference – Soufiane Sep 01 '16 at 16:11

1 Answers1

0

I think that i found the answer To calculate data usage we must calculate either transmetted and received data so i have to change my code as following :

long now = TrafficStats.getMobileRxBytes()+TrafficStats.getMobileTxBytes();
long before  = now;
long Diffnow ;

do {

    now = TrafficStats.getMobileRxBytes()+TrafficStats.getMobileTxBytes() ;
    Diffnow = now - before;
    SystemClock.sleep(500);


}while ((cm.getActiveNetworkInfo() != null) && (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE));

Log.i(TAG,"delta  = "+(float)Diffnow/(1024*1024));
Soufiane
  • 368
  • 1
  • 3
  • 14
  • If you can add more information about why it fixes the problem, it will not only be helpful for others but also yourself if you run into it again ;) – Sufian Sep 02 '16 at 13:39
  • The problem was how to calculate usage data : I thought that I have just to compute received data (getMobileRxBytes()) but in reality data usage is both received and transmetted data that’s why I add getMobileTxBytes() to compute total data before and after 3G connection – Soufiane Sep 02 '16 at 18:00