Calculate network traffic stats of app during a month - android

I want to calculate the amount of network usage/network traffic stats for my app in a month.
I can use TrafficStats to provides network traffic statistics, but the statistics returned by this class reset and start from zero after every reboot. I think about storing the statistics on the storage, but I want another way.
So I change to use NetworkStatsManager to calculate, but most of method required API >= 23.
So how can I do it with api below 23? Thank you.

you should persist the data from traffic stat in sqlite at some time interval. And store the last reading just before Shutdown using
action android.intent.action.ACTION_SHUTDOWN in broadcastreceiver. After restart, you should start storing the data again. This way, you will not lost the data. The solution works on all android version.

I can use TrafficStats to provides network traffic statistics, but the
statistics returned by this class reset and start from zero after
every reboot.
How about storing this data somewhere? E.g. in SharedPreferences, SQLite database or somewhere else. After that, your data will be persisted after reboot and you can accumulate the calculated results.

Even if we persist the data in sqlite, it is not necessary that the value is reset to zero after shut down of device. In that case there is confusion whether to add the previous stored bytes with the value that we get after reset, because the value is not always zero after shut down.

Related

Android Time Synchronization in UTC

I have an application that relies heavily on current timestamps. Currently, when user submits a request, I get the current timestamp in UTC using System.currentTimeMillis(). While this works fine, it becomes a problem when the user starts manipulating their Date/Time on their device and would result as inaccurate timestamps.
Why do it on the client then? Why not just handle it on the server? Well, my application needs to work offline. All my requests get pushed into a jobQueue when connectivity to the internet is unavailable. In these cases, I must have the original time wherein the user did the action so if I submit a request at 4:02pm, but due to network problems, server will only receive it around 7:30pm, server MUST know that I sent the request at 4:02pm.
Now what options have I considered?
Upon user login, I sync the device time with the server time and store that time locally. If any user manipulation occurs while the user is logged in, I'll have a BroadcastReceiver listening in onto any intents of Date/Time manipulation, then store the offset so that whenever a user submits a request, I will calculate the synced time with the offset to ensure the timestamp is accurate.
Have a server sync api done in the backend and set up a service within my application to continuously sync up with the server time and look for any drift while also listening in onto any user manipulation.
Use push notifications and listen downstream for time synchronization adjustments while also listening onto any user manipulation.
I could also make use of the NTP servers to synchronize time with my device.
I'm not entirely sure which would be the most optimal (assuming I have listed down all the possible solutions). If there are other solutions I haven't thought of, please let me know.
P.S. If I happen to use the BroadcastReceiver to listen onto any datetime manipulation on the device, how would I even calculate the offset in that?
It has been some time since I asked this question and there hasn't been any elegant answers to the problem so after some research and some trial and error, I decided to take the NTP route and after some digging around, I found a nice library that does the entire thing for you.
It can be found here:
NTP TRUE TIME
Credits to these guys who had made life a lot easier.
You must sync with the ntp servers just once and from there on, they will calculate the Delta for us giving us accurate UTC regardless of SystemClock time.
For time synchronization you can implement like getting time zone from server. Once we have timzone we can get the current time of server.

How to get trafficStats information from android by time?

Is there a way how to get trafficStats from some date? For example from last month.
I´m using this Get wifi traffic stats android and as u can see from the code there is only number value of traffic in this file, but for example in DroidStats app data are counted from last day/month etc.
Also value is always 0 when i reboot my phone or when i´m messing up with settings of network is there another file somewhere or do i have to store this data myself if i don´t want to lose them?
Is there a way how to get trafficStats from some date? For example from last month.
You would have had to have been running last month, collected the data yourself, and saved it to a database or something. TrafficStats does not have any history. It only reports current cumulative values, except for resets (e.g., reboots).
Also value is always 0 when i reboot my phone
Correct. This is working as intended.
do i have to store this data myself if i don´t want to lose them?
Yes.

Android : How to get Internet Data Usage per Day or by range of time?

I am trying to get the exact Data Usage per Day , or by Range of Time in Android
however from what I searched, I cannot found anything that could do this
Something that I tried
TrafficStats
this one will reset all data every time the device is boot, so I
couldn't use it
NetworkPolicyManager
this one require system permission. So, I can't use it
any help would be appreciate
You need to have a service that will periodically call TrafficStats APIs to get current statistics, and store the results. E.g. the delta between two invocations of getMobileTxBytes() is the number of bytes received during that time period.
Of course, if someone just pulls a battery out of their phone, you'll lose statistics since the last invocation of your service. So set the frequency of updates according to your needs (every hour versus every minute).

Get accurate time from android/iphone to server

