1/* 2 * Copyright (c) 2023-2024 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 backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; 17import wantAgent from '@ohos.app.ability.wantAgent'; 18import common from '@ohos.app.ability.common' 19import { BusinessError } from '@ohos.base'; 20import Logger from '../util/Logger' 21 22const TAG: string = 'ContinuousTaskModel' 23 24export default class ContinuousTaskModel { 25 private context: common.UIAbilityContext 26 private list: Array<string> = ["audioPlayback"]; 27 28 constructor(context: common.UIAbilityContext) { 29 this.context = context 30 } 31 32 // start continuous task 33 startContinuousTask(): void { 34 let wantAgentInfo: wantAgent.WantAgentInfo = { 35 wants: [ 36 { 37 bundleName: 'ohos.samples.continuoustask', 38 abilityName: 'ohos.samples.continuoustask.MainAbility', 39 } 40 ], 41 actionType: wantAgent.OperationType.START_ABILITY, 42 requestCode: 0, 43 actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 44 } 45 46 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { 47 backgroundTaskManager.startBackgroundRunning(this.context, this.list, wantAgentObj).then(() => { 48 Logger.info(TAG, 'startBackgroundRunning succeeded'); 49 this.list = ["audioPlayback","audioRecording"] 50 setTimeout(()=>{ 51 backgroundTaskManager.updateBackgroundRunning(this.context, this.list).then(() => { 52 Logger.info(TAG, 'Operation updateBackgroundRunning succeeded'); 53 }).catch((error: BusinessError) => { 54 Logger.info(TAG, `Operation updateBackgroundRunning failed. code is ${error.code} message 55 is ${error.message}`); 56 }); 57 },5000) 58 }).catch((error: BusinessError) => { 59 Logger.error(TAG, `Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); 60 }); 61 }); 62 } 63 64 // cancel continuous task 65 stopContinuousTask(): void { 66 try { 67 backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { 68 Logger.info(TAG, `stopBackgroundRunning succeeded`); 69 }).catch((err: BusinessError) => { 70 Logger.info(TAG, `stopBackgroundRunning failed Cause: ${JSON.stringify(err)}`); 71 }) 72 } catch (error) { 73 Logger.error(TAG, `stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); 74 } 75 } 76} 77