HarmonyOS 鸿蒙Next rcp相关demo

发布于 1周前 作者 yibo5220 来自 鸿蒙OS

HarmonyOS 鸿蒙Next rcp相关demo

提供一下rcp网络相关的demo,主要包含多种常用拦截器interceptor的实现、JSON的解析(json与数据类互转且属性不缺失)、网络请求时loading的加载取消。

3 回复

拦截器参考下述demo:

import { rcp } from '@kit.RemoteCommunicationKit';

class ResponseCache {
  private readonly cache: Record<string, rcp.Response> = {};

  getResponse(url: string): rcp.Response {

    return this.cache[url];

  }

  setResponse(url: string, response: rcp.Response): void {

    this.cache[url] = response;

  }
}

class ResponseCachingInterceptor implements rcp.Interceptor {
  private readonly cache: ResponseCache;

  constructor(cache: ResponseCache) {

    this.cache = cache;

  }

  async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {

    const url = context.request.url.href;

    const responseFromCache = this.cache.getResponse(url);

    if (responseFromCache) {

      return Promise.resolve(responseFromCache);

    }

    const promise = next.handle(context);

    promise.then((resp) => {

      resp.statusCode;

      cache.setResponse(url, resp);

    });

    return promise;

  }
}

const cache = new ResponseCache();

async function testInterceptor() {

  const session = rcp.createSession({

    interceptors: [new ResponseCachingInterceptor(cache)]

  });

  const response1 = await session.get("https://xxxx");

  let request = new rcp.Request("https://xxxx", 'GET');

  const response2 = await session.fetch(request);

}

JSON解析参考下述demo:

//网络请求

export function httpRequestPost(url: string, requestData?: Object): Promise<ResponseResult> {

  let serverData: ResponseResult = new ResponseResult();

  let httpRequest = http.createHttp();

  let responseResult = httpRequest.request(url, {

    method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET

    // 根据自身业务需要添加header字段

    header: {

      'Content-Type': 'application/json'

    },

  });

  // Processes the data and returns.

  return responseResult.then((data) => {

    if (data.responseCode == 200) {

      // 处理返回结果

      let resultJson: ResponseResult = JSON.parse(data.result as string);

      if (resultJson.msg == 'success') {

        serverData.data = resultJson.data

      } else {

        serverData.data = resultJson.data

      }

      serverData.code = resultJson.code;

      serverData.msg = resultJson.msg;

    } else {

      // todo 请求失败,进行失败逻辑处理

       serverData.msg = `${$r('app.string.http_error_message')}&${data.responseCode}`;

    }

    return serverData;

  }).catch(() => {

    // todo 请求失败,进行失败逻辑处理

     serverData.msg = $r('app.string.http_error_message');

    return serverData;

  })

}

网络请求时loading的加载取消参考下述demo:

// CommonWindow.ets

import window from '[@ohos](/user/ohos).window';

import common from '[@ohos](/user/ohos).app.ability.common';

import { BusinessError } from '[@ohos](/user/ohos).base';

import { entryName } from './MainPage';

export class CommonWindow {

  private storage: LocalStorage | null = null;

  private subWindow: window.Window | null = null;

  private windowStage1: window.WindowStage | null = null

  private context: common.UIAbilityContext | null = null;

  private init() {

    this.context = getContext(this) as common.UIAbilityContext;

    let data: Data = { subWindowStage: null, storage: null };

    this.context.eventHub.emit("createWindow", data);

    this.windowStage1 = data.subWindowStage;

    this.storage = data.storage;

    console.log("aboutToAppear end createWindowStage");

    this.context.eventHub.on("closeWindow", (data: Data) => {

      this.destroySubWindow();

    })

  }

  showWindow() {

    this.init();

    if (this.subWindow) {

      console.log("subWindow is already exist");

      return;

    }

    try {

      if (!this.windowStage1) {

        console.error("this.windowStage1 is null");

        return;

      }

      this.windowStage1.createSubWindow('mySubWindow', (err: BusinessError, data) => {

        const errCode: number = err.code;

        if (errCode) {

          console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));

          return;

        }

        this.subWindow = (data as window.Window);

        console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data));

        if (!this.subWindow) {

          console.info('Failed to load the content. Cause: windowClass is null');

        } else {

          let names: Array<'status' | 'navigation'> = [];

          this.subWindow.setWindowSystemBarEnable(names);

          this.subWindow.setWindowTouchable(true);

          this.loadContent(entryName);

          this.showSubWindow();

        }

      });

    } catch (exception) {

      console.error('Failed to create the window. Cause: ' + JSON.stringify(exception));

    }

  }

