Skip to content

通知意图

我们可以给通知或其中的按钮设置行为意图(Want),从而实现拉起应用组件或者发布公共事件等能力

简答来说: 就是点击通知后,跳转到 APP

流程:

  • 意图行为信息

  • 创建 wantAgent 实例

  • 通知请求

代码

创建意图和实例

js
import { wantAgent, WantAgent } from '@kit.AbilityKit';
@Entry
@Component
struct SecondPage {
  @State message: string = 'Hello World'
  pixel: PixelMap
  wantAgentInstance: WantAgent
  async aboutToAppear() {
    this.createWants()
  }
  // 创建wants
  async createWants(){
    // 1. 创建wangInfo信息
    let wantInfo: wantAgent.WantAgentInfo = {
      wants:[
        {
          bundleName: "com.jsopy.myapplication",
          abilityName:'EntryAbility'
          // 里面也可以设置路径
        }
      ],
      requestCode:0, // 设置ID可以通过这个ID获取数据
      operationType:wantAgent.OperationType.START_ABILITY,
      wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
    }
    // 2.创建实例
    this.wantAgentInstance = await wantAgent.getWantAgent(wantInfo)
  }
}

写一个通知

  • 发送的时候带上 wants
js

sendNormalText() {
    console.log("确实点击了")
    let request: notificationManager.NotificationRequest = {
      id: 10,
      wantAgent:this.wantAgentInstance,
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '通知标题',
          text: '通知详情',
          additionalText: "通知附加内容"
        }
      }
    }
    notificationManager.publish(request).then(() => {
      console.log("发送通知")
    }).catch((err) => {
      console.log("发送失败", JSON.stringify(err))
    })
  }

调用

js
Button("发送normalText通知")
  .type(ButtonType.Capsule)
  .onClick(() => {
    this.sendNormalText();
  });