• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
17import { notificationUtil, notificationContentUtil, notificationRequestUtil, wantAgentUtil } from '@ohos/notification'
18import { logger } from '@ohos/details-page-component'
19
20const TAG: string = 'WorkAbility'
21const BUNDLE_NAME = 'ohos.samples.orangeshopping'
22const ABILITY_NAME = 'MainAbility'
23const NOTIFICATION_ID = 1 // 定义发送通知的id,默认1
24
25export default class WorkAbility extends WorkSchedulerExtensionAbility {
26  onWorkStart(workInfo) {
27    logger.info(TAG, `onWorkStart ${JSON.stringify(workInfo)}`)
28    if (workInfo.parameters) {
29      this.publishNotification(workInfo.parameters)
30    }
31  }
32
33  onWorkStop(workInfo) {
34    logger.info(TAG, `onWorkStop ${JSON.stringify(workInfo)}`)
35    notificationUtil.cancelNotificationById(1)
36  }
37
38  publishNotification = async (parameters: any) => {
39    let parametersObject = JSON.parse(parameters)
40    logger.info(TAG, `publishNotification parametersObject= ${parametersObject}`)
41    let basicContent = {
42      title: parametersObject.title,
43      text: ''
44    }
45    let actionButtons = [
46      {
47        title: parametersObject.firstButton,
48        wantAgent: await wantAgentUtil.createWantAgentForCommonEvent('')
49      },
50      {
51        title: parametersObject.secondButton,
52        wantAgent: await wantAgentUtil.createWantAgentForStartAbility(BUNDLE_NAME, ABILITY_NAME)
53      }
54    ]
55    try {
56      let notificationContent = notificationContentUtil.initBasicNotificationContent(basicContent)
57      let notificationRequest = notificationRequestUtil.initButtonNotificationRequest(notificationContent, actionButtons)
58      notificationUtil.publishNotification(notificationRequest, NOTIFICATION_ID)
59    } catch (error) {
60      logger.info(TAG, `publish notification error ${JSON.stringify(error)}`)
61    }
62  }
63}