0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

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

jf_46214456 来源:jf_46214456 作者:jf_46214456 2024-06-05 09:28 次阅读

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]
    鸿蒙文档.png
/*`HarmonyOSOpenHarmony鸿蒙文档籽料:mau123789是v直接拿`

 * 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是建立连接之后的返回值。

审核编辑 黄宇

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 框架
    +关注

    关注

    0

    文章

    398

    浏览量

    17432
  • 鸿蒙
    +关注

    关注

    57

    文章

    2307

    浏览量

    42737
收藏 人收藏

    评论

    相关推荐

    鸿蒙开发接口Ability框架:【@ohos.application.Ability (Ability)】

    Ability模块提供对Ability生命周期、上下文环境等调用管理的能力,包括Ability创建、销毁、转储客户端信息等。
    的头像 发表于 04-30 17:42 2206次阅读
    <b class='flag-5'>鸿蒙</b>开发接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【@ohos.application.<b class='flag-5'>Ability</b> (<b class='flag-5'>Ability</b>)】

    鸿蒙开发接口Ability框架:【@ohos.ability.featureAbility (FeatureAbility模块)】

    FeatureAbility模块提供带有UI设计与用户交互的能力,包括启动新的ability、获取dataAbilityHelper、设置此Page Ability、获取当前Ability对应的窗口,连接
    的头像 发表于 05-06 16:31 925次阅读
    <b class='flag-5'>鸿蒙</b>开发接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【@ohos.<b class='flag-5'>ability</b>.featureAbility (FeatureAbility模块)】

    鸿蒙开发接口Ability框架:【@ohos.ability.particleAbility (particleAbility模块)】

    particleAbility模块提供了Service类型Ability的能力,包括启动、停止指定的particleAbility,获取dataAbilityHelper,连接、断开当前Ability与指定ServiceAbility等。
    的头像 发表于 05-09 10:21 685次阅读
    <b class='flag-5'>鸿蒙</b>开发接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【@ohos.<b class='flag-5'>ability</b>.particleAbility (particleAbility模块)】

    鸿蒙开发接口Ability框架:【 (ServiceExtensionAbility)】

    ServiceExtensionAbility模块提供ServiceExtension服务扩展相关接口的能力。
    的头像 发表于 05-09 09:59 766次阅读
    <b class='flag-5'>鸿蒙</b>开发接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【 (<b class='flag-5'>ServiceExtensionAbility</b>)】

    鸿蒙开发接口Ability框架:【 (Context模块)】

    Context模块提供了ability或application的上下文的能力,包括允许访问特定于应用程序的资源、请求和验证权限等。
    的头像 发表于 05-13 16:04 669次阅读
    <b class='flag-5'>鸿蒙</b>开发接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【 (Context模块)】

    鸿蒙开发接口Ability框架:【(AbilityContext)】

    AbilityContext是Ability的上下文环境,继承自Context。
    的头像 发表于 05-13 09:26 958次阅读
    <b class='flag-5'>鸿蒙</b>开发接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【(AbilityContext)】

    鸿蒙开发接口Ability框架:【(AbilityDelegator)】

    AbilityDelegator提供添加用于监视指定能力的生命周期状态更改的AbilityMonitor对象的能力,包括对AbilityMonitor实例的添加、删除、等待ability到达
    的头像 发表于 05-13 17:58 916次阅读
    <b class='flag-5'>鸿蒙</b>开发接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【(AbilityDelegator)】

    鸿蒙开发接口Ability框架:【AbilityDelegator】

    AbilityDelegator提供添加用于监视指定能力的生命周期状态更改的AbilityMonitor对象的能力,包括对AbilityMonitor实例的添加、删除、等待ability到达
    的头像 发表于 05-16 16:48 900次阅读
    <b class='flag-5'>鸿蒙</b>开发接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【AbilityDelegator】

    鸿蒙Ability Kit程序框架服务)【ServiceExtensionAbility

    [ServiceExtensionAbility]是SERVICE类型的ExtensionAbility组件,提供后台服务能力,其内部持有了一个[ServiceExtensionContext],通过[ServiceExtensionContext]提供了丰富的接口供外部
    的头像 发表于 06-04 14:50 1132次阅读
    <b class='flag-5'>鸿蒙</b><b class='flag-5'>Ability</b> <b class='flag-5'>Kit</b>(<b class='flag-5'>程序</b><b class='flag-5'>框架</b><b class='flag-5'>服务</b>)【<b class='flag-5'>ServiceExtensionAbility</b>】

    鸿蒙Ability开发-Stage模型下Ability的创建和使用

    ) ?? \'\'); }); } ... }; UIAbilityContext模块启动Ability的能力 UIAbilityContext模块提供允许访问特定Ability的资源的能力,包括对Ability的启动、停止
    发表于 01-08 15:34

    跟阿斌一起学鸿蒙(2): Ability vs App?

    程序员们依然可以为你实现,只是实现起来会相对麻烦,比如各种远程通信,各种数据和状态的同步,还有各种联调和测试。而鸿蒙OS,将很多麻烦的处理过程整合到操作系统中,借此希望让程序员们可以
    发表于 11-30 20:56

    鸿蒙开发接口Ability框架:【AbilityRunningInfo】

    AbilityRunningInfo模块提供对Ability运行的相关信息和状态进行设置和查询的能力。
    的头像 发表于 05-17 17:12 292次阅读
    <b class='flag-5'>鸿蒙</b>开发接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【AbilityRunningInfo】

    鸿蒙应用模型:【Ability Kit】简介

    Ability Kit程序框架服务)提供了应用程序开发和运行的应用模型,是系统为开发者提供的应
    的头像 发表于 05-29 14:41 589次阅读
    <b class='flag-5'>鸿蒙</b>应用模型:【<b class='flag-5'>Ability</b> <b class='flag-5'>Kit</b>】简介

    鸿蒙Ability Kit程序框架服务)【Ability内页面间的跳转】

    基于Stage模型下的Ability开发,实现Ability内页面间的跳转和数据传递。
    的头像 发表于 06-03 20:43 273次阅读
    <b class='flag-5'>鸿蒙</b><b class='flag-5'>Ability</b> <b class='flag-5'>Kit</b>(<b class='flag-5'>程序</b><b class='flag-5'>框架</b><b class='flag-5'>服务</b>)【<b class='flag-5'>Ability</b>内页面间的跳转】

    鸿蒙开发Ability Kit程序框架服务:FA模型绑定Stage模型ServiceExtensionAbility

    本文介绍FA模型的三种应用组件如何绑定Stage模型的ServiceExtensionAbility组件。
    的头像 发表于 06-25 10:43 257次阅读
    <b class='flag-5'>鸿蒙</b>开发<b class='flag-5'>Ability</b> <b class='flag-5'>Kit</b><b class='flag-5'>程序</b><b class='flag-5'>框架</b><b class='flag-5'>服务</b>:FA模型绑定Stage模型<b class='flag-5'>ServiceExtensionAbility</b>