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

zhouchy
发布于 2025-3-8 21:38
浏览
0收藏

文章目录

概要

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

整体架构流程

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

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

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

技术细节

1、通知栏展示数据

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)}`);
    })
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.

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

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

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

@Component
@Entry({routeName: 'ResponseListPage'})
export struct ResponseListPage
  • 1.
  • 2.
  • 3.


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

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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

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

onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  router.pushNamedRoute({name: want.uri})
}
  • 1.
  • 2.
  • 3.

小结

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

SDK调用方式如下

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)
    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.


©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2025-3-14 19:47:36修改
收藏
回复
举报


回复
    相关推荐