Disable Google Analytics when in development

雨燕双飞 提交于 2019-12-04 02:38:55

If you're using ADT 17 and above, you can utilize the BuildConfig class:

if(BuildConfig.DEBUG) {
    GoogleAnalytics googleAnalytics = GoogleAnalytics.getInstance(getApplicationContext());
    googleAnalytics.setAppOptOut(true);
}

The BuildConfig class is automatically generated like R.java is. It only contains the DEBUG boolean, which is set to true by default, and to false when you export an apk.

Well you can set it to not be active easily enough:

if (...) {
  GoogleAnalytics ga= GoogleAnalytics.getInstance(getApplicationContext());
  ga.setAppOptOut(true);
}

I usually just check the hardware serial number of some known devices used for testing:

if (Arrays.asList("x", "y").contains(getHardwareSerial()))

Where getHardwareSerial() is:

public static String getHardwareSerial() {
        try {
            Field serialField = Build.class.getDeclaredField("SERIAL");
            return (String) serialField.get(null);
        } catch (NoSuchFieldException nsf) {
        } catch (IllegalAccessException ia) {
        }
        return Build.UNKNOWN;
    }
Nimesh Madhavan

With the latest version of Google Analytics, you should be using the following code:

if(BuildConfig.DEBUG){
    GoogleAnalytics.getInstance(this).setDryRun(true);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!