1

I want to write a service in android which will keep track of data usage in the background. when an event of data usage will be captured, I will save the details in local database.

I read about TrafficStats class in android but it will check only once when activity gets started. I want a continuous background process running.

I even found a sample project - https://github.com/commonsguy/cw-andtuning/tree/master/TrafficMonitor

as mentioned in the post - How to measure data usage of my app

Thanks in advance.

Community
  • 1
  • 1
rupali mandge
  • 73
  • 1
  • 7

1 Answers1

3

You need to do the following :

  • Create a local database that will store the data usage values .

  • Start a service which runs continuously / periodically to calculate /recalculate the data usage .

  • After data usage is calculated by the service ,add the data into your data usage table .

To create local database you can refer to this tutorial on sqlite

Here is how you can start a service Creating a Service in Android

EDIT

There is no way to get notified if any fresh data usage is made .You will have to periodically check it using your service that will run continuously or periodically .

You can use the following code to calculate the usage :

int UID=Process.myUid();
long recived = TrafficStats.getUidRxBytes(UID);
long send = TrafficStats.getUidTxBytes(UID);

Other functions that you can use depending on your requirement are:

long initialRX = TrafficStats.getTotalRxBytes();// recieved
long initialTx = TrafficStats.getTotalTxBytes();// sent
long initialMobRX = TrafficStats.getMobileRxBytes();
long initialMobTx = TrafficStats.getMobileTxBytes();

Remember that that TrafficStats returns a cumulative value .Hence you have to subtract the initail value in order to know the amount of increment in usage

Also The TrafficStats counter is reset whenever the process is killed.eg when phone is shut down . Hence you will have to add code to handle it .

Related Link:
TrafficStats Api android and calculation of daily data usage

Community
  • 1
  • 1
Rachita Nanda
  • 4,509
  • 9
  • 42
  • 66
  • thanks Rachita. but my question is how will the service get notified when a data usage event will occur. and how to catch the data usage event. – rupali mandge Aug 01 '13 at 09:43
  • There is no way to get notified if any fresh data usage is made .You will have to periodically check it using your service that will run continuously or periodically .I will add all this in my edit to answer – Rachita Nanda Aug 01 '13 at 09:45