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