How to write a service to keep track of gprs data usage on android device

五迷三道 提交于 2019-12-24 08:22:11

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/17989962/how-to-write-a-service-to-keep-track-of-gprs-data-usage-on-android-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!