0
  • 聊天消息
  • 系統(tǒng)消息
  • 評(píng)論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會(huì)員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識(shí)你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

鴻蒙Ability Kit(程序框架服務(wù))【Ability與ServiceExtensionAbility通信】

jf_46214456 ? 來(lái)源:jf_46214456 ? 作者:jf_46214456 ? 2024-06-05 09:28 ? 次閱讀

Ability與ServiceExtensionAbility通信

介紹

本示例展示通過(guò)[IDL的方式]和 [@ohos.rpc] 等接口實(shí)現(xiàn)了Ability與ServiceExtensionAbility之間的通信。

效果預(yù)覽

image.png
使用說(shuō)明

1.啟動(dòng)應(yīng)用后,首頁(yè)展示城市的天氣信息,當(dāng)前溫度每隔5S會(huì)刷新一次。

工程目錄

entry/src/main/ets/
|---Application
|---feature
|   |---HomeFeature.ets                  // 任務(wù)信息組件
|---MainAbility
|---Mock
|   |---RequestData.ts                   // 遠(yuǎn)程請(qǐng)求的數(shù)據(jù)
|   |---WeatherData.ts                   // 天氣頁(yè)面數(shù)據(jù)
|---model
|   |---FormDate.ts                      // 日期函數(shù)方法
|   |---Main.ts                          // 數(shù)據(jù)類
|---pages
|   |---home
|   |   |---BasicDataSource.ets          // 懶加載封裝類
|   |   |---HomeContent.ets              // 內(nèi)容組件
|   |   |---HoursWeather.ets             // 天氣組件(小時(shí))
|   |   |---IndexHeader.ets              // 首頁(yè)頭部組件
|   |   |---MultiDayWeather.ets          // 天氣組件(天)
|   |---Home.ets                         // 首頁(yè)
|---util
|   |---Logger.ts                        // 日志工具
|   |---Style.ts                         // 靜態(tài)樣式變量

