日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

一文詳解無痕埋點在Android中的實現_Android

作者:小寶一號 ? 更新時間: 2023-05-21 編程語言

前言

本篇技術實現主要是運行是代理,不涉及到插樁技術,不引入插件,對業務影響點最小

技術難點

1. 如何攔截到所有的view的點擊事件

view有個setAccessibilityDelegate方法可以通過自定義一個全局的AccessibilityDelegate對象來監聽view的點擊事件

object EventTrackerAccessibilityDelegate : View.AccessibilityDelegate() {

    override fun sendAccessibilityEvent(host: View?, eventType: Int) {
        super.sendAccessibilityEvent(host, eventType)
        if (eventType == AccessibilityEvent.TYPE_VIEW_CLICKED) {
            host?.let {
                // 統一做埋點
            }
        }
    }
}

通過給每個View設置上述單例對象,這樣每當View被點擊時,View.performClick內部就會觸發上述方法。這樣就能夠攔截view的點擊事件,而不用修改業務層代碼。

2. 如何對app所有的view設置setAccessibilityDelegate

解決這個問題,就得攔截到app中view的創建。我們先要對Android中View的創建流程需要明白,對于android中的view創建,我們先從AppCompatActivity.onCreate方法入手

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
  final AppCompatDelegate delegate = getDelegate();
  delegate.installViewFactory(); //重點
  delegate.onCreate(savedInstanceState);
  super.onCreate(savedInstanceState);
}

我們重點看installViewFactory方法,delegate返回的實際類型為AppCompatDelegateImpl,它繼承了AppCompatDelegate抽象類

// AppCompatDelegateImpl.java
@Override
public void installViewFactory() {
  LayoutInflater layoutInflater = LayoutInflater.from(mContext);
  if (layoutInflater.getFactory() == null) {
    LayoutInflaterCompat.setFactory2(layoutInflater, this);
  } else {
    if (!(layoutInflater.getFactory2() instanceof AppCompatDelegateImpl)) {
      Log.i(TAG, "The Activity's LayoutInflater already has a Factory installed"
            + " so we can not install AppCompat's");
    }
  }
}

這里面可以看到內部調用了LayoutInflaterCompat**.setFactory2方法,第二個參數傳入了this;其實可以理解view的創建托管給了AppCompatDelegateImpl.onCreateView了;我們繼續看onCreateView**內部做了什么

public View createView(View parent, final String name, @NonNull Context context,
            @NonNull AttributeSet attrs) {
    
        if (mAppCompatViewInflater == null) {
            TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme);
            String viewInflaterClassName =
                    a.getString(R.styleable.AppCompatTheme_viewInflaterClass);
            // 讀取當前活動theme中是否聲明了viewInflaterClass屬性,
            // 如果沒有就創建一個AppCompatViewInflater對象,否則使用自定義屬性對象
            if ((viewInflaterClassName == null)
                    || AppCompatViewInflater.class.getName().equals(viewInflaterClassName)) {
                // Either default class name or set explicitly to null. In both cases
                // create the base inflater (no reflection)
                mAppCompatViewInflater = new AppCompatViewInflater();
            } else {
                try {
                    Class<?> viewInflaterClass = Class.forName(viewInflaterClassName);
                    mAppCompatViewInflater =
                            (AppCompatViewInflater) viewInflaterClass.getDeclaredConstructor()
                                    .newInstance();
                } catch (Throwable t) {
                    Log.i(TAG, "Failed to instantiate custom view inflater "
                            + viewInflaterClassName + ". Falling back to default.", t);
                    mAppCompatViewInflater = new AppCompatViewInflater();
                }
            }
        }

        ...
        // 返回view

        return mAppCompatViewInflater.createView(parent, name, context, attrs, inheritContext,
                IS_PRE_LOLLIPOP, /* Only read android:theme pre-L (L+ handles this anyway) */
                true, /* Read read app:theme as a fallback at all times for legacy reasons */
                VectorEnabledTintResources.shouldBeUsed() /* Only tint wrap the context if enabled */
        );
    }

