吴忠躺衫网络科技有限公司

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

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

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

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

jf_46214456 ? 來源:jf_46214456 ? 作者:jf_46214456 ? 2024-06-05 09:28 ? 次閱讀

Ability與ServiceExtensionAbility通信

介紹

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

效果預覽

image.png
使用說明

1.啟動應用后,首頁展示城市的天氣信息,當前溫度每隔5S會刷新一次。

工程目錄

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

具體實現(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,

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

      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)方法來建立服務器連接;
  • 接收服務端實例并發(fā)送請求:連接成功時new IdlWeatherServiceProxy(proxy)來接收服務端實例,通過[@ohos.rpc] 接口來執(zhí)行new rpc.MessageOption(0)、 new rpc.MessageParcel()、 new rpc.MessageParcel()獲取 MessageParcel對象和請求的模式,調(diào)用idl_weather_service_proxy中的this.proxy.sendRequest()來發(fā)送請求;
  • 接收遠程請求處理數(shù)據(jù):在idl_weather_service_stub中接收遠程請求并通過ServiceExtAbility中的updateWeather()函數(shù)來處理數(shù)據(jù)進行返回;
  • 獲取數(shù)據(jù):最后將獲得的數(shù)據(jù)渲染到頁面中去;
  • 斷開連接:可以通過HomeFeature中的this.context.disconnectAbility(this.connection)方法來斷開服務器連接,這里的this.connection是建立連接之后的返回值。

審核編輯 黃宇

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

    關注

    0

    文章

    403

    瀏覽量

    17542
  • 鴻蒙
    +關注

    關注

    57

    文章

    2392

    瀏覽量

    43050
收藏 人收藏

    評論

    相關推薦

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

    Ability模塊提供對Ability生命周期、上下文環(huán)境等調(diào)用管理的能力,包括Ability創(chuàng)建、銷毀、轉儲客戶端信息等。
    的頭像 發(fā)表于 04-30 17:42 ?2340次閱讀
    <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設計與用戶交互的能力,包括啟動新的ability、獲取dataAbilityHelper、設置此Page Ability、獲取當前Ability對應的窗口,連接
    的頭像 發(fā)表于 05-06 16:31 ?1066次閱讀
    <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的能力,包括啟動、停止指定的particleAbility,獲取dataAbilityHelper,連接、斷開當前Ability與指定ServiceAbility等。
    的頭像 發(fā)表于 05-09 10:21 ?762次閱讀
    <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服務擴展相關接口的能力。
    的頭像 發(fā)表于 05-09 09:59 ?890次閱讀
    <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的上下文的能力,包括允許訪問特定于應用程序的資源、請求和驗證權限等。
    的頭像 發(fā)表于 05-13 16:04 ?767次閱讀
    <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 ?1071次閱讀
    <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對象的能力,包括對AbilityMonitor實例的添加、刪除、等待ability到達
    的頭像 發(fā)表于 05-13 17:58 ?1000次閱讀
    <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對象的能力,包括對AbilityMonitor實例的添加、刪除、等待ability到達
    的頭像 發(fā)表于 05-16 16:48 ?981次閱讀
    <b class='flag-5'>鴻蒙</b>開發(fā)接口<b class='flag-5'>Ability</b><b class='flag-5'>框架</b>:【AbilityDelegator】

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

    [ServiceExtensionAbility]是SERVICE類型的ExtensionAbility組件,提供后臺服務能力,其內(nèi)部持有了一個[ServiceExtensionContext],通過[ServiceExtensionContext]提供了豐富的接口供外部
    的頭像 發(fā)表于 06-04 14:50 ?1280次閱讀
    <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開發(fā)-Stage模型下Ability的創(chuàng)建和使用

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

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

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

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

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

    鴻蒙應用模型:【Ability Kit】簡介

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

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

    基于Stage模型下的Ability開發(fā),實現(xiàn)Ability內(nèi)頁面間的跳轉和數(shù)據(jù)傳遞。
    的頭像 發(fā)表于 06-03 20:43 ?338次閱讀
    <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>內(nèi)頁面間的跳轉】

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

    本文介紹FA模型的三種應用組件如何綁定Stage模型的ServiceExtensionAbility組件。
    的頭像 發(fā)表于 06-25 10:43 ?346次閱讀
    <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'>服務</b>:FA模型綁定Stage模型<b class='flag-5'>ServiceExtensionAbility</b>
    大发888出纳| 百家乐官网用品| 百家乐官网有没有单机版的 | 德州扑克与梭哈| 宜城市| 百家乐官网推广| 神人百家乐官网赌场| 百家乐官网的规则博彩正网| 红9百家乐官网的玩法技巧和规则 高尔夫百家乐官网的玩法技巧和规则 | 网上现金棋牌游戏| 温州市| 广州百家乐官网扫描分析| 澳门百家乐官网手机软件| 可以玩百家乐的博彩公司| 百家乐筹码防伪| 新全讯| 百家乐官网赌场技巧大全| 游戏厅百家乐软件| 全讯网高手论坛| 盱眙县| 联众博彩| 百家乐官网时时彩网站| 属虎和属猴牛人做生意| 网上的百家乐怎么才能赢| 博彩网导航| 百家乐官网打法介绍| 现金百家乐赌法| bet365最快最稳定| 百家乐官网注册彩金| 百家乐开户就送现金| 大发888官方 df888gfxzylc8 | 万安县| 百家乐官网老千| 大发888开户博盈国际| r百家乐官网娱乐下载| 百家乐官网园好又多| 大发888最新版本下载| 百家乐官网投注方法| 玩百家乐保时捷娱乐城| 线上龙虎| 美女百家乐官网的玩法技巧和规则|