具體實(shí)現(xiàn)

  • 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,

      // 連接成功時(shí)回調(diào)

      onConnect: function (elementName, proxy) {

        Logger.info(`onConnect success`)

        // 接收來(lái)自服務(wù)返回的實(shí)例

        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`)

  }

}
  • 建立服務(wù)器連接:通過(guò)HomeFeature中的this.context.connectAbility(want, this.options)方法來(lái)建立服務(wù)器連接;
  • 接收服務(wù)端實(shí)例并發(fā)送請(qǐng)求:連接成功時(shí)new IdlWeatherServiceProxy(proxy)來(lái)接收服務(wù)端實(shí)例,通過(guò)[@ohos.rpc] 接口來(lái)執(zhí)行new rpc.MessageOption(0)、 new rpc.MessageParcel()、 new rpc.MessageParcel()獲取 MessageParcel對(duì)象和請(qǐng)求的模式,調(diào)用idl_weather_service_proxy中的this.proxy.sendRequest()來(lái)發(fā)送請(qǐng)求;
  • 接收遠(yuǎn)程請(qǐng)求處理數(shù)據(jù):在idl_weather_service_stub中接收遠(yuǎn)程請(qǐng)求并通過(guò)ServiceExtAbility中的updateWeather()函數(shù)來(lái)處理數(shù)據(jù)進(jìn)行返回;
  • 獲取數(shù)據(jù):最后將獲得的數(shù)據(jù)渲染到頁(yè)面中去;
  • 斷開連接:可以通過(guò)HomeFeature中的this.context.disconnectAbility(this.connection)方法來(lái)斷開服務(wù)器連接,這里的this.connection是建立連接之后的返回值。

審核編輯 黃宇

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場(chǎng)。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問(wèn)題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • 框架
    +關(guān)注

    關(guān)注

    0

    文章

    404

    瀏覽量

    17755
  • 鴻蒙
    +關(guān)注

    關(guān)注

    57

    文章

    2474

    瀏覽量

    43689
收藏 人收藏

    評(píng)論

    相關(guān)推薦
    熱點(diǎn)推薦

    鴻蒙開發(fā)接口Ability框架:【@ohos.application.Ability (Ability)】

    Ability模塊提供對(duì)Ability生命周期、上下文環(huán)境等調(diào)用管理的能力,包括Ability創(chuàng)建、銷毀、轉(zhuǎn)儲(chǔ)客戶端信息等。
    的頭像 發(fā)表于 04-30 17:42 ?2586次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<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>)】

    鴻蒙開發(fā)接口Ability框架:【@ohos.ability.featureAbility (FeatureAbility模塊)】

    FeatureAbility模塊提供帶有UI設(shè)計(jì)與用戶交互的能力,包括啟動(dòng)新的ability、獲取dataAbilityHelper、設(shè)置此Page Ability、獲取當(dāng)前Ability對(duì)應(yīng)的窗口,連接
    的頭像 發(fā)表于 05-06 16:31 ?1231次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【@ohos.<b class='flag-5'>ability</b>.featureAbility (FeatureAbility模塊)】

    鴻蒙開發(fā)接口Ability框架:【@ohos.ability.particleAbility (particleAbility模塊)】

    particleAbility模塊提供了Service類型Ability的能力,包括啟動(dòng)、停止指定的particleAbility,獲取dataAbilityHelper,連接、斷開當(dāng)前Ability與指定ServiceAbility等。
    的頭像 發(fā)表于 05-09 10:21 ?898次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【@ohos.<b class='flag-5'>ability</b>.particleAbility (particleAbility模塊)】

    鴻蒙開發(fā)接口Ability框架:【 (ServiceExtensionAbility)】

    ServiceExtensionAbility模塊提供ServiceExtension服務(wù)擴(kuò)展相關(guān)接口的能力。
    的頭像 發(fā)表于 05-09 09:59 ?1053次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【 (<b class='flag-5'>ServiceExtensionAbility</b>)】

    鴻蒙開發(fā)接口Ability框架:【 (Context模塊)】

    Context模塊提供了ability或application的上下文的能力,包括允許訪問(wèn)特定于應(yīng)用程序的資源、請(qǐng)求和驗(yàn)證權(quán)限等。
    的頭像 發(fā)表于 05-13 16:04 ?1003次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【 (Context模塊)】

    鴻蒙開發(fā)接口Ability框架:【(AbilityContext)】

    AbilityContext是Ability的上下文環(huán)境,繼承自Context。
    的頭像 發(fā)表于 05-13 09:26 ?1260次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【(AbilityContext)】

    鴻蒙開發(fā)接口Ability框架:【(AbilityDelegator)】

    AbilityDelegator提供添加用于監(jiān)視指定能力的生命周期狀態(tài)更改的AbilityMonitor對(duì)象的能力,包括對(duì)AbilityMonitor實(shí)例的添加、刪除、等待ability到達(dá)
    的頭像 發(fā)表于 05-13 17:58 ?1148次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【(AbilityDelegator)】

    鴻蒙開發(fā)接口Ability框架:【AbilityDelegator】

    AbilityDelegator提供添加用于監(jiān)視指定能力的生命周期狀態(tài)更改的AbilityMonitor對(duì)象的能力,包括對(duì)AbilityMonitor實(shí)例的添加、刪除、等待ability到達(dá)
    的頭像 發(fā)表于 05-16 16:48 ?1133次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【AbilityDelegator】

    鴻蒙Ability Kit程序框架服務(wù))【ServiceExtensionAbility

    [ServiceExtensionAbility]是SERVICE類型的ExtensionAbility組件,提供后臺(tái)服務(wù)能力,其內(nèi)部持有了一個(gè)[ServiceExtensionContext],通過(guò)[ServiceExtensionContext]提供了豐富的接口供外部
    的頭像 發(fā)表于 06-04 14:50 ?1488次閱讀
    <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'>服務(wù)</b>)【<b class='flag-5'>ServiceExtensionAbility</b>】

    鴻蒙Ability開發(fā)-Stage模型下Ability的創(chuàng)建和使用

    ) ?? \'\'); }); } ... }; UIAbilityContext模塊啟動(dòng)Ability的能力 UIAbilityContext模塊提供允許訪問(wèn)特定Ability的資源的能力,包括對(duì)Ability的啟動(dòng)、停止
    發(fā)表于 01-08 15:34

    跟阿斌一起學(xué)鴻蒙(2): Ability vs App?

    ,程序員們依然可以為你實(shí)現(xiàn),只是實(shí)現(xiàn)起來(lái)會(huì)相對(duì)麻煩,比如各種遠(yuǎn)程通信,各種數(shù)據(jù)和狀態(tài)的同步,還有各種聯(lián)調(diào)和測(cè)試。而鴻蒙OS,將很多麻煩的處理過(guò)程整合到操作系統(tǒng)中,借此希望讓程序員們可以
    發(fā)表于 11-30 20:56

    鴻蒙開發(fā)接口Ability框架:【AbilityRunningInfo】

    AbilityRunningInfo模塊提供對(duì)Ability運(yùn)行的相關(guān)信息和狀態(tài)進(jìn)行設(shè)置和查詢的能力。
    的頭像 發(fā)表于 05-17 17:12 ?449次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【AbilityRunningInfo】

    鴻蒙應(yīng)用模型:【Ability Kit】簡(jiǎn)介

    Ability Kit程序框架服務(wù))提供了應(yīng)用程序開發(fā)和運(yùn)行的應(yīng)用模型,是系統(tǒng)為開發(fā)者提供的應(yīng)
    的頭像 發(fā)表于 05-29 14:41 ?976次閱讀
    <b class='flag-5'>鴻蒙</b>應(yīng)用模型:【<b class='flag-5'>Ability</b> <b class='flag-5'>Kit</b>】簡(jiǎn)介

    鴻蒙Ability Kit程序框架服務(wù))【Ability內(nèi)頁(yè)面間的跳轉(zhuǎn)】

    基于Stage模型下的Ability開發(fā),實(shí)現(xiàn)Ability內(nèi)頁(yè)面間的跳轉(zhuǎn)和數(shù)據(jù)傳遞。
    的頭像 發(fā)表于 06-03 20:43 ?493次閱讀
    <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'>服務(wù)</b>)【<b class='flag-5'>Ability</b>內(nèi)頁(yè)面間的跳轉(zhuǎn)】

    鴻蒙開發(fā)Ability Kit程序框架服務(wù):FA模型綁定Stage模型ServiceExtensionAbility

    本文介紹FA模型的三種應(yīng)用組件如何綁定Stage模型的ServiceExtensionAbility組件。
    的頭像 發(fā)表于 06-25 10:43 ?462次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)<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'>服務(wù)</b>:FA模型綁定Stage模型<b class='flag-5'>ServiceExtensionAbility</b>

    電子發(fā)燒友

    中國(guó)電子工程師最喜歡的網(wǎng)站

    • 2931785位工程師會(huì)員交流學(xué)習(xí)
    • 獲取您個(gè)性化的科技前沿技術(shù)信息
    • 參加活動(dòng)獲取豐厚的禮品