华为ArkUI-X 指南二 跨端代码统一接口

不同平台的原生代码要和UI层通信,如果在代码里面随用随写,那过不了多久,就会成为屎山代码。

最好一开始就清晰的规划好。

特别是要用第三方SDK,每个平台的原生sdk都得写一套代码时。统一的接口非常有必要。

1.在ArkUI利用操作系统识别,进入同接口不同过程:

export function getPlatformImpl(): PlatformInterface {
  //获得设备系统名
  const osName: string = deviceInfo.osFullName;
  if (osName.startsWith('OpenHarmony')) {
    //鸿蒙5
    return new HarmonyPlatform();
  } else if (osName.startsWith('Android')) {
    //安卓
    return new AndroidPlatform();
  } else if (osName.startsWith('iOS')) {
    //iOs
    //return new IosPlatform();
  }
  throw new Error('Unsupported platform');
}

暂未开发的平台,就注释掉。

2.定义接口

/**
 * 各平台统一接口
 */
export interface PlatformInterface {
  //【注意这行,不建议将桥的Object作为接口参数,所以这行应该删除。】
  bridgeAuth: bridge.BridgeObject | null ;
  /** 获取用户信息(uid/phone) 【自定义AuthResult代替了桥的Object】*/
  getCurrentUser(): Promise<AuthResult | null>;
  ...
  ..
  .
}

3.编写平台类,实现接口

const TAG:string = 'AndroidPlatform';
export class AndroidPlatform implements PlatformInterface {
  //创建桥
  public bridgeAuth = bridge.createBridge('AuthUtil');
  //距离获取用户信息
  async getCurrentUser(): Promise<AuthResult | null> {
    try {
      //通过桥调用原生Android的方法。
      const result = await this.bridgeAuth.callMethod('getCurrentUser');
      if (!result) {
        return null;
      }
      
      // 添加原始数据日志,帮助调试。
      showLog.log(TAG, `原始返回数据:${result.toString()}`);
      
      // 解析返回的 JSON 字符串
      const response: AndroidBirdgeResult<AuthResult> = JSON.parse(result.toString());
      
      // 检查错误信息
      if (response.error) {
        throw new customError(response.error.code);
      }

      // 使用 response.data,因为它已经是正确格式的对象
      const userInfo = response.data as AuthResult;
      showLog.log(TAG, `用户信息: ${userInfo.uid} - ${userInfo.phone}`);
      return userInfo;
      
    } catch (error) {
      showLog.error(TAG, `获取用户信息失败:${error}`);
      throw new customError(203817730);
    }
  }

这里使用了自定义console.log,打印了TAG,以便在Android studio中筛选日志。

自定义了错误类,统一管理多平台错误码。

自定义了response对象,和Android原生map格式一致。

4.在前端使用

private platform = getPlatformImpl();

this.platform.getCurrentUser()
      .then((userInfo:AuthResult) => {
            //处理用户信息
    })

注意,HarmonyOS端的同功能代码,比如AGC登录、云数据库代码,会报错,参考避坑指南一的解决办法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值