Ability與ServiceExtensionAbility通信
介紹
本示例展示通過[IDL的方式]和 [@ohos.rpc] 等接口實現了Ability與ServiceExtensionAbility之間的通信。
效果預覽
使用說明
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]
/*`HarmonyOS與OpenHarmony鴻蒙文檔籽料: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文章
403瀏覽量
17489 -
鴻蒙
+關注
關注
57文章
2352瀏覽量
42859
發布評論請先 登錄
相關推薦
鴻蒙開發接口Ability框架:【@ohos.application.Ability (Ability)】
Ability模塊提供對Ability生命周期、上下文環境等調用管理的能力,包括Ability創建、銷毀、轉儲客戶端信息等。
鴻蒙開發接口Ability框架:【@ohos.ability.featureAbility (FeatureAbility模塊)】
FeatureAbility模塊提供帶有UI設計與用戶交互的能力,包括啟動新的ability、獲取dataAbilityHelper、設置此Page Ability、獲取當前Ability對應的窗口,連接
鴻蒙開發接口Ability框架:【@ohos.ability.particleAbility (particleAbility模塊)】
particleAbility模塊提供了Service類型Ability的能力,包括啟動、停止指定的particleAbility,獲取dataAbilityHelper,連接、斷開當前Ability與指定ServiceAbility等。
鴻蒙開發接口Ability框架:【 (ServiceExtensionAbility)】
ServiceExtensionAbility模塊提供ServiceExtension服務擴展相關接口的能力。
鴻蒙開發接口Ability框架:【(AbilityDelegator)】
AbilityDelegator提供添加用于監視指定能力的生命周期狀態更改的AbilityMonitor對象的能力,包括對AbilityMonitor實例的添加、刪除、等待ability到達
鴻蒙開發接口Ability框架:【AbilityDelegator】
AbilityDelegator提供添加用于監視指定能力的生命周期狀態更改的AbilityMonitor對象的能力,包括對AbilityMonitor實例的添加、刪除、等待ability到達
鴻蒙Ability Kit(程序框架服務)【ServiceExtensionAbility】
[ServiceExtensionAbility]是SERVICE類型的ExtensionAbility組件,提供后臺服務能力,其內部持有了一個[ServiceExtensionContext],通過[ServiceExtensionContext]提供了豐富的接口供外部
鴻蒙Ability開發-Stage模型下Ability的創建和使用
) ?? \'\');
});
}
...
};
UIAbilityContext模塊啟動Ability的能力
UIAbilityContext模塊提供允許訪問特定Ability的資源的能力,包括對Ability的啟動、停止
發表于 01-08 15:34
跟阿斌一起學鴻蒙(2): Ability vs App?
,程序員們依然可以為你實現,只是實現起來會相對麻煩,比如各種遠程通信,各種數據和狀態的同步,還有各種聯調和測試。而鴻蒙OS,將很多麻煩的處理過程整合到操作系統中,借此希望讓程序員們可以
發表于 11-30 20:56
鴻蒙開發Ability Kit程序框架服務:FA模型綁定Stage模型ServiceExtensionAbility
本文介紹FA模型的三種應用組件如何綁定Stage模型的ServiceExtensionAbility組件。
評論