鸿蒙Ability Kit(程序框架服务)【Ability与ServiceExtensionAbility通信】

Ability与ServiceExtensionAbility通信

介绍

本示例展示通过[IDL的方式]和 [@ohos.rpc] 等接口实现了Ability与ServiceExtensionAbility之间的通信。

效果预览

image.png
使用说明

1.启动应用后,首页展示城市的天气信息,当前温度每隔5S会刷新一次。

工程目录

entry/src/main/ets/
|---Application
|---feature
|   |---HomeFeature.ets                  // 任务信息组件
|---MainAbility
|---Mock
|   |---RequestData.ts                   // 远程请求的数据
|   |---WeatherData.ts                   // 天气页面数据
|---model
|   |---FormDate.ts                      // 日期函数方法
|   |---Main.ts                          // 数据类
|---pages
|   |---home
|   |   |---BasicDataSource.ets          // 懒加载封装类
|   |   |---HomeContent.ets              // 内容组件
|   |   |---HoursWeather.ets             // 天气组件(小时)
|   |   |---IndexHeader.ets              // 首页头部组件
|   |   |---MultiDayWeather.ets          // 天气组件(天)
|   |---Home.ets                         // 首页
|---util
|   |---Logger.ts                        // 日志工具
|   |---Style.ts                         // 静态样式变量

具体实现

  • Ability与ServiceExtensionAbility通信的方法主要封装在idl_weather_service_proxy、idl_weather_service_stub、HomeFeature、ServiceExtAbility中。
  • 源码参考:[idl_weather_service_proxy.ts]
