订阅滑动丢帧事件(ArkTS)
接口说明
API接口的具体使用说明(参数使用限制、具体取值范围等)。
接口名 | 描述 |
---|---|
addWatcher(watcher: Watcher): AppEventPackageHolder | 添加应用事件观察者,以添加对应用事件的订阅。 |
removeWatcher(watcher: Watcher): void | 移除应用事件观察者,以移除对应用事件的订阅。 |
开发步骤
以实现对用户滑动列表触发丢帧生成的滑动丢帧事件订阅为例,说明开发步骤。
-
编辑工程中的“entry > src > main > ets > entryability > EntryAbility.ets”文件,在onCreate函数中添加系统事件的订阅,示例代码如下:
import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit'; hiAppEvent.addWatcher({ // 开发者可以自定义观察者名称,系统会使用名称来标识不同的观察者 name: "watcher", // 开发者可以订阅感兴趣的系统事件,此处是订阅了滑动丢帧事件 appEventFilters: [ { domain: hiAppEvent.domain.OS, names: [hiAppEvent.event.SCROLL_JANK] } ], // 开发者可以自行实现订阅实时回调函数,以便对订阅获取到的事件数据进行自定义处理 onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => { hilog.info(0x0000, 'testTag', `HiAppEvent onReceive: domain=${domain}`); for (const eventGroup of appEventGroups) { // 开发者可以根据事件集合中的事件名称区分不同的系统事件 hilog.info(0x0000, 'testTag', `HiAppEvent eventName=${eventGroup.name}`); for (const eventInfo of eventGroup.appEventInfos) { // 开发者可以对事件集合中的事件数据进行自定义处理,此处是将事件数据打印在日志中 hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo=${JSON.stringify(eventInfo)}`); } } } });
-
编辑工程中的“entry > src > main > ets > pages > Index.ets”文件,添加一个列表控件,在列表的滚动事件中做一些耗时操作,示例代码如下:
// 模拟列表元素 private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23] // 创建List控件 List({ space: 10 }) { ForEach(this.arr, (item: number) => { ListItem() { Text(`${item}`) .width('100%') .height(100) .fontSize(20) .fontColor(Color.White) .textAlign(TextAlign.Center) .borderRadius(10) .backgroundColor(0x007DFF) } }) } .onScrollIndex((firstIndex: number) => { let i = 1; while (i<10000) { // 在列表滑动事件中做一些耗时操作 console.log("do something"); i++; } })
-
点击IDE界面中的运行按钮,运行应用工程,在页面中滑动列表,当系统检测到故障时触发滑动丢帧事件。
-
可以在Log窗口看到对系统事件数据的处理日志:
HiAppEvent onReceive: domain=OS HiAppEvent eventName=SCROLL_JANK HiAppEvent eventInfo={"domain":"OS","name":"SCROLL_JANK","eventType":1,"params":{"ability_name":"EntryAbility","begin_time":1710322495739,"bundle_name":"com.example.myapplication1","bundle_version":"1.0.0","duration":801,"max_app_frametime":3,"max_app_seq_frames":0,"max_render_frametime":8,"max_render_seq_frames":0,"process_name":"com.example.myapplication1","time":1710322497495,"total_app_frames":98,"total_app_missed_frames":0,"total_render_frames":80,"total_render_missed_frames":0}}