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)
    }
相关推荐
一梦南柯3 小时前
HarmonyOS NEXT快速入手IBest-UI组件库
harmonyos
二流小码农4 小时前
鸿蒙开发:权限管理之权限声明
android·ios·harmonyos
全栈若城7 小时前
67.Harmonyos NEXT 图片预览组件之性能优化策略
性能优化·harmonyos·harmonyos next
觉醒法师7 小时前
HarmonyOS NEXT - 电商App实例三( 网络请求axios)
前端·华为·typescript·axios·harmonyos·ark-ts
全栈若城10 小时前
63.Harmonyos NEXT 图片预览组件之手势处理实现
华为·harmonyos·harmonyos next
Bowen_J10 小时前
HarmonyOS架构详解
华为·harmonyos·arkts
蓝枫Amy11 小时前
HarmonyOS应用程序包概述
程序员·harmonyos
ChinaDragon11 小时前
HarmonyOS:UIAbility组件启动模式
harmonyos
轻口味11 小时前
【每日学点HarmonyOS Next知识】状态栏字体、生命周期、自定义对话框屏幕中间、透明度、tab居中
pytorch·华为·harmonyos·harmonyosnext
林钟雪11 小时前
HarmonyNext实战:基于ArkTS的高性能图像处理应用开发
harmonyos