BackgroundTaskManager.ets 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 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. import { common, wantAgent } from '@kit.AbilityKit';
  16. import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
  17. import { BusinessError } from '@kit.BasicServicesKit';
  18. import { hilog } from '@kit.PerformanceAnalysisKit';
  19. const TAG = 'onecold [BackgroundTaskManager]';
  20. /**
  21. * Background task tool class.
  22. */
  23. export class BackgroundTaskManager {
  24. public static startContinuousTask(context?: common.UIAbilityContext): void {
  25. if (!context) {
  26. return;
  27. }
  28. let wantAgentInfo: wantAgent.WantAgentInfo = {
  29. wants: [
  30. {
  31. bundleName: context.abilityInfo.bundleName,
  32. abilityName: context.abilityInfo.name
  33. }
  34. ],
  35. operationType: wantAgent.OperationType.START_ABILITY,
  36. requestCode: 0,
  37. wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
  38. };
  39. wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
  40. backgroundTaskManager.startBackgroundRunning(context,
  41. backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK, wantAgentObj).then(() => {
  42. hilog.info(0x0000, TAG, 'startBackgroundRunning succeeded');
  43. }).catch((err: BusinessError) => {
  44. hilog.error(0x0000, TAG, `startBackgroundRunning failed, cause: ${JSON.stringify(err)}`);
  45. });
  46. });
  47. }
  48. /**
  49. * Cancel continuous task
  50. */
  51. public static stopContinuousTask(context?: common.UIAbilityContext): void {
  52. if (!context) {
  53. return;
  54. }
  55. backgroundTaskManager.stopBackgroundRunning(context).then(() => {
  56. hilog.info(0x0000, TAG, 'stopBackgroundRunning succeeded');
  57. }).catch((err: BusinessError) => {
  58. hilog.error(0x0000, TAG, `stopBackgroundRunning failed, cause: ${JSON.stringify(err)}`);
  59. });
  60. }
  61. }