@ohos.vibrator (振动)提供控制设备马达振动的能力,在.on()方法使用完毕后,需及时调用对应的.off()方法注销监听,避免导致内存泄漏。
调用.on()监听接口后,只要存在对应的.off()调用(即取消全部或部分监听)时,不会告警;仅当代码中不存在任何.off()调用时,才产生告警。
// rules.json
{
"rules": {
"arkts": {
"ResourceLeak": [
{
"ruleId": "VibratorListenerNotOff",
"severity": "error",
"skip": false
}
]
}
}
} import { vibrator } from '@kit.SensorServiceKit';
import Ability from '@ohos.app.ability.Ability';
enum eType {
type = 'vibratorStateChange'
}
/**
* 正例:正确释放资源
*/
export class TestRelease extends Ability {
private vibratorCallBack1 = (data: vibrator.VibratorStatusEvent) => {
console.info('vibrator state callback1 info:', JSON.stringify(data));
}
private vibratorCallBack2 = (data: vibrator.VibratorStatusEvent) => {
console.info('vibrator state callback2 info:', JSON.stringify(data));
}
onCreate(): void {
vibrator.on('vibratorStateChange', this.vibratorCallBack1);
vibrator.on(eType.type, this.vibratorCallBack2);
}
onDestroy(): void {
vibrator.off('vibratorStateChange', this.vibratorCallBack1);
vibrator.off(eType.type, this.vibratorCallBack2);
}
} import { vibrator } from '@kit.SensorServiceKit';
import Ability from '@ohos.app.ability.Ability';
enum eType {
type = 'vibratorStateChange'
}
/**
* 反例:未释放资源
*/
export class TestNotRelease extends Ability {
private vibratorCallBack1 = (data: vibrator.VibratorStatusEvent) => {
console.info('vibrator state callback1 info:', JSON.stringify(data));
}
private vibratorCallBack2 = (data: vibrator.VibratorStatusEvent) => {
console.info('vibrator state callback2 info:', JSON.stringify(data));
}
onCreate(): void {
vibrator.on('vibratorStateChange', this.vibratorCallBack1); // leak
vibrator.on(eType.type, this.vibratorCallBack2); // leak
}
} Code Scanner代码检查规则的配置指导请参考1.6.3 代码检查工具(codescanner)