Search code examples
androidgoogle-analytics-firebase

Disable google analytics tracking during live run


According to the terms for Google analytics you need to provide the user with a option to opt out of the tracking. But I feel, documentation is not very clear on how to do that. This what I got so far.

GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker t = analytics.newTracker(R.xml.tracker);
t.enableAdvertisingIdCollection(false);
t.enableAutoActivityTracking(false);
t.enableExceptionReporting(false);

Will this disable all tracking including events like this.

t.send(new HitBuilders.EventBuilder()
    .setCategory("category")
    .setAction("test")
    .setLabel("label")
.build());

If not how do I completely disable tracking during run on user device?


Solution

  • You need to use GoogleAnalytics.getInstance(this).setAppOptOut(true);.

    In Google Analytics documentation(1), there is simple example with shared preferences.

    SharedPreferences userPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    
    userPrefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener () {
    
      @Override
      public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals(TRACKING_PREF_KEY)) {
          GoogleAnalytics.getInstance(getApplicationContext()).setAppOptOut(sharedPreferences.getBoolean(key, false));
        } else {
          // Any additional changed preference handling.
        }
      }
    });
    

    Note: This is different from disabling Google Analytics during testing / development. If your aim is to disable during test/development, use (2)

    GoogeAnalytics.getInstance(this).setDryRun(true);