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 rpc from "@ohos.rpc" 17import wantAgent from '@ohos.wantAgent' 18import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility' 19import Logger from '../model/Logger' 20 21const TAG: string = 'ServiceAbility' 22 23class FirstServiceAbilityStub extends rpc.RemoteObject { 24 constructor(des: string) { 25 if (typeof des === 'string') { 26 super(des) 27 } else { 28 return 29 } 30 } 31 32 onRemoteRequest(code: number, data: rpc.MessageParcel, reply: rpc.MessageParcel, option: rpc.MessageOption) { 33 Logger.info(`${TAG}onRemoteRequest called`) 34 if (code === 1) { 35 let dataStr = data.readString() 36 Logger.info(`${TAG} string=${dataStr}`) 37 if (dataStr === 'start_game') { 38 this.startContinousTask(); 39 let result = 'ok start game' 40 Logger.info(`${TAG} result=${result}`) 41 reply.writeString(result) 42 } else if (dataStr === 'disconnect_service') { 43 let result = 'ok disconnect service' 44 Logger.info(`${TAG} result=${result}`) 45 reply.writeString(result) 46 } 47 else { 48 Logger.info(`${TAG} error string}`) 49 } 50 } else { 51 Logger.info(`${TAG} unknown request code`) 52 } 53 return true 54 } 55 56 startContinousTask() { 57 Logger.info(TAG, 'start background continousTask api') 58 let wantAgentInfo = { 59 wants: [ 60 { 61 bundleName: 'ohos.samples.flybird', 62 abilityName: 'EntryAbility' 63 } 64 ], 65 operationType: wantAgent.OperationType.START_ABILITY, 66 requestCode: 0, 67 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 68 }; 69 70 } 71 72 callback(err, data) { 73 if (err) { 74 Logger.error(TAG, `Operation failed Cause: ${err}`) 75 } else { 76 Logger.info(TAG, "Operation succeeded") 77 } 78 } 79} 80 81export default class ServiceExtAbility extends ServiceExtension { 82 onCreate(want) { 83 Logger.info(`${TAG} onCreate, want: ${want.abilityName}`) 84 } 85 86 onRequest(want, startId) { 87 Logger.info(`${TAG} onRequest, want: ${want.abilityName}`) 88 } 89 90 onConnect(want) { 91 Logger.info(`${TAG} onConnect, want: ${want.abilityName}`) 92 return new FirstServiceAbilityStub("first ts service stub") 93 } 94 95 onDisconnect(want) { 96 Logger.info(`${TAG} onDisconnect, want: ${want.abilityName}`) 97 } 98 99 onDestroy() { 100 Logger.info(`${TAG} onDestroy`) 101 } 102}