Pabloku
Pabloku

Reputation: 113

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?

Upvotes: 2

Views: 1003

Answers (1)

anddev84
anddev84

Reputation: 1483

(@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:

  1. 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.
  2. Also set an alarm for the end of your range.
  3. Create a BroadcastReceiver to receive ACTION_SHUTDOWN.
  4. 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.
  5. 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!

Upvotes: 3

Related Questions