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 wantAgent from '@ohos.wantAgent' 17import backgroundTaskManager from '@ohos.backgroundTaskManager' 18import featureAbility from '@ohos.ability.featureAbility' 19import Notification from '@ohos.notification' 20import Logger from '../MainAbility/mode/Logger' 21 22const TAG = "serviceAbility" 23let num: number = 0 24let timerID: number = 0 25 26let notificationRequest = { 27 content: { 28 contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, 29 normal: { 30 title: '文件名', 31 text: '' 32 } 33 }, 34 id: 1 35} 36 37function callback(err, data) { 38 if (err) { 39 Logger.error(TAG, `Operation failed Cause: ${err}`) 40 return 41 } 42 if (timerID !== 0) { 43 clearInterval(timerID) 44 } 45 Logger.info(TAG, `Operation startBackgroundRunning succeeded`) 46 timerID = setInterval(() => { 47 notificationRequest.content.normal.text = `${num}%` 48 Notification.publish(notificationRequest).then(() => { 49 Logger.info(TAG, `==========================>publishCallback=======================>`); 50 }) 51 num += 5 52 if (num > 20) { 53 clearInterval(timerID) 54 } 55 }, 5000) 56} 57 58function startContinuousTask() { 59 Logger.info(TAG, `startBackground use new api`) 60 let wantAgentInfo = { 61 wants: [ 62 { 63 bundleName: "ohos.samples.backgroundtaskmanager", 64 abilityName: "ohos.samples.backgroundtaskmanager.MainAbility" 65 } 66 ], 67 operationType: wantAgent.OperationType.START_ABILITIES, 68 requestCode: 0, 69 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 70 }; 71 72 wantAgent.getWantAgent(wantAgentInfo).then((data) => { 73 Logger.info(TAG, `startBackground begin`) 74 backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data, callback) 75 }) 76} 77 78export default { 79 onStart() { 80 Logger.info(TAG, 'ServiceAbility onStart') 81 startContinuousTask() 82 }, 83 onStop() { 84 Logger.info(TAG, 'ServiceAbility onStop') 85 backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()) 86 }, 87 onCommand(want, startId) { 88 Logger.info(TAG, 'ServiceAbility onCommand') 89 } 90}