從上述代碼可以看到負責view的創建的其實是mAppCompatViewInflater對象;思路來了,我們可以通過自定義主題樣式中viewInflaterClass屬性,來接管view的創建

Style.xml中添加配置

 <!-- Base application theme. -->
    <style name="AppTheme" parent="AppThemeBase" >
        ...
        <item name="viewInflaterClass">com.dbs.module.framework.event.tracker.DBSAppCompatViewInflater</item>
    </style>

view創建

@Keep
class DBSAppCompatViewInflater : AppCompatViewInflater() {

    private val mViewCreateHelper by lazy { ViewCreateHelper() }

    override fun createView(context: Context?, name: String?, attrs: AttributeSet?): View? {
        return when (name) {
                try {
                    mViewCreateHelper.createViewFromTag(context, name, attrs)
                } catch (e: Exception) {
                    // noNeed throw exception, just return null
                    null
                }
        }
    }
}

ViewCreateHelper主要是通過全路徑名以反射形式創建view;你可以參考AppCompatViewInflater類中實現

DBSAppCompatViewInflater方法我們實現了自定義view的方法;(但它只是view創建的一部分,所以此處沒有對view設置EventTrackerAccessibilityDelegate),外部調用的只是AppCompatViewInflater.createView

所以為了攔截所有view的創建,我們需要對activity中getDelagate方法做包裝; 有人可能會想能不能自定義Delegate,自己實現AppCompatDelegate抽象類嗎?;答案是不行(抽象類中聲明了私有方法,子類直接繼承編譯報錯)也不建議這樣做,自定義類去做需要實現許多方法,穩定性太差;能不能直接繼承AppCompatDelegateImpl類呢?答案也是不行

@RestrictTo(LIBRARY)
class AppCompatDelegateImpl extends AppCompatDelegate
        implements MenuBuilder.Callback, LayoutInflater.Factory2 {
}

從源碼可以看出compat包中對AppCompatDelegateImpl類做了限制,只能用在那個庫中LIBRARY中使用

Restrict usage to code within the same library (e.g. the same gradle group ID and artifact ID).

所以我們只能對Delegate增加一層包裝,delegate現在已經擁有創建view的能力,我們只要在install之前對LayoutInflater設置Factory2中方法,在方法中直接引用delegate對象創建view就可以了;

實現一個LayoutIInflater.Factory2接口

class AppLayoutInflaterFactory2Proxy(private val delegate: AppCompatDelegate)
    : LayoutInflater.Factory2 {

    override fun onCreateView(parent: View?, name: String?, context: Context?, attrs: AttributeSet): View? {
        context ?: return null
        delegate.createView(parent, name, context, attrs)?.apply {
                // 無痕埋點啟用,則綁定,否則不做處理
                if (EventAutoTrackerCfg.enable) {
                    if (ViewCompat.getAccessibilityDelegate(this) == null) {
                        accessibilityDelegate = EventTrackerAccessibilityDelegate
                    }
                }
            }
    }

    override fun onCreateView(name: String?, context: Context?, attrs: AttributeSet): View? {
        return onCreateView(null, name, context, attrs)
    }
}

Activity基類中復寫getDelegate方法

override fun getDelegate(): AppCompatDelegate {
        val delegate =  super.getDelegate()
        try {
            val inflater = LayoutInflater.from(this)
            // avoid throw exception when invoking method multiple times
            if (inflater.factory == null) {
                LayoutInflaterCompat.setFactory2(inflater, MKAppLayoutInflaterFactory2Proxy(delegate) )
            }
        } catch (e: Exception) {
            // do nothing
        }
        return delegate
    }

這樣整個無痕埋點技術實現方案已經完成了

可以優化的點

當前技術實現中需要在Style.xml中添加相關viewInflaterClass配置,有些耦合

優化技術實現方案:可以通過插樁方式修改viewInflaterClassName的值,對于我們自己業務類(通過context判斷)設置我們自定義的InflaterClassName,第三方sdk可以控制保持不變

總結?

原文鏈接:https://blog.csdn.net/dbs1215/article/details/128857690

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新