Google analytics drops metrics in Android if you send them too quickly
I just ran into this problem with the Google Analytics SDK for Android (v0.8). Basically, if you try to send too many pageviews too quickly, the tracker gets overwhelmed and forgets to track some of them.
My solution was just to space things out a bit with Timers and TimerTasks. I have a small wrapper around the analytics tracker, which has a timer, a static inner TimerTask class, and a long which is the soonest that a pageview should be sent. Whenever you want to send a pageview, you just call recordView, which looks like this:
public void recordView(String metric) { // The current time. long time = new Date().getTime(); // We keep track of the next appropriate time to send a metric with sendTime. sendTime only gets updated // when we try to send something, if (this.sendTime > time) { time = this.sendTime; } this.sendTimer.schedule(new TrackTask(this, metric), new Date(time)); // I have sendInterval set to 2000, meaning pageviews are sent at a minimum, two seconds apart. this.sendTime = time + this.sendInterval; }
Then, TrackTask looks like this:
protected static class TrackTask extends TimerTask { // private WeakReference ref; private String metric; public TrackTask(Metrics met, String metric) { // WeakReference to avoid memory leaks. this.ref = new WeakReference(met); this.metric = metric; } public void run() { // try catch block because our WeakReference has the possibility of being GCed out from under us. try { this.ref.get().tracker.trackPageView(this.metric); this.ref.get().tracker.dispatch(); } catch (NullPointerException e) { } } }