use*_*936 6 android google-analytics
我必须在 android 中实现自动事件跟踪
需要自动收集所有按钮点击和页面浏览的分析数据,但必须以通用方式完成,这样我就不需要为每次点击再次编写分析代码。
示例:我的活动中有 2 个按钮,每个按钮都有一个点击侦听器。现在我想调用 Analytics.track(String buttonName) 这样我就不必在每个点击监听器中添加它。跟踪中应该传递的数据是按钮名称。
一种方法(可能不是最终方法)可以是扩展Button(或View),并将分析代码放入View#performClick()方法中。
至于buttonName,它可以是自定义 View 类的一个字段,您可以通过编程方式甚至通过 XML 自定义属性进行设置。
全球实施:
创建自定义 XML 属性:attrs.xml在资源文件夹中创建一个名为的文件:
<resources>
    <declare-styleable name="tracking">
        <attr name="tracking_name" format="string" />
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)创建一个自定义Button(或View)类,该类覆盖performClick()方法并Analytics.track()使用从 XML 自定义属性获取的字符串进行调用或以编程方式设置:
public class TrackedClickButton extends Button {
    private String mTrackingName;
    public TrackedClickButton(Context context) {
        super(context);
    }
    public TrackedClickButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }
    public TrackedClickButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }
    @TargetApi(21)
    public TrackedClickButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }
    private void init(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.tracking);
        if (array.hasValue(R.styleable.tracking_name)) {
            mTrackingName = array.getString(R.styleable.tracking_name);
        }
    }
    public void setTrackingName(String trackingName) {
        this.mTrackingName = trackingName;
    }
    @Override
    public boolean performClick() {
        //Make sure the view has an onClickListener that listened the click event,
        //so that we don't report click on passive elements
        boolean clickHasBeenPerformed = super.performClick();
        if(clickHasBeenPerformed && mTrackingName != null) {
            Analytics.track(mTrackingName);
        }
        return clickHasBeenPerformed;
    }
}
Run Code Online (Sandbox Code Playgroud)在您想要跟踪事件的任何地方使用您的新类,例如在布局文件中:
<com.heysolutions.dentsply.Activites.MainActivity.TrackedClickButton
    xmlns:tracking="http://schemas.android.com/apk/res-auto"
    android:id="@+id/button"
    android:layout_width="50dp"
    android:layout_height="50dp"
    tracking:tracking_name="buttonTrackingName"/>
Run Code Online (Sandbox Code Playgroud)再说一遍,这是一种方法,可能是其他更容易/更好/更好的实现方法:)
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           1992 次  |  
        
|   最近记录:  |