HarmonyNext APP网络请求监听SDK的封装实现

文章目录

概要

以前在做安卓APP开发时,使用"com.readystatesoftware.chuck" ​​SDK,监听Http请求和应答数据,非常方便便捷,因此最近在做鸿蒙项目时,想实现类似的功能,于是就封装了一个类似功能的SDK。​

整体架构流程

1、SDK实现接口列表和接口详情页面,列表页可通过文字筛选,详情页展示请求参数和应答数据的详细信息;

2、在通知栏展示最新调用的接口,点击可跳转到接口列表页面;

3、封装供外部调用的函数,APP通过网络拦截器捕获网络应答数据,并通过此函数将数据传递给SDK进行展示。在SDK中将数据保存到本地数据库中实现数据持久化。

技术细节

1、通知栏展示数据

typescript 复制代码
private notify(title: string, text: string, additionalText: string) {
  notificationManager.isNotificationEnabled().then((data: boolean) => {
    if (data) {
      this.addNotification(title, text, additionalText)
    }
  }).catch((err: BusinessError) => {
    hilog.error(1, TAG, `isNotificationEnabled fail: ${JSON.stringify(err)}`);
  });
}

private addNotification(title: string, text: string, additionalText: string) {
  //获取当前应用的bundleName
  let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_HAP_MODULE | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_ABILITY;
  let bundle = bundleManager.getBundleInfoForSelfSync(bundleFlags);
  let abilityName = 'EntryAbility'
  if (bundle.hapModulesInfo.length > 0 && bundle.hapModulesInfo[0].mainElementName) {
    abilityName = bundle.hapModulesInfo[0].mainElementName
  }
  let wantAgentInfo:wantAgent.WantAgentInfo = {
    wants: [
      {
        deviceId: '',
        bundleName: bundle.name,
        abilityName: abilityName,
        uri: 'ResponseListPage',
        parameters: {}
      }
    ],
    actionType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
  };

  wantAgent.getWantAgent(wantAgentInfo)
    .then((wantAgent) => {
      // publish回调
      let publishCallback = (err: BusinessError): void {
        if (err) {
          hilog.error(1, TAG, `publish failed, code is ${err.code}, message is ${err.message}`);
        } else {
          hilog.info(1, TAG, "publish success");
        }
      }
      // 通知Request对象
      let notificationRequest: notificationManager.NotificationRequest = {
        id: systemDateTime.getTime(),
        groupName: 'network',
        content: {
          notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
          normal: {
            title: title,
            text: text,
            additionalText: additionalText
          }
        },
        wantAgent: wantAgent
      };
      notificationManager.publish(notificationRequest, publishCallback);
    })
    .catch((err: Error) => {
      console.error(`get wantAgent failed because ${JSON.stringify(err)}`);
    })
}

2、实现点击通知栏消息,跳转到SDK内页面

由于SDK是独立于APP的,实现路由跳转需要借助APP来实现。

1)、在SDK内通过routeName为Entry声明路由名称

less 复制代码
@Component
@Entry({routeName: 'ResponseListPage'})
export struct ResponseListPage

2)、创建通知时,指定点击跳转的uri参数为上一步声明的routeName

yaml 复制代码
let wantAgentInfo:wantAgent.WantAgentInfo = {
   wants: [
     {
       deviceId: '',
       bundleName: bundle.name,
       abilityName: abilityName,
       uri: 'ResponseListPage',
       parameters: {}
     }
   ],
   actionType: wantAgent.OperationType.START_ABILITY,
   requestCode: 0,
   wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG

3)、点击通知栏的通知时,会跳转回APP,并自动调用EntryAbility.onNewWant函数。因此我们可以在onNewWant函数中进行路由跳转

php 复制代码
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  router.pushNamedRoute({name: want.uri})
}

小结

在开发HarmonyNext APP时,也可以直接调用已经封装好的SDK,gitee地址​​@sunshine/toolkit · git_zhaoyang/MultiList - 码云 - 开源中国​

SDK调用方式如下

php 复制代码
1、以网络请求框架为axios为例,在网络请求拦截器中,添加如下代码:

    import netWorkInterceptor from '@sunshine/toolkit/src/main/ets/network/NetWorkInterceptor';
    
    axios.interceptors.response.use((response: AxiosResponse) => {
      netWorkInterceptor.interceptor({
          url: response.config.url,
          headers: response.headers,
          method_type: response.config.method,
          body: response.config.params,
          response: response.data,
          status: response.status,
          message: response.statusText,
          request_time: response.headers.date,
          durations: response.performanceTiming
        })
        return response;
    }, (error: AxiosError) => {
      error
    });

2、在EntryAbility中,添加如下代码:

    import netWorkInterceptor from '@sunshine/toolkit/src/main/ets/network/NetWorkInterceptor';
    
    onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        netWorkInterceptor.route(want)
    }
相关推荐
bestadc20 小时前
鸿蒙 所有API缩略图鉴
harmonyos
马剑威(威哥爱编程)1 天前
HarmonyOS 5.0 分布式数据协同与跨设备同步
分布式·华为·harmonyos·arkts·harmonyos-next
茄子忍者烧纸尿裤1 天前
鸿蒙开发——4.ArkTS快速入门指南
华为·harmonyos
_waylau2 天前
【HarmonyOS NEXT+AI】问答05:ArkTS和仓颉编程语言怎么选?
人工智能·华为·harmonyos·arkts·鸿蒙·仓颉
鸿蒙布道师2 天前
鸿蒙NEXT开发动画案例3
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei
雪芽蓝域zzs2 天前
HarmonyOS开发-组件市场
华为·harmonyos
__Benco2 天前
OpenHarmony平台驱动开发(十),MMC
人工智能·驱动开发·harmonyos
何玺2 天前
鸿蒙电脑:五年铸剑开新篇,国产操作系统新引擎
华为·电脑·harmonyos
__Benco2 天前
OpenHarmony平台驱动开发(十一),PIN
人工智能·驱动开发·harmonyos