1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import Logger from '../util/Logger' 17import IdlWeatherServiceProxy from '../MainAbility/data/IIdlWeatherServiceTS/idl_weather_service_proxy' 18 19const BUNDLE_NAME = "com.example.abilityconnectserviceextension" 20const SERVICE_EXTENSION_ABILITY_NAME = "ServiceExtAbility" 21const ERROR_CODE = -1 // 失败 22const SUCCESS_CODE = 0 // 成功 23 24export default class HomeFeature { 25 connection = -1 // 初始值 26 remoteCallback = null 27 context = null 28 options = null 29 30 constructor(context) { 31 this.context = context 32 this.options = { 33 outObj: this, 34 // 连接成功时回调 35 onConnect: function (elementName, proxy) { 36 Logger.info(`onConnect success`) 37 // 接收来自服务返回的实例 38 let weatherProxy = new IdlWeatherServiceProxy(proxy) 39 weatherProxy.updateWeather(123, this.outObj.remoteCallback) 40 }, 41 onDisconnect: function () { 42 Logger.info(`onDisconnect`) 43 }, 44 onFailed: function () { 45 Logger.info(`onFailed`) 46 } 47 } 48 } 49 50 connectServiceExtAbility(callback) { 51 Logger.info(`connectServiceExtAbility`) 52 this.remoteCallback = callback 53 let want = { 54 bundleName: BUNDLE_NAME, 55 abilityName: SERVICE_EXTENSION_ABILITY_NAME 56 } 57 try { 58 this.connection = this.context.connectServiceExtensionAbility(want, this.options) 59 } catch (err) { 60 Logger.error(`connectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`) 61 } 62 Logger.info(`connectServiceExtAbility result:${this.connection}`) 63 } 64 65 disconnectServiceExtAbility(callback) { 66 Logger.info(`disconnectServiceExtAbility`) 67 this.context.disconnectAbility(this.connection).then((data) => { 68 Logger.info(`disconnectAbility success:${JSON.stringify(data)}`) 69 callback(SUCCESS_CODE) 70 }).catch((error) => { 71 Logger.error(`disconnectAbility failed:${JSON.stringify(error)}`) 72 callback(ERROR_CODE) 73 }) 74 } 75}