/*

 * Copyright (c) 2022 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import rpc from '@ohos.rpc'

import { updateWeatherCallback } from './i_idl_weather_service'

import IIdlWeatherService from './i_idl_weather_service'

import Logger from '../../../util/Logger'



export default class IdlWeatherServiceProxy implements IIdlWeatherService {

  constructor(proxy) {

    this.proxy = proxy

  }



  updateWeather(data: number, callback: updateWeatherCallback): void {

    let _option = new rpc.MessageOption(0)

    let _data = new rpc.MessageParcel()

    let _reply = new rpc.MessageParcel()

    _data.writeInt(data)

    this.proxy.sendRequest(IdlWeatherServiceProxy.COMMAND_UPDATE_WEATHER, _data, _reply, _option).then(function (result) {

      if (result.errCode === 0) {

        let _errCode = result.reply.readInt()

        if (_errCode != 0) {

          let _returnValue = undefined

          callback(_errCode, _returnValue)

          return

        }

        let _returnValue = result.reply.readInt()

        callback(_errCode, _returnValue)

      } else {

        Logger.error("sendRequest failed, errCode: " + result.errCode)

      }

    })

  }



  static readonly COMMAND_UPDATE_WEATHER = 1

  private proxy

}
  • [idl_weather_service_stub.ts]
/*

 * Copyright (c) 2022 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import rpc from '@ohos.rpc'

import { updateWeatherCallback } from './i_idl_weather_service'

import IIdlWeatherService from './i_idl_weather_service'

import Logger from '../../../util/Logger'



export default class IdlWeatherServiceStub extends rpc.RemoteObject implements IIdlWeatherService {

  constructor(des: string) {

    super(des)

  }



  onRemoteRequest(code: number, data, reply, option): boolean {

    Logger.info("onRemoteRequest called, code = " + code)

    switch (code) {

      case IdlWeatherServiceStub.COMMAND_UPDATE_WEATHER: {

        let _data = data.readInt()

        this.updateWeather(_data, (errCode, returnValue) => {

          reply.writeInt(errCode)

          if (errCode == 0) {

            reply.writeInt(returnValue)

          }

        })

        return true

      }

      default: {

        Logger.error("invalid request code" + code)

        break

      }

    }

    return false

  }



  updateWeather(data: number, callback: updateWeatherCallback): void {

  }



  static readonly COMMAND_UPDATE_WEATHER = 1

}
  • [HomeFeature]
/*

 * Copyright (c) 2022 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import Logger from '../util/Logger'

import IdlWeatherServiceProxy from '../MainAbility/data/IIdlWeatherServiceTS/idl_weather_service_proxy'



const BUNDLE_NAME = "com.example.abilityconnectserviceextension"

const SERVICE_EXTENSION_ABILITY_NAME = "ServiceExtAbility"

const ERROR_CODE = -1 // 失败

const SUCCESS_CODE = 0 // 成功



export default class HomeFeature {

  connection = -1 // 初始值

  remoteCallback = null

  context = null

  options = null



  constructor(context) {

    this.context = context

    this.options = {

      outObj: this,

      // 连接成功时回调

      onConnect: function (elementName, proxy) {

        Logger.info(`onConnect success`)

        // 接收来自服务返回的实例

        let weatherProxy = new IdlWeatherServiceProxy(proxy)

        weatherProxy.updateWeather(123, this.outObj.remoteCallback)

      },

      onDisconnect: function () {

        Logger.info(`onDisconnect`)

      },

      onFailed: function () {

        Logger.info(`onFailed`)

      }

    }

  }



  connectServiceExtAbility(callback) {

    Logger.info(`connectServiceExtAbility`)

    this.remoteCallback = callback

    let want = {

      bundleName: BUNDLE_NAME,

      abilityName: SERVICE_EXTENSION_ABILITY_NAME

    }

    this.connection = this.context.connectAbility(want, this.options)

    Logger.info(`connectServiceExtAbility result:${this.connection}`)

  }



  disconnectServiceExtAbility(callback) {

    Logger.info(`disconnectServiceExtAbility`)

    this.context.disconnectAbility(this.connection).then((data) => {

      Logger.info(`disconnectAbility success:${JSON.stringify(data)}`)

      callback(SUCCESS_CODE)

    }).catch((error) => {

      Logger.error(`disconnectAbility failed:${JSON.stringify(error)}`)

      callback(ERROR_CODE)

    })

  }

}
  • [ServiceExtAbility]
/*

 * Copyright (c) 2022 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility'

import IdlWeatherServiceStub from '../MainAbility/data/IIdlWeatherServiceTS/idl_weather_service_stub'

import { updateWeatherCallback } from "../MainAbility/data/IIdlWeatherServiceTS/i_idl_weather_service"

import { getUpdateTemperature } from '../mock/RequestData'

import Logger from '../util/Logger'



class WeatherServiceStub extends IdlWeatherServiceStub {

  constructor(des) {

    super(des)

  }



  updateWeather(data: number, callback: updateWeatherCallback): void {

    let temperature = getUpdateTemperature()

    callback(0, temperature)

    Logger.info(`testIntTransaction: temperature: ${temperature}`)

  }

}



export default class ServiceExtAbility extends ServiceExtension {

  onCreate(want) {

    Logger.info(`onCreate, want: ${want.abilityName}`)

  }



  onRequest(want, startId) {

    Logger.info(`onRequest, want: ${want.abilityName}`)

  }



  onConnect(want) {

    Logger.info(`onConnect , want: ${want.abilityName}`)

    return new WeatherServiceStub("weather service stub")

  }



  onDisconnect(want) {

    Logger.info(`onDisconnect, want: ${want.abilityName}`)

  }



  onDestroy() {

    Logger.info(`onDestroy`)

  }

}
  • 建立服务器连接:通过HomeFeature中的this.context.connectAbility(want, this.options)方法来建立服务器连接;
  • 接收服务端实例并发送请求:连接成功时new IdlWeatherServiceProxy(proxy)来接收服务端实例,通过[@ohos.rpc] 接口来执行new rpc.MessageOption(0)、 new rpc.MessageParcel()、 new rpc.MessageParcel()获取 MessageParcel对象和请求的模式,调用idl_weather_service_proxy中的this.proxy.sendRequest()来发送请求;
  • 接收远程请求处理数据:在idl_weather_service_stub中接收远程请求并通过ServiceExtAbility中的updateWeather()函数来处理数据进行返回;
  • 获取数据:最后将获得的数据渲染到页面中去;
  • 断开连接:可以通过HomeFeature中的this.context.disconnectAbility(this.connection)方法来断开服务器连接,这里的this.connection是建立连接之后的返回值。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/680314.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

短链接突然无法打开和域名有关系?短链接使用必读

在使用短链接的过程中,偶尔会遇到短链接无法正常访问的情形,打开之后,要么呈现该网页已然停止访问的提示,要么就是显示无法访问此网站,这究竟是何种缘由导致的呢?而当遇到这些状况时又该如何去妥善解决呢&a…

IC设计企业致力于解决的HPC数据防泄漏,到底该怎么做?

对于半导体IC设计企业来说,芯片设计、验证、仿真使用HPC环境现在已逐渐成为趋势,主要原因在于原来的工作流程存在较多的缺陷: 性能瓶颈:仿真、设计、验证、生产过程中,前端仿真需要小文件高并发低时延的读写和巨量元数…

2024年人文教育与管理科学国际会议(ICHEMS 2024)

2024年人文教育与管理科学国际会议 2024 International Conference on Humanities Education and Management Science 【1】会议简介 2024年人文教育与管理科学国际会议是一场集合了全球人文教育与管理科学领域精英的学术盛会。本次会议旨在搭建一个国际化的学术交流平台&#…

ElementUi el-tree动态加载节点数据 load方法触发机制

需求背景:需要根据点击后获取的数据动态渲染一个 el-tree,同时渲染出来的 el-tree,需要点击节点时才能获取该节点的层数的获取,如图所示,我需要点击“组”节点才能渲染“设备列表”树,同时“设备列表”树的…

企业数据安全管理容易忽视的关键点:云存储权限管控

云存储已经广泛应用于企业用户、教育领域、医疗领域以及政府和公共服务部门。具体应用场景包括文件共享、数据备份、在线课程、教学资源库、电子病历、医学影像、实验室数据、政务数据的集中管理和共享等。 云存储的优势非常明显: 可扩展性:云存储空间可…

Message forwarding mechanism (消息转发机制)

iOS的消息转发机制 iOS的消息转发机制是在消息发送给对象时,找不到对应的实例方法的情况下启动的。消息转发允许对象在运行时处理无法识别的消息,提供了一种动态的、灵活的消息处理方式。 消息转发机制主要分为三个阶段: 动态方法解析快速…

深度神经网络——什么是 CNN(卷积神经网络)?

Facebook和Instagram自动检测图像中的面孔,Google通过上传照片搜索相似图片的功能,这些都是计算机视觉技术的实例,它们背后的核心技术是卷积神经网络(CNN)。那么,CNN究竟是什么呢?接下来&#x…

通过 .NET COM 互操作设置 System.Drawing.Color

1. 问题背景 在尝试使用 Aspose.Words 库执行 COM 互操作时,遇到了一个关键问题:无法设置颜色。理论上,可以通过向 DocumentBuilder.Font.Color 赋值来设置颜色,但尝试时却出现了 OLE 错误 0x80131509。 以下代码示例演示了这个…

el-tabel名称排序问题

el-tabel排序 最终实现功能如下: 排序限制为: 文件夹>普通文件 数字(0->9)->大写字母(A->Z)->小写字母(a->z)->中文拼音(a->z) 正序…

8086 汇编笔记(七):数据处理的两个基本问题

一、bx、si、di 和 bp 在使用过程中有几处需要注意的地方: (1)在 8086CPU 中,只有这4个寄存器可以用在“[....]”中来进行内存单元的寻址。其他寄存器是不可以的,例如“mov bx, [ax]”就是错误的用法。 &#xff08…

C#中字节数组(byte[])末尾继续添加字节的示例

方法一:使用List 使用List可以很容易地在末尾添加字节,然后如果需要,可以将其转换回byte[]。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Lin…

【机器学习基础】Python编程02:五个实用练习题的解析与总结

Python是一种广泛使用的高级编程语言,它在机器学习领域中的重要性主要体现在以下几个方面: 简洁易学:Python语法简洁清晰,易于学习,使得初学者能够快速上手机器学习项目。 丰富的库支持:Python拥有大量的机器学习库,如scikit-learn、TensorFlow、Keras和PyTorch等,这些…

展厅装修设计对于企业的关重要性

1、定位和主题 定位和主题与企业的品牌形象、产品和服务特点相一致,以展示企业形象和产品特点。 2、空间布局 在空间布局方面,采用分区展示、独立展示、开放式展示等方式,以便客户和观众浏览和参观。同时,合理利用,避免…

Android Lottie 体积优化实践:从 6.4 MB 降到 530 KB

一、说明 产品提出需求:用户有 8 个等级,每个等级对应一个奖牌动画。 按照常用的实现方式: 设计提供 8 个 lottie 动画(8 个 json 文件)。研发将 json 文件打包进入 APK 中。根据不同等级播放指定的动画。 每一个 …

Spring AI 第二讲 之 Chat Model API 第六节Google VertexAI API

VertexAI API 可提供高质量的定制机器学习模型,只需花费最少的机器学习专业知识和精力。 Spring AI 通过以下客户端提供与 VertexAI API 的集成: VertexAI Gemini Chat Vertex AI Gemini API 允许开发人员使用 Gemini 模型构建生成式人工智能应用程序。…

SpringMVC接收数据

SpringMVC接收数据 SpringMVC处理请求流程 SpringMVC涉及组件理解: DispatcherServlet : SpringMVC提供,我们需要使用web.xml配置使其生效,它是整个流程处理的核心,所有请求都经过它的处理和分发![ CEO ]HandlerMappi…

创新实训2024.06.03日志:完善Baseline Test框架、加入对Qwen-14B的测试

1. Baseline Test框架重构与完善 在之前的一篇博客中(创新实训2024.05.29日志:评测数据集与baseline测试-CSDN博客),我介绍了我们对于大模型进行基线测试的一些基本想法和实现,包括一些基线测试的初步结果。 后来的一…

SpringCloud-面试篇(二十三)

(1)SpringCloud常见组件有那些 有无数微服务需要相互调用:可以用远程调用组件OpenFeign组件,也可以用Dobble 这么多微服务相互调用怎么管理:就用到注册中心组件Nacos,Eureka 所有的服务去找注册中心做注…

Ollama本地运行 Codestral-22B-v0.1

Ollama本地运行 Codestral-22B-v0.1 0. 引言1. 运行 codestral:22b-v0.1-q8_02. 简单测试下它的代码能力 0. 引言 Mixtral 5月30日发布了 Codestral-22B-v0.1。 Codestrall-22B-v0.1 在 80 多种编程语言的多样化数据集上进行训练,包括最流行的语言,例如…

vue实现pdf下载——html2canvas

html2canvas 官方文档https://html2canvas.hertzen.com/getting-started html2canvas 的原理是通过遍历DOM树,将每一个HTML元素转化为Canvas对象,并叠加到一起形成一张完整的图片或者PDF文件。 1. 安装插件 npm install html2canvas jspdf --save 2.使用(页面已经…