我正在尝试将 Google Analytics 集成到我的应用程序中,并按照此处的教程进行一切设置:
我有一个 MainActivity 扩展 Activity 并附加了三个 Tab 片段,我在这个 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