We have an android(or iphone) client we are developing. The client allows the android user to send entries to a server which we also develop. If the client does not have data services (GPRS) at the moment the user sends the entry to the server, the client also supports saving the entry to an offline database and sending it later to the server.
One important aspect of the whole process is accuracy of the timestamps on which the user sent the entry to the server (whether the entry is made in real time or sent by the client from the offline database)
When available on the client, we get a GPS location and are able to use the GPS timestamp to send that to the server (or save the GPS timestamp on the offline DB and send it later to the server). However if the user has turned off the GPS (and all other location services), the device will not have a GPS fix and therefore the server can not determine accurately when an entry was made.
We can not use the local device clock as the user may change the clock to make entries on different times than they actually occurred (these entries are part of the users salary so he might have an interest to "fix" them).
So basically I am searching for a way to determine as best I can the time some entry was made when I can not trust the internal clock of the mobile. The algorithm should support both entries sent in real time or entries sent from an offline DB. the algorithm should also support cases where the user changes the time of the mobile, turns the mobile on/off, turns the GPS on/off while the application is running on the mobile etc...
Few ideas that I thought of:
Although I can not trust the mobile's time, it can still perform as a stop watch:
Have a class that will loop until the application exists, the loop will sleep 1 second and increase an internal clock variable by 1 second. On every GPS location my code gets we update the internal clock variable. This way I have an absolute clock that came from outside the device (from the GPS) and when the client sends an entry to the server, we can use the internal clock as an absolute time.
PROS: the user can not modify this clock as it is only updated when we get a location from the GPS
CONS: the application needs at least one GPS fix before the user can make any reliable entries
I can take advantage of the fact that the server has an accurate clock which is correct. If the client would send to the server info that the age of the entry is 10 minutes, the server could use its internal time and know the exact time the entry was made on.
The biggest problem is how to know the entry age? I thought about saving the entries to the offline DB with an age of 0, then every 1 second increase the age of the entry in the DB. The problem is that if the app is closed and/or the device is off this will now happen
This is where I am currently stuck. Any ideas on how to solve this are more than welcome
Thanks
Here's how I handle this issue for iPhone. When the app starts, I call my server and ask for the current GMT time (you could also call a public NTP server if you preferred). I then compare it to the system time. If it is different by more than X then I popup a message saying, sorry your system time is wrong so you can't use the app until you fix this. I then monitor for the user changing the system time while the app is running and if they do that, then I do the compare again (and popup the error message if the time is off by more than X). This ensures that their system time is always correct (within some reasonable allowance) and you can trust [NSDate date]. However, this solution does require a valid network connection. If this solution works for you, I can post the sample code.
i think i am going to combine Jules and Joel's answers into one solution which will provide for my needs the best solution:
since the user might change the clock when the mobile doed not have GPRS, just detecting the time change event will not help us as we can not validate at that moment the new time is correct.
As Joel recommended i will pull the time from my server when my application is started (at that point i still must have communications with the server or else my application will not start). The time pulled from the server along with the current device upTime will be saved.
when the user wants to make an entry i will calculate the current time using (Server Base Time + Current UpTime - Base UpTime). this way i will have an independent source of time regardless of the current clock of the device
this will defenitly work on android
on iPhone we will try to use something out of http://www.cocoadev.com/index.pl?FindingUptime to get the upTime
Jules & Joel, thanks for your answers!
Look into android.os.SystemClock. Specifically, elapsedRealtime() returns a time since the phone was switched on, which is not affected if the clock is changed by the user.
You can correlate times in event the phone is switched off by having code that runs when it is switched on and checks the realtime clock. As the clock can't be changed when the phone is off, I suspect you could use this to put together a system that will catch any simple attempts at cheating. (If the user roots the phone all bets are off -- they could modify the behaviour of the APIs from under you).
Running code every second will kill the phone's battery life. Most phones would be unlikely to last a day if you did this.

Android TrafficStats background service?

I would like to get some help about getting 3G data statistics between a date interval.
As far as I know, I should use TrafficStats (Android api 2.2 or higher). I would like to save this information into a SQLite table to show statistics for apps monthly:
Interval date: 01/01/2012 - 31/01/2012
Google Maps - 1,5 Mb
Google Talk - 0,9 Mb
Facebook app - 5,6 Mb
So, I Think I should use a background service. Is this the best way? How should I try to do it in the background service? How do you think I should save the information in SQLite?
(#Pabloku, sorry this answer is coming so late, hopefully it will still be of some help)
Firstly, if you're looking to get traffic stats for individual apps, but only on 3G, it's not possible using public APIs. Android provides the TrafficStats.getUidTxBytes(int) and TrafficStats.getUidRxBytes(int) as public APIs to get the total number of bytes used by apps, but nothing (public) to separate them by interface.
Assuming this doesn't ruin your day, here is a pseudocode algorithm for how to do the rest of what you mention:
Set an alarm if necessary (using AlarmManager) for the start of your range, and store these values (presumably in a DB). Reason: you may need to subtract these existing TrafficStats values as an offset if they are > 0 at the time your date range starts.
Also set an alarm for the end of your range.
Create a BroadcastReceiver to receive ACTION_SHUTDOWN.
In your BroacastReceiver, note down the TrafficStats for your app(s) at shutdown. Reason: TrafficStats will get reset on every reboot.
If this is the first shutdown since start: subtract your initial offset and store that final value (being careful to remove the initial offset)
Otherwise, whatever value is reported will be accurate since boot.
Once your end alarm is triggered, note down the TrafficStats at that point, and add all previously collected stats
(if somehow the phone never rebooted between start and end, just do endStats - startStats).
Good luck!

Categories

Resources