Search code examples
androidgoogle-analyticsgoogle-analytics-apigoogle-analytics-sdk

Google analytics doesn't send event before setAppOptOut(true)


I try to send an event just before disabling the Google analytics in android. But, the event doesn't show up in the real-time GA console.

    tracker.send(new HitBuilders.EventBuilder()
                    .setCategory(category)
                    .setAction(action)
                    .setLabel(label)
                    .build());
    //disable GA
    GoogleAnalytics.getInstance(this).setAppOptOut(true);

Thanks for any advice.


Solution

  • If you enable Google Analytics logging you can see that when you call setAppOptOut(true) Google Analytics will clear all queued hits since it last sent hits to the Google Analytics servers:

    V/GAV4﹕ Thread[GAThread,5,main]: clearHits called
    

    As you noticed yourself dispatchLocalHits() doesn't help since it does nothing with Google Play Services installed. What you need to do is to wait with calling setAppOptOut(true) until after your hits have been dispatched. However as you don't know when the hits are dispatched it's not an easy thing to do.

    You can specify what dispatch period your app should have with the ga_dispatchPeriod setting (with the default being 30 minutes). If you wait for longer than the configured dispatch period you should be fairly certain that your event has been sent, however this is not guaranteed since GA may wait with sending the data even longer if you do not have any network connection at the moment.

    If you would take this approach you must make sure that the wait works across sessions since Google Play services is a separate service on the device and it will hold on to your hits even if you restart your app. So opting out on next startup of your app will not work either.

    However waiting with opting out for more than 30 minutes might not be very nice to your users since that gives a lot of time for data to be gathered and submitted after the user thinks that they have opted out.

    A better approach might be to have your own internal Google Analytics wrapper class that all parts of your app calls to report data. Then each reporting method could have a check if Google Analytics is enabled, never call any of the real Google Analytics methods.

    This way you can be sure that you final event is sent to Google Analytics while no more events are sent after that even though you don't call setAppOptOut(true).

    Do note that this only works if you do not rely on any automatic tracking like automatic reporting of uncaught exceptions or automatic screen measurement.