private showSubWindow() {

    if (this.subWindow) {

      this.subWindow.showWindow((err: BusinessError) => {

        const errCode: number = err.code;

        if (errCode) {

          console.error('Failed to show the window. Cause: ' + JSON.stringify(err));

          return;

        }

        console.info('Succeeded in showing the window.');

      });

    } else {

      console.info('showSubWindow subWindow not created.');

    }

  }

  private destroySubWindow() {

    if (this.subWindow) {

      this.subWindow.destroyWindow((err) => {

        const errCode: number = err.code;

        if (errCode) {

          console.error('Failed to destroy the window. Cause:' + JSON.stringify(err));

          return;

        }

        this.subWindow = null

      });

    } else {

      console.info('showSubWindow subWindow not created.');

    }

  }

  private loadContent(path: string) {

    if (this.subWindow) {

      let that = this;

      let para: Record<string, number> = { 'PropA': 66 };

      that.storage = new LocalStorage(para);

      if (that.storage != null && this.subWindow != null) {

        that.storage.setOrCreate("windowObj", this.subWindow)

      }

      this.subWindow.loadContentByName(path, this.storage, (err: BusinessError) => {

        const errCode: number = err.code;

        if (errCode) {

          return;

        }

        if (this.subWindow) {

          this.subWindow.setWindowBackgroundColor('#cc000e03')

        }

      });

    } else {

      console.info('loadContent subWindow not created.');

    }

  }

}

export interface Data {

  subWindowStage: window.WindowStage | null,

  storage: LocalStorage | null

}

// MainPage.ets

import window from '[@ohos](/user/ohos).window';

export const entryName: string = 'loadingPage';

[@Entry](/user/Entry)({ routeName: entryName, storage: LocalStorage.getShared() })

[@Component](/user/Component)

export struct MainPage {

  [@LocalStorageLink](/user/LocalStorageLink)('PropA') var

number | undefined = 1;

  private subWindow: window.Window | undefined;

  build() {

    Column() {

      LoadingProgress().width(150)

    }

    .justifyContent(FlexAlign.Center)

    .height('100%')

    .width('100%')

  }

  // 页面生命周期:打开沉浸式

  onPageShow() {

    window.getLastWindow(getContext(this), (err, win) => {

      // 获取当前窗口的属性

      let prop: window.WindowProperties = win.getWindowProperties();

      // 打印当前窗口属性

      console.log(JSON.stringify(prop));

      win.setWindowLayoutFullScreen(true)

    })

  }

  // 页面生命周期:关闭沉浸式

  onPageHide() {

    window.getLastWindow(getContext(this), (err, win) => {

      win.setWindowLayoutFullScreen(false)

    })

  }

  aboutToAppear() {

    this.varA = LocalStorage.getShared().get<number>("PropA");

    this.subWindow = LocalStorage.getShared().get<window.Window>("windowObj");

  }

}

复制
EntryAbility.ets中

1、增加subWindowStage定义

private subWindowStage: window.WindowStage | undefined = undefined;
复制
2、onCreate增加监听

onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {

    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');

    const that: EntryAbility = this

    this.context.eventHub.on("createWindow", (data: Data) => {

      if (that.subWindowStage != undefined) {

        data.subWindowStage = that.subWindowStage

      } else {

        hilog.info(0x0000, 'testTag', '%{public}s', 'that.subWindowStage == undefined');

      }

    })

  }
复制
3、onWindowStageCreate中增加赋值

this.subWindowStage = windowStage
复制
使用:

public httpRequest(reqMethod: http.RequestMethod, url: string): Promise<Object> {

    // 每一个httpRequest对应一个HTTP请求任务,不可复用

    let httpRequest = http.createHttp();

    let promise = httpRequest.request(url, {

      method: reqMethod,

      readTimeout: 10000,

      connectTimeout: 10000

    });

        new CommonWindow().showWindow();

        //Processes the data and returns.

        return new Promise((resolve, reject) => {

         promise.then((resp) => {

          this.closeSubWindow()

          if (resp.responseCode === http.ResponseCode.OK) {

           //Obtains the returned data.

           const respData:Object = typeof resp.result === 'string' ? JSON.parse(resp.result) : resp.result

           resolve(respData)

          } else {

            httpRequest.destroy();

            reject('error')

          }

      }).catch((err:BusinessError) => {

        this.closeSubWindow()

        httpRequest.destroy();

        reject('error');

      })

    })

  }

  closeSubWindow() {

    let context = getContext(this) as common.UIAbilityContext;

    context.eventHub.emit("closeWindow", null);

  }

更多关于HarmonyOS 鸿蒙Next rcp相关demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


有demo链接吗

HarmonyOS 鸿蒙Next的RCP(Remote Procedure Call,远程过程调用)相关demo主要涉及跨设备或服务间的通信机制。在HarmonyOS中,RCP通过定义接口和服务,允许应用在不同设备间调用对方的功能,从而实现分布式协同工作。

要获取HarmonyOS鸿蒙Next的RCP相关demo,您可以参考以下途径:

  1. 官方示例代码:HarmonyOS官方通常会提供一系列示例代码和教程,展示如何使用RCP机制。您可以在HarmonyOS的开发者官网上查找这些资源,这些示例代码通常包括详细的注释和说明,帮助您快速上手。

  2. 开发者社区:在HarmonyOS的开发者社区中,开发者们会分享自己的经验、代码片段和demo。您可以在这些社区中搜索RCP相关的帖子或项目,找到一些实用的示例代码。

  3. SDK和工具:HarmonyOS的SDK中包含了开发所需的各种工具和库。在SDK中,您可能会找到一些官方的RCP示例代码或模板,这些代码可以作为您开发过程中的参考。

请注意,由于HarmonyOS是一个不断更新的系统,其API和机制也可能会有所变化。因此,在获取和使用demo时,请确保您使用的版本与HarmonyOS的当前版本相匹配。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部