在鸿蒙开发的广阔天地中,UTS(Unified Type System)正以其简洁高效的特性,为开发者带来全新的开发体验。今天,我就来和大家分享一下,如何运用 UTS 轻松调用鸿蒙原生 API,实现各种实用功能。
先来看看核心代码部分:
import call from'@ohos.telephony.call';
import common from'@ohos.app.ability.common';
import Want from'@ohos.app.ability.Want';
import { BusinessError } from'@kit.BasicServicesKit';
import batteryInfo from'@ohos.batteryInfo';
import { GetBatteryInfo, GetBatteryInfoOptions, GetBatteryInfoSuccess, GetBatteryInfoResult, GetBatteryInfoSync } from'../interface.uts';
import { scanCore, scanBarcode } from'@kit.ScanKit';
// 导入默认界面需要的日志模块和错误码模块
import { hilog } from'@kit.PerformanceAnalysisKit';
import { BusinessError } from'@kit.BasicServicesKit';
type PhoneType = string;
class smsInfo {
telephone: PhoneType;
constructor(telephone: PhoneType) {
this.telephone = telephone
}
}
//打电话
exportfunction makeCall(telephone: PhoneType) {
if(!telephone) {
console.error(`telephone is required`);
return;
}
call.makeCall(telephone, (err: BusinessError) => {
if (err) {
console.error(`makeCall fail, err->${JSON.stringify(err)}`);
} else {
console.log(`makeCall success`);
}
});
}
//发送短信
exportfunction sendSms(telephone: PhoneType, smsContext?: string) {
if(!telephone) {
console.error(`telephone is required`);
return;
}
let contactInfo: Array<smsInfo> = newArray();
contactInfo[0] = new smsInfo(telephone);
const context = getContext() as common.UIAbilityContext;
let want: Want = {
bundleName: 'com.ohos.mms',
abilityName: 'com.ohos.mms.MainAbility',
parameters: {
contactObjects: JSON.stringify(contactInfo),
content: smsContext || '',
pageFlag: 'conversation'
}
};
context.startAbility(want)
.then(() => {
console.info('Succeed to invoke startAbility.');
})
.catch((err: BusinessError) => {
console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
});
}
//退出 APP
exportfunction exitAPP() {
try {
let context = getContext() as common.UIAbilityContext;
context.terminateSelf((err: BusinessError) => {
if (err.code) return;
});
} catch (err) {
// 捕获同步的参数错误
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
}
}
大家有没有发现,这和 ArkTS 的开发方式有着异曲同工之妙,简洁且直观。
在实际使用中,只需简单地引入相应功能模块,就能快速实现所需功能。例如,添加退出应用方法时,只需如下调用退出应用模块:
// 添加退出应用方法
exitApplication() {
// 调用退出应用模块
exitAPP();
}
UTS 的这种简洁性,大大降低了开发门槛,让开发者能够更高效地利用鸿蒙原生 API 构建应用。无论是调用通讯功能,还是实现应用控制,都能轻松应对。往后,我们将继续深入探索 UTS 的更多特性和应用,为大家带来更多实用的开发技巧和经验分享,助力大家在鸿蒙开发的道路上一往无前!
uts,全称 uni type script,统一、强类型、脚本语言。
它可以被编译为不同平台的编程语言,如: