在代码中设置screenName

时间:2015-01-19 12:25:51

标签: android google-analytics google-analytics-api google-analytics-v4

我正在使用Google Analytics for Android,我创建了这样的跟踪器:

    GoogleAnalytics analytics = GoogleAnalytics.getInstance(context);
    tracker = analytics.newTracker(context.getString(R.string.ga_tracking_id));
    tracker.enableAutoActivityTracking(true);

我对不同的配置有不同的trackingIds,所以我不能从xml中提取跟踪器(因为我不能从xml引用字符串资源)。

我已在代码中启用了自动活动跟踪,但我找不到任何API来自定义将出现在我的报告中的屏幕名称。相反,我在报告中看到了完整的活动名称。

Tracker.setScreenName方法,但似乎意味着手动活动跟踪。

如何在代码中模拟跟踪器xml文件中的屏幕配置?通常看起来像这样:

<!-- The screen names that will appear in reports -->
<screenName name="com.mycompany.MyActivity">MyActivity Screen Name</screenName>

1 个答案:

答案 0 :(得分:2)

使用自动活动跟踪时,Google Analytics v4 API不提供在代码中设置屏幕名称的方法。您需要停用自动活动跟踪tracker.enableAutoActivityTracking(false)并从GoogleAnalytics.reportActivityStart(activity)onActivityStarted()来回GoogleAnalytics.reportActivityStop(activity)来回拨onActivityStop()

以下是应用程序活动生命周期回调的链接: http://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks.html

您的代码将如下所示:

public class MyApp extends Application {
    private final String TRACKER_ID = "UA-12345678-1";

    private static GoogleAnalytics analytics;
    private static Tracker tracker;

    public static GoogleAnalytics analytics() {
        return analytics;
    }

    public static Tracker tracker() {
        return tracker;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        analytics = GoogleAnalytics.getInstance(this);
        // analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
        tracker = analytics.newTracker(TRACKER_ID);

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

            @Override
            public void onActivityStarted(Activity activity) {
                tracker().setScreenName("My Activity");
                tracker().send(new HitBuilders.ScreenViewBuilder().build());
                analytics().reportActivityStart(activity);
            }

            @Override
            public void onActivityResumed(Activity activity) {}

            @Override
            public void onActivityPaused(Activity activity) {}

            @Override
            public void onActivityStopped(Activity activity) {
                analytics().reportActivityStop(activity);
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

            @Override
            public void onActivityDestroyed(Activity activity) {}
        });
    }
}