1 个回答

参考此demo:

import Notification from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
import { WantAgent } from '@ohos.app.ability.wantAgent';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct InputPage {
  @State message: string = 'Hello World';


  notification(message:string) {

    let wantAgentObj:WantAgent | undefined = undefined// 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。

    // 通过WantAgentInfo的operationType设置动作类型
    let wantAgentInfo:wantAgent.WantAgentInfo = {
      wants: [
        {
          deviceId: '',
          bundleName: 'com.example.application',
          abilityName: 'EntryAbility',
          action: '',
          entities: [],
          uri: '',
          parameters: {}
        }
      ],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
    };

    // 创建WantAgent
    wantAgent.getWantAgent(wantAgentInfo, (err:BusinessError, data:WantAgent) => {
      if (err) {
        console.error(`Failed to get want agent. Code is ${err.code}, message is ${err.message}`);
        return;
      }
      console.info('Succeeded in getting want agent.');
      wantAgentObj = data;
      let notificationRequest: Notification.NotificationRequest  = {
        id: 1,
        content: {
          notificationContentType:Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
          normal: {
            title: "通知测试",
            text: message,
          }
        },
        notificationSlotType:Notification.SlotType.SOCIAL_COMMUNICATION,
        wantAgent: wantAgentObj
      }

      Notification.requestEnableNotification().then(() => {
        Notification.publish(notificationRequest).then(() =>{
          console.log("发布成功")
        }).catch((err: BusinessError) => {
          console.error(`publish:${err}`)
        })
      }).catch((err: BusinessError) => {
        console.error(`${err}`)
      })
    });
  }

  build() {
    Column(){
      Button('发布通知').onClick(() => {
        this.notification("这是一个通知")
      })
    }
  }
}

服务端推送配置abilityName:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/notification-with-wantagent-V5\#开发步骤

logo
HarmonyOS
子站问答
访问
宣传栏