Ability與ServiceExtensionAbility通信
介紹
本示例展示通過(guò)[IDL的方式]和 [@ohos.rpc] 等接口實(shí)現(xiàn)了Ability與ServiceExtensionAbility之間的通信。
效果預(yù)覽
使用說(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]
/*`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`)
}
}
- 建立服務(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是建立連接之后的返回值。
審核編輯 黃宇
-
框架
+關(guān)注
關(guān)注
0文章
404瀏覽量
17755 -
鴻蒙
+關(guān)注
關(guān)注
57文章
2474瀏覽量
43689
發(fā)布評(píng)論請(qǐng)先 登錄
鴻蒙開發(fā)接口Ability框架:【@ohos.application.Ability (Ability)】

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

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

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

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

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

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

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

鴻蒙Ability開發(fā)-Stage模型下Ability的創(chuàng)建和使用
跟阿斌一起學(xué)鴻蒙(2): Ability vs App?
鴻蒙開發(fā)接口Ability框架:【AbilityRunningInfo】

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

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

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

評(píng)論