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)
    }
相关推荐
Georgewu5 小时前
【HarmonyOS】鸿蒙应用开发Text控件常见错误
harmonyos
Georgewu7 小时前
【HarmonyOS】富文本编辑器RichEditor详解
harmonyos
zhanshuo13 小时前
鸿蒙应用调试与测试实战全指南:高效定位问题,性能优化必备技巧+实用代码示例
harmonyos
万少17 小时前
2025中了 聊一聊程序员为什么都要做自己的产品
前端·harmonyos
幽蓝计划1 天前
HarmonyOS NEXT仓颉开发语言实战案例:动态广场
华为·harmonyos
万少2 天前
第五款 HarmonyOS 上架作品 奇趣故事匣 来了
前端·harmonyos·客户端
幽蓝计划2 天前
HarmonyOS NEXT仓颉开发语言实战案例:电影App
华为·harmonyos
HMS Core2 天前
HarmonyOS免密认证方案 助力应用登录安全升级
安全·华为·harmonyos
生如夏花℡2 天前
HarmonyOS学习记录3
学习·ubuntu·harmonyos
jie_07542 天前
鸿蒙系统(HarmonyOS)4.2 设备上实现无线安装 APK 并调试
华为·harmonyos