使用uts调用鸿蒙原生API

2025-03-08 19:14:34
164次阅读
0个评论

使用uts调用鸿蒙原生API

今天我发现使用uts开发插件超级简单,不信我们来看

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
    }
}

//打电话
export function 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`);
        }
    });
}

//发送短信
export function sendSms(telephone: PhoneType, smsContext?: string) {
    if(!telephone) {
        console.error(`telephone is required`);
        return;
    }
    
    let contactInfo: Array<smsInfo> = new Array();
    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
export function 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();
		}

好的,今天就到这

收藏00

登录 后评论。没有帐号? 注册 一个。