我发布这个问题是因为我找不到明确的答案。:)
我是 Android 新手,目前正在制作一个有多个活动的应用程序。我使用谷歌播放服务进行谷歌分析。通过遵循谷歌开发指南,我设法让它工作。但是每当我创建一个新的活动(屏幕)时,我必须在每个活动类中重复相同的代码。
例如:-Activity1.java
public class Activity1 extends Activity {
HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity1);
setAnalytics();
}
public enum TrackerName {
APP_TRACKER, // Tracker used only in this app.
GLOBAL_TRACKER, // Tracker used by all the apps from a company.
ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company.
}
synchronized Tracker getTracker(TrackerName trackerId) {
if (!mTrackers.containsKey(trackerId)) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker tracker = analytics.newTracker(R.xml.global_tracker);
mTrackers.put(trackerId, tracker);
}
return mTrackers.get(trackerId);
}
private void setAnalytics(){
// Get tracker.
Tracker t = getTracker(TrackerName.APP_TRACKER);
// Set screen name.
//t.setScreenName("Activity 1");
// Send a screen view.
t.send(new HitBuilders.AppViewBuilder().build());
}
}
我的 global_tracker.xml 是
<!-- Enable automatic Activity measurement -->
<bool name="ga_autoActivityTracking">true</bool>
<!-- The screen names that will appear in reports -->
<screenName name="com.test.activity1">Activity1</screenName>
<screenName name="com.test.activity2">Activity2</screenName>
<!-- The following value should be replaced with correct property id. -->
<string name="ga_trackingId">UA-XXXXXXXX-1</string>
这个设置工作得很好。我的问题是“这是最好的方法吗?”。是否可以使用另一种方法来最小化每个 Activity 类中的代码?因为每次我都必须重复相同的代码。是否可以创建一个通用类来保存这些通用代码集并将其用作每个 Activity 类中的对象?
有什么想法吗?先感谢您。