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 小时前
鸿蒙跨端框架Flutter学习:CustomTween自定义Tween详解
学习·flutter·harmonyos
mocoding4 小时前
使用鸿蒙化flutter_fluttertoast替换Flutter原有的SnackBar提示弹窗
flutter·华为·harmonyos
2601_949593657 小时前
高级进阶React Native 鸿蒙跨平台开发:LinearGradient 背景渐变与主题切换
react native·react.js·harmonyos
深海呐7 小时前
鸿蒙基本UI控件(List相关-含Grid)
harmonyos·harmonyos ui·harmonyos list·harmonyos grid·鸿蒙列表view·art列表ui控件·art网格ui控件
小雨青年7 小时前
鸿蒙 HarmonyOS 6 | AI Kit 集成 Core Speech Kit 语音服务
人工智能·华为·harmonyos
一起养小猫8 小时前
Flutter for OpenHarmony 实战 表单处理与验证完整指南
android·开发语言·前端·javascript·flutter·harmonyos
摘星编程9 小时前
React Native鸿蒙版:自定义useMask输入掩码
react native·react.js·harmonyos
mocoding9 小时前
使用Flutter设置UI三方库card_settings_ui重构鸿蒙版天气预报我的页面
flutter·ui·harmonyos
摘星编程10 小时前
OpenHarmony + RN:自定义useValidator表单验证
react native·react.js·harmonyos
摘星编程11 小时前
OpenHarmony环境下React Native:自定义useFieldArray字段数组
react native·react.js·harmonyos