如何使用Android View Pager + ActionBar标签向Google Analytics发送视图?

时间:2014-06-14 11:44:11

标签: android android-fragments tabs google-analytics android-actionbar

我使用ViewPager和ActionBar标签向用户显示数据,我还想将当前屏幕发送到Google Analytics。

但我有问题,因为ActionBar标签的工作方式是他们正在加载当前和下一个片段的数据,因此在Google Analytics实时中我只显示下一个片段。

对于ActionBar标签中的每个片段,我将数据发送到Google Analytics,如下所示:

@Override
public void onStart() {
    // Get an Analytics tracker to report app starts & uncaught exceptions
    // etc.
    // Get tracker.
    Tracker t = ((MyApplication) getActivity().getApplication())
            .getTracker(TrackerName.APP_TRACKER);

    // Set screen name
    t.setScreenName(screenName);

    // Send a screen view.
    t.send(new HitBuilders.AppViewBuilder().build());
    super.onStart();
}

我如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

我发现在发送GA screenview事件之前检查每个片段中getUserVisibleHint()isResumed()的组合是有效的。覆盖setUserVisibleHint(boolean)onResume()可确保无论调用它们的顺序如何都会发送屏幕视图事件。

此解决方案解决了使用ViewPager.setOnPageChengeListener的问题,其中初始片段未被onPageSelected调用。

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
  super.setUserVisibleHint(isVisibleToUser);
  publishScreenViewEvent();
}

@Override
public void onResume() {
  super.onResume();
  publishScreenViewEvent();
}

private void publishScreenViewEvent() {
  // Only publish if this fragment is visible to the user and the fragment has been resumed.
  // setUserVisibleHint may be called before onResume and before this fragment is injected.
  // onResume may be called before setUserVisibleHint because this fragment is in a ViewPager that
  // caches the next and previous fragment by calling onResume before the fragment is visible
  if (getUserVisibleHint() && isResumed()) {
    // Send GA screenview event here
  }
}

答案 1 :(得分:0)

我这样解决了这个问题: 1.当我的活动开始时,我放置

Utils.sendGAScreenName("Highlights", this);
ActivityProducts_.intent(this).start();

这有助于我处理第一个标签的打开。

2.在ActivityProducts中我定义了onPageChangeListener()方法

mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override

public void onPageSelected(int position) {
        actionBar.setSelectedNavigationItem(position);
        //Log.d("OnPageSelected " + position);
        switch (position)
        {
            case TAB_HIGHLIGHTS:
                Utils.sendGAScreenName("Highlights", ActivityProducts.this);
                break;
            case TAB_APPLICATIONS:
                Utils.sendGAScreenName("LT Brands", ActivityProducts.this);
                break;
            case TAB_PRODYCT_TYPE:
                Utils.sendGAScreenName("Product Type", ActivityProducts.this);
                break;
            case TAB_ALL_PRODUCTS:
                Utils.sendGAScreenName("All Products", ActivityProducts.this);
                break;
        }
    }
});