我正在尝试将Google Analytics集成到我的应用程序中,并按照here的教程设置所有内容:
我有一个MainActivity,它扩展了Activity并附加了三个Tab Fragments,我在这个Activity中初始化代码如下:
private static final String PROPERTY_ID = "UA-xxxxxx";
//Logging TAG
private static final String TAG = "MyApp";
public static int GENERAL_TRACKER = 0;
public enum TrackerName {
APP_TRACKER,
GLOBAL_TRACKER,
ECOMMERCE_TRACKER,
}
HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
public MainActivity() {
super();
}
synchronized Tracker getTracker(TrackerName trackerId) {
if (!mTrackers.containsKey(trackerId)) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(R.xml.app_tracker)
: (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(PROPERTY_ID)
: analytics.newTracker(R.xml.ecommerce_tracker);
mTrackers.put(trackerId, t);
}
return mTrackers.get(trackerId);
}
现在我正在尝试做一个标签:
((MainActivity) getApplication()).getTracker(MainActivity.TrackerName.APP_TRACKER);
但是我得到以下内容:
无法在上面的代码行中从Application转换为MainActivity。任何提示?我试图使用它的片段具有以下签名:
public class FragmentTab1 extends Fragment
答案 0 :(得分:3)
如果你在片段中调用它,也许你需要调用getActivity?
((MainActivity) getActivity()).getTracker(MainActivity.TrackerName.APP_TRACKER);