HarmonyOS鸿蒙Next中适配多版本API,有类似android注解限制api使用的方式吗?
HarmonyOS鸿蒙Next中适配多版本API,有类似android注解限制api使用的方式吗? 我需要同时适配API13和API20,有一个能力只有API20才能适配,目前的做法是获取设备API用if判断,这样写感觉好麻烦,有什么好的方法吗?
3 回复
【背景知识】 ArkTS支持TS5.0之前的TS装饰器语法。关于装饰器的定义和运行时行为,可以参考TS官方文档。需要注意,如果是在ets文件中定义装饰器,则需要同时满足ArkTS的语法规则,比如不能使用any等。
【解决方案】 示例代码如下:
export function ApiDescriptor(apiVersion: number) {
return (target: Object, key: string, descriptor: PropertyDescriptor) => {
const originalMethod: Function = descriptor.value;
descriptor.value = (...args: Object[]) => {
console.log(`flag: ${apiVersion}`);
// 获取设备api版本
let currentVersion = 13;
if (currentVersion < apiVersion) {
return;
}
originalMethod(args);
};
return descriptor;
};
}
@Entry
@Component
struct Index {
build() {
RelativeContainer() {
Button('click test')
.onClick(() => {
this.test()
})
}
.height('100%')
.width('100%')
}
@ApiDescriptor(20)
test() {
console.log('flag: test');
}
}
更多关于HarmonyOS鸿蒙Next中适配多版本API,有类似android注解限制api使用的方式吗?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
HarmonyOS Next提供@ohos.hap.level注解限制API使用。在module.json5中配置compileSdkVersion指定编译SDK版本,使用@ohos.hap.level标注API调用,系统会根据设备API级别进行兼容性检查。


