大量文本的浏览进度和浏览时长统计
埋点需求,Android App 需要在onResume 和 onPause 方法中计算浏览的时长,同时上报浏览的进度。
浏览进度Rate具体的计算方式的具体过程:
1、在滚动屏幕过程中,通过 textContent?.viewTreeObserver?.addOnScrollChangedListener 来记录屏幕滚动的位置
2、在滚动监听里通过textContent?.getLocationOnScreen(location)获取在屏幕的具体位置,同时,
计算出visibleHeight = screenHeight - location[1] 当前文本的可见高度
3、当可见高度超过目标的高度,则认为已经全部浏览,rate = 100% ,同时移除滚动监听textContent?.viewTreeObserver?.removeOnScrollChangedListener(mScrollChangeListener)
核心代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| private var totalHeight: Int = 0 private var visibleHeight: Int = 0 private var screenHeight = 0
fun getViewRate(): String? = if (totalHeight <= 0 || visibleHeight < 0) null else "${(visibleHeight * 100 / totalHeight)}%"
private fun bindViewTreeObserver() { cleanCache() contentTv.post { totalHeight = contentTv.height screenHeight = ScreenUtils.getScreenHeight(context) contentVisibleRate() } contentTv.viewTreeObserver.addOnScrollChangedListener(mScrollChangeListener) }
private fun cleanCache() { totalHeight = 0 screenHeight = 0 visibleHeight = 0 }
private val mScrollChangeListener = ViewTreeObserver.OnScrollChangedListener { contentVisibleRate() }
private fun contentVisibleRate() { val location = IntArray(2) contentTv.getLocationOnScreen(location) visibleHeight = (screenHeight - location[1]).coerceAtLeast(visibleHeight) if (visibleHeight >= totalHeight) { visibleHeight = totalHeight removeOnScrollChangedListener() } }
private fun removeOnScrollChangedListener() { mScrollChangeListener?.let { contentTv.viewTreeObserver.removeOnScrollChangedListener(mScrollChangeListener) } }
|