封装Tracking 工具(数据埋点工具)
数据埋点是指在软件或者应用的关键位置插入一段代码,以用来统计用户信息。在面通中,数据埋点是统计用户在试题详情页的停留时间。封装数据埋点工具类,其中声明了两个实例方法分别是record记录方法以及report上传方法。而persistent虽然也可以实现持久化,但其存储数据不超过2kb,而首选项数据会保存在沙箱中。
·
数据埋点是指在软件或者应用的关键位置插入一段代码,以用来统计用户信息。在面通中,数据埋点是统计用户在试题详情页的停留时间。
封装数据埋点工具类,其中声明了两个实例方法分别是record记录方法以及report上传方法。
知识点准备:首选项preference
- 用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。
- 数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。
而persistent虽然也可以实现持久化,但其存储数据不超过2kb,而首选项数据会保存在沙箱中。
封装:
需要在Tracking类中封装两个实例方法,record需要三个参数,进入试题的开始时间,划出试题的结束时间,以及试题的id。在书写时,需要封装一个getStore()方法。
import { TimeItem } from '../../models'
import { http } from './Http'
import { preferences } from '@kit.ArkData'
import { JSON } from '@kit.ArkTS'
interface TimeList {
timeList:TimeItem[]
}
class Tracking {
store?: preferences.Preferences
dataKey: string = 'time-list'
// 初始化实例 只会初始化一次
[获取上下文](https://blog.csdn.net/m0_71406834/article/details/143746056?fromshare=blogdetail&sharetype=blogdetail&sharerId=143746056&sharerefer=PC&sharesource=m0_71406834&sharefrom=from_link)
getStore() {
if (!this.store) {
const context = AppStorage.get<Context>('context')
this.store = preferences.getPreferencesSync(context, { name: 'tracking-store' })
}
return this.store
}
// 记录埋点信息
async record(startTime: number, endTime: number, questionId: string) {
// 先初始化一个数组,用于存储数据
// 拿到一个字符串数组
const json = this.getStore().getSync(this.dataKey, '[]')
// 转为对象数组
const list = JSON.parse(json as string) as TimeItem[]
// 添加数据
list.push({ startTime, endTime, questionId })
// 持久化数据
this.getStore().putSync(this.dataKey, JSON.stringify(list))
await this.getStore().flush()
}
// 上报埋点信息
async report(force: boolean = false) {
const json = this.getStore().getSync(this.dataKey, '[]')
const list = JSON.parse(json as string) as TimeItem[]
// 如果数据大于5条在上报 或 强制上报(不足5条退出应用了也要上报)
if (list.length >= 5 || (force && list.length )) {
await http.request<null, TimeList>({ url: 'time/tracking', method: 'post', data: { timeList: list } })
// 上报完成删除数据
this.getStore().deleteSync(this.dataKey)
await this.getStore().flush()
}
}
}
export const tracking = new Tracking()
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐



所有评论(0)