本文主要是介绍Android 轻量级无痕埋点事件监听,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
code小生 一个专注大前端领域的技术平台公众号回复Android
加入安卓技术群
作者:R7_Perfect
链接:https://www.jianshu.com/p/997674931225声明:本文已获
R7_Perfect
授权发表,转发等请联系原作者授权
全链路无痕埋点作为一个明确的需求,目前已经有较多的实现方案。本人认为比较好的是Hook+Aop方案
hook是利用view的AccessibilityDelegate接口做代理, RecyclerView的mScrollListeners对象替换等等
Aop可以用AspectJ实现
本文是提供一个较为轻量级的做法,实现对所有view的touch事件监控 首先我们来复习下相关知识点:
1. View的层级
首先我们来了解下View的层级:引用一张网图:
Window的根View是DecorView,通过iewRoot管理,此处不作扩展
DecorView是个ViewGroup,我们目标是监听DecorView的touch事件
那么如何监听:
2. 事件分发
view和子view的事件分发可以用伪代码表示:
fun dispatchTouchEvent(ev: MotionEvent) {var consume = falseif(onInterceptTouchEvent(ev)) {consume = onTouchEvent(ev)} else {consume = child.dispatchTouchEvent(ev)}return consume
}
ViewGroup中的dispatchTouchEvent会分发到onInterceptTouchEvent中, 在onInterceptTouchEvent中就可以记录日志,并且return super.onInterceptTouchEvent(event)不会影响子view的调用
监听方案:
DecorView我们无法改写,我们可以用一个ProxyView插入在DecorView之后,只去监听onInterceptTouchEvent
将第一张图中Activity->PhoneWindow->DecorView->titleBar+mContentParent
变为Activity->PhoneWindow->DecorView->ProxyView->titleBar+mContentParent
代理方案:
使用插装思想来插入ProxyView,利用ActivityLifecycleCallbacks的onActivityResumed方法,在每个Activity resume之后,插入ProxyView:首先在入口启动时注册一个ActivityLifecycleCallbacks:
object HookTrack {private var activityLifeCycleRegister = falsefun init(application: Application?) {if (application == null) {Log.e("e", "Please init with the param \"Application\"/")throw RuntimeException()}if (!activityLifeCycleRegister) {application.registerActivityLifecycleCallbacks(HookActivityLifecycleCallbacks())activityLifeCycleRegister = true}}
}
HookActivityLifecycleCallbacks的实现:
internal class HookActivityLifecycleCallbacks : ActivityLifecycleCallbacks {override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}override fun onActivityStarted(activity: Activity) {}override fun onActivityResumed(activity: Activity) {if (!activityNameSet.contains(activity.javaClass.name)) {val viewGroup = activity.window.decorView as ViewGroupif (viewGroup != null) {val size = viewGroup.childCountval customFrameLayout = ProxyFrameLayout(activity)for (i in 0 until size) {val view = viewGroup.getChildAt(i)if (view != null) {viewGroup.removeView(view)customFrameLayout.addView(view)}}viewGroup.addView(customFrameLayout)}activityNameSet.add(activity.javaClass.name)}}override fun onActivityPaused(activity: Activity) {}override fun onActivityStopped(activity: Activity) {}override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}override fun onActivityDestroyed(activity: Activity) {}companion object {var activityNameSet: MutableSet<String> = HashSet()}
}
遍历decorView对象,将其子view全部放到ProxyFrameLayout,再将ProxyFrameLayout加到decorView,形成代理
此处我们用activityNameSet防止重复插入ProxyFrameLayout 在用ProxyFrameLayout用中实现上述用onInterceptTouchEvent用:
class ProxyFrameLayout(private val resumedActivity: Activity) : FrameLayout(resumedActivity) {override fun onInterceptTouchEvent(event: MotionEvent): Boolean {when (event.action) {MotionEvent.ACTION_DOWN -> {//ACTION_DOWN do some thing}MotionEvent.ACTION_MOVE -> {//ACTION_MOVE do some thing}MotionEvent.ACTION_UP -> {//ACTION_UP do some thing}}return super.onInterceptTouchEvent(event)}
}
现在实现了“根”view的事件监听,我们如何来获知具体是哪个view呢:
可以通过屏幕上的像素点,遍历view,计算当前像素点在哪个view:
private fun findEventSrcView(event: MotionEvent, srcView: View): View? {if (srcView is ViewGroup) {val viewGroup = srcViewval size = viewGroup.childCountfor (i in 0 until size) {val view = viewGroup.getChildAt(i)if (view !is ProxyFrameLayout && isEventInView(event, view)) {val tmpRetView = findEventSrcView(event, view)if (tmpRetView != null) {return tmpRetView}}}} else if (isEventInView(event, srcView)) {return srcView}return null}/*** 判断是否在view的rect范围内* @param event* @param srcView* @return*/private fun isEventInView(event: MotionEvent, srcView: View): Boolean {val currentViewRect = Rect()if (srcView.getGlobalVisibleRect(currentViewRect)) {val rectF = RectF(currentViewRect)if (rectF.contains(event.rawX, event.rawY)) {return true}}return false}
所以我们的ProxyFrameLayout中的nInterceptTouchEvent就变成了:
override fun onInterceptTouchEvent(event: MotionEvent): Boolean {when (event.action) {MotionEvent.ACTION_DOWN -> {val touchViewDown = findEventSrcView(event, this)if (touchViewDown != null) {Log.d(Constants.TAG, "Activity:" + resumedActivity::class.java.name+ "- ACTION_DOWN:" + touchViewDown::class.java.name)}}MotionEvent.ACTION_MOVE -> {}MotionEvent.ACTION_UP -> {val touchViewUp = findEventSrcView(event, this)if (touchViewUp != null) {Log.d(Constants.TAG, "Activity:" + resumedActivity::class.java.name+ "- ACTION_UP:" + touchViewDown::class.java.name)}}}return super.onInterceptTouchEvent(event)}
至此,每个子view的touch事件就监听到了
另外:由于子view重名的会很多,如果直接打印view的名字无法区分 我们需要打印整个view的全链路才有意义:
在此我们遍历view,通过view.parent方法一路寻找到根节点才结束:
fun getAbsolutePath(view: View?): String {if (view == null) {return ""}if (view.parent == null) {return "rootView"}var path = "";var temp = view!!while (temp.parent != null && temp.parent is View) {var index = 0try {index = indexOfChild(temp.parent as ViewGroup, temp)} catch (e: Exception) {}path = "${temp.javaClass.simpleName}[$index]/${path}"temp = temp.parent as View}return path}private fun indexOfChild(parent: ViewGroup?, child: View): Int {if (parent == null) {return 0}val count = parent.childCountvar j = 0for (i in 0 until count) {val view = parent.getChildAt(i)if (child.javaClass.isInstance(view)) {if (view === child) {return j}j++}}return -1}
运行后打印的效果:点击一个button:
robin.scaffold.jet D/Track: Activity:robin.scaffold.jet.MainActivity- ACTION_DOWN:ProxyFrameLayout[0]/LinearLayout[0]/FrameLayout[0]/FitWindowsLinearLayout[0]/ContentFrameLayout[0]/DrawerLayout[0]/CoordinatorLayout[0]/ConstraintLayout[0]/FragmentContainerView[0]/ConstraintLayout[0]/AppCompatButton[0]/
robin.scaffold.jet D/Track: Activity:robin.scaffold.jet.MainActivity- ACTION_UP:ProxyFrameLayout[0]/LinearLayout[0]/FrameLayout[0]/FitWindowsLinearLayout[0]/ContentFrameLayout[0]/DrawerLayout[0]/CoordinatorLayout[0]/ConstraintLayout[0]/FragmentContainerView[0]/ConstraintLayout[0]/AppCompatButton[0]/
点击RecycleView中的item:
robin.scaffold.jet D/Track: Activity:robin.scaffold.jet.ui.NavTestActivity- ACTION_DOWN:ProxyFrameLayout[0]/LinearLayout[0]/FrameLayout[0]/ActionBarOverlayLayout[0]/ContentFrameLayout[0]/ConstraintLayout[0]/FragmentContainerView[0]/ConstraintLayout[0]/SwipeRefreshLayout[0]/LinearLayout[0]/RecyclerView[0]/ConstraintLayout[2]/AppCompatTextView[0]/
robin.scaffold.jet D/Track: Activity:robin.scaffold.jet.ui.NavTestActivity- ACTION_UP:ProxyFrameLayout[0]/LinearLayout[0]/FrameLayout[0]/ActionBarOverlayLayout[0]/ContentFrameLayout[0]/ConstraintLayout[0]/FragmentContainerView[0]/ConstraintLayout[0]/SwipeRefreshLayout[0]/LinearLayout[0]/RecyclerView[0]/ConstraintLayout[2]/AppCompatTextView[0]/
ConstraintLayout[2]代表的是点中第三个item
至此,一个最简单的无痕touch事件监听实现完成.
此处是监听了所有view,当然也可以不通过onInterceptTouchEvent,而是实现AccessibilityDelegate,来监听实现了Click事件的view,读者可以自行实验
相关阅读
1 项目埋点的演进
2 Android 可视化埋点方案
3 MixPanel -Android 端埋点技术研究
4 不给你的 APP 加上自动换图标的功能吗?
5 探索 Glide 原理
如果你有写博客的好习惯
欢迎投稿
赞+在看,小生感恩❤️
这篇关于Android 轻量级无痕埋点事件监听的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!