Android TrafficStats background service? - android

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!

Related

Calculate network traffic stats of app during a month

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.

Settings time difference from System.currentTimeMillis()

I found what was wrong:
So apparently http://www.epochconverter.com/ is makes assumptions of the precision of the input values, and from those assumptions values around 841073068 goes to 1996/1997. I'm not sure what is the assumption that leads to that exact date, but honestly I don't care.
Using the attached debugger I called new Date(System.currentTimeMillis()) and it correctly gave me a 10th Jan-1070 date, meaning the clock is not jumping out of the way like crazy.
Original question:
I'm running a single-board computer with Android for and IoT case (this https://developer.qualcomm.com/hardware/dragonboard-410c). The OS running is the plain vanilla Android supplied by Qualcomm.
Currently I'm testing the reliability of the board to be left executing for long periods at once and I'm seeing some very very weird behavior that I can't find an explanation for.
The board was powered up 10 days ago and it have no access to internet (WiFi is on but no access point setup and no Ethernet). The bluetooth is on and there're iBeacons and Eddystone in the office. Also there are WiFi in the area.
If I go now to Settings -> Date and Time, or check the notification shade or enter the clock app, or the calendar app, I see 10th of January 1970. Which is expected and basically showing for how long the board been running.
The app on it have an always running service, which does some data processing and some disk-logging (for debugging).
From the logs, I can see that System.currentTimeMillis() was returning an expected value when the board was initially powered on. That means, the beginning of the logs indicate an epoch time in January 1970.
But at the end of the logs (and also attaching the debugger on the live process), the value of System.currentTimeMillis() is somewhere in Sep/Oct 1996. Example values: 841073068, 841263234, 841579239
So my question is:
What is happening here?
Why System.currentTimeMillis() value changed and what could have changed it?
Why the Android UI (notification, clock app, settings) still shows me 1970? Where are they getting this value from?
edit:
There's been some confusion on the answers, and I can see my question was lacking the details.
I do not want to measure difference of time. I need an actual time stamp. Those values will be reported with bluetooth LE events via POST to our backend. This "no network" thing is a reliability test that we're running on the board, but we do expect to have network most of the time, and the boards should auto-update their times from network using the normal Android ways.
I'm just trying to understand on the current batch of testing, what went wrong and why.
Well, as you already know, the current system time (System.currentTimeMillis()) can be modified by any process if desired, it's perfectly be possible that it was modified by another process. It's not a reliable method to measure up-time.
I would rater use something like:
SystemClock.uptimeMillis()
Which returns the elapsed time (in milliseconds) since the device booted (not including time spent in deep-sleep).
I would also like to mention that I suspect that Bluetooth has something to do with it, I can imagine that Bluetooth uses the system time for pairing and security just like SSL does (but I'm no expert). GPS could also be a problem as GPS can be used to obtain an UTC time value, but I'm not sure if your board has a GPS module.
Regarding your edit:
Obtaining a valid time-stamp would be quite easy: server time minus the elapsed time reported by your board. But I suggest you either choose to accept the time reported by System.currentTimeMillis() or use the elapsed time instead. At the company I work we also work with embedded Android devices and on our server dashboard we can see both the up-time (up since) and the current device time, but they should not be mixed, at least in my opinion, especially since System.currentTimeMillis() is subject to changes and is affected by summer and winter time.
If you want to measure something, better try System.nanoTime(). Here is difference - https://stackoverflow.com/a/351571/2793494

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).

Synchronize timestamps across multiple devices

I'm trying to synchronize the timestamps between multiple Android devices so I can kick off a task at the same time. I figure that I can use Timer and set a Date based on System.currentTimeMillis(), but the problem seems to be that the timestamps of multiple devices are just far enough apart from each other that I'm not getting the precision I want.
I'm looking at somewhere in the range of 50-100 ms, if possible. One idea I had was to use Android Beam to send one device's timestamp to the other device and then calculate a delta, but it turns out that I have to get the timestamp before the message is actually sent and received (i.e., the longer a user waits to send, the bigger the delta will be), which makes that scheme completely fall apart.
How can I sync up two or more devices so that their internal clocks will be no more than 100 ms apart from each other? Is this even possible without using an external server that keeps time?
Any other suggestions for techniques to do something across multiple devices as close to simultaneously as possible would also be welcome.
Why not use the GPS time? The time tags from GPS are pretty accurate.
You could agree on all devices on a certain time and then start it when the GPS tells you to.
Essentially, you have two choices: the simple way or the hard way.
The simple way is to use a single external source for time signals, such NIST, another internet source, or GPS as #Stefan suggests. Internet sources use NTP, see this Java NTP client question.
The hard way is to do Clock synchronization between the devices.
Android GPS hardware generally have only seconds precision. The three last timestamp digits of milliseconds float number are 000.
I am struggling with the same issue right now. I tried gps time, but I cannot guarantee that the user will have gps signal indoors.
My solution was to have all devices retrieve the time from a nist server and then just add or subtract the time difference with System.currentTimeMillis()
If the devices are rooted you could try to sync the clocks.
https://play.google.com/store/apps/details?id=ru.org.amip.ClockSync&hl=en

How to measure mobile data traffic on Android

I'm developing an application that measure the data traffic recived through mobile data interface (no wifi) from all processes. Additionally this counter have to be related to a date range, i.e. betheen March 1 and April 1.
I had read about TrafficStats class, but in the documentation doesn't mentioned any about from when are the stats.
This is my first question and I really appreciate your help.
Thanks
I had read about TrafficStats class, but in the documentation doesn't mentioned any about from when are the stats.
"From when" should not matter to you. Take a reading at a point in time, take another reading at a later point in time, and the difference between the two is the bandwidth consumed between those two points in time.
Additionally this counter have to be related to a date range, i.e. betheen March 1 and April 1.
You would need to handle this yourself, most likely, checking for the amount of bandwidth consumption every so often (e.g., every 4 hours via AlarmManager), storing the results in a database, and then using that information to determine the bandwidth consumed over extended periods of time.

Categories

Resources