• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022-2023 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 prompt from '@ohos.prompt'
17import common from '@ohos.app.ability.common'
18import rpc from "@ohos.rpc"
19import Logger from '../model/Logger'
20
21const localDeviceId: string = ''
22let mRemote: rpc.IRemoteObject = null
23let connection: number = -1
24const TAG = 'ServiceModel'
25
26export class ServiceModel {
27  private sendMessage: string = ''
28
29  onConnectCallback(element, remote) {
30    Logger.info(`${TAG}onConnectLocalService onConnectDone element:${element}`)
31    Logger.info(`${TAG}onConnectLocalService onConnectDone remote:${remote}`)
32    mRemote = remote
33    if (mRemote === null) {
34      prompt.showToast({
35        message: 'onConnectLocalService not connected yet'
36      })
37      return
38    }
39    prompt.showToast({
40      message: 'connect service success',
41    })
42  }
43
44  onDisconnectCallback(element) {
45    Logger.info(`${TAG}onConnectLocalService onDisconnectDone element:${element}`)
46  }
47
48  onFailedCallback(code) {
49    Logger.info(`${TAG}onConnectLocalService onFailed errCode:${code}`)
50    prompt.showToast({
51      message: `onConnectLocalService onFailed:${code}`
52    })
53  }
54
55  connectService() {
56    Logger.info(`${TAG} onCconnectService begin`)
57    let context = getContext(this) as common.UIAbilityContext
58    connection = context.connectServiceExtensionAbility(
59      {
60        deviceId: localDeviceId,
61        bundleName: 'ohos.samples.flybird',
62        abilityName: 'ServiceExtAbility',
63      },
64      {
65        onConnect: this.onConnectCallback,
66        onDisconnect: this.onDisconnectCallback,
67        onFailed: this.onFailedCallback,
68      },
69    )
70  }
71
72  disconnectService() {
73    Logger.info(`${TAG} onDisconnectService begin`)
74    mRemote = null
75    if (connection === -1) {
76      prompt.showToast({
77        message: 'onDisconnectService not connected yet'
78      })
79      return
80    }
81    let context = getContext(this) as common.UIAbilityContext
82    context.disconnectServiceExtensionAbility(connection)
83    connection = -1 // 连接状态值设置为-1
84    prompt.showToast({
85      message: 'onDisconnectService disconnect done'
86    })
87  }
88
89  getRemoteObject() {
90    return mRemote
91  }
92}