鸿蒙开发:应用通知栏基本操作

🎯 应用通知栏基本操作

⭐⭐⭐⭐

📌 见解

通知旨在让用户以合适的方式及时获得有用的新消息,帮助用户高效地处理任务。应用可以通过通知接口发送通知消息,用户可以通过通知栏查看通知内容,也可以点击通知来打开应用

🎬 使用场景

使用场景特性描述相关API/组件
服务与通讯通知即时通讯、服务提醒(订单/出行/健康等),支持高优先级通知,允许触发铃声/振动NotificationManager.SlotType.SOCIAL_COMMUNICATION
NotificationRequest
资讯营销通知内容推荐/促销信息,静默展示在通知栏,无声音提示,每日推送数量受限默认slotType(非SOCIAL_COMMUNICATION)
进度条通知实时显示任务进度(如文件下载/上传)基于基础通知扩展实现
NotificationRequest中的progress参数
图片/多媒体通知展示商品详情等含图片或富媒体内容的通知NOTIFICATION_CONTENT_PICTURE
image.PixelMapFormat.RGBA_8888
交互式通知包含操作按钮(确认/取消),支持通知栏直接交互NotificationActionButton
定时/代理提醒闹钟、日程等需要精确时间触发的场景reminderAgentManager模块
publishReminder
系统级通知设备告警、系统更新等关键事件系统预留通道(如SlotType.SERVICE_REMINDER

🧩 拆解

⚠️ 注意

  • 更新通知: 在发出通知后,使用您之前使用的相同通知ID,再次调用notificationManager.publish来实现通知的更新。如果之前的通知是关闭的,将会创建新通知

  • 移除通知:

  • 通过通知ID和通知标签取消已发布的通知,notificationManager.cancel(notificationId)

  • 取消所有已发布的通知,notificationManager.cancelAll()

🧱 普通文本类型通知

// 1、获取用户授权才能发送通知。
windowStage.loadContent('pages/Index', (err) => {
  notificationManager.requestEnableNotification(this.context).then(() => {
      hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`);
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag',
          `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`)
    })
})

// 2、视图封装发送通知
pushTextNotification() {
// 设置发布通知的内容和相关配置信息
let notificationRequest: notificationManager.NotificationRequest = {
    // 描述通知的请求
    id: 1, // 通知ID
    content: {
    // 通知内容
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
        // 基本类型通知内容
        title: '通知内容标题',
        text: '通知内容详情'
    }
    }
}
// 发布通知 当发布通知成功,err为undefined,否则为错误对象。
notificationManager.publish(notificationRequest).then(() => { // 发布通知
    console.info('publish success');
}).catch((err: Error) => {
    console.error(`publish failed,message is ${err}`);
});
}

// 3、视图使用
Column() {
    // 文本
    Button('点击通知')
    .onClick(() => {
        this.pushTextNotification()
    })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)

🧱 发布进度类型通知

@State isSupport: boolean = false

aboutToAppear(): void {
// 1、通过该接口查询是否支持对应的通知模板。
notificationManager.isSupportTemplate('downloadTemplate').then(isSupport => {
    this.isSupport = isSupport
})
}
// 2、模拟下载发布通知
pushProgressNotification() {
if (!this.isSupport) return
setInterval(() => {
    const template: notificationManager.NotificationTemplate = {
    name: 'downloadTemplate',
    data: {
        title: '进度',
        fileName: '进度',
        progressValue: this.curProgress,
        progressMaxValue: 100,
        isProgressIndeterminate: false
    }
    };
    const notificationRequest: notificationManager.NotificationRequest = {
    id: 5,
    notificationSlotType: notificationManager.SlotType.CONTENT_INFORMATION,
    template: template,
    content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
        title: '进度',
        text: ' ',
        additionalText: `${this.curProgress}%`
        }
    },
    };

    // 发布通知
    notificationManager.publish(notificationRequest, (err: BusinessError) => {
    if (err) {
        return
    }
    })

    this.curProgress++
}, 1000)
}

🧱 添加意图以例1为case

// 1、创建对于状态变量
@State wantAgentObj: WantAgent | undefined = undefined // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作
  private bundleName: string = this.context.abilityInfo.bundleName
  private abilityName: string = this.context.abilityInfo.name

// 2、创建wantAgent
createWantAgent() {
// 通过WantAgentInfo的operationType设置动作类型
const wantAgentInfo: wantAgent.WantAgentInfo = {
    wants: [
    {
        deviceId: '',
        bundleName: this.bundleName, // 需要替换为对应的bundleName。
        abilityName: this.abilityName, // 需要替换为对应的abilityName。
        action: '',
        entities: [],
        uri: '',
        parameters: {}
    }
    ],
    actionType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    actionFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
}

// 创建WantAgent
wantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data: WantAgent) => {
    if (err) {
       return;
    }
    this.wantAgentObj = data
})
}

// 3、创天通知栏并且携带wantAgent
pushTextNotification() {
const notificationRequest: notificationManager.NotificationRequest = {
    // 描述通知的请求
    id: 1, // 通知ID
    content: {
    // 通知内容
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
        // 基本类型通知内容
        title: '通知内容标题',
        text: '通知内容详情'
    }
    },
    wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
    tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
}
notificationManager.publish(notificationRequest).then(() => { // 发布通知
    console.info('publish success');
}).catch((err: Error) => {
    console.error(`publish failed,message is ${err}`);
});
}

🧱 通知组(将不同类型的通知分为不同的组,以便用户可以更好的管理他们。)

// 1、创建通知栏组1
 /**
   * 文本通知
   */
pushTextNotification() {
const notificationRequest: notificationManager.NotificationRequest = {
    // 描述通知的请求
    id: 1, // 通知ID
    groupName: 'textGroup', // 用于归纳的组别
    content: {
    // 通知内容
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
        // 基本类型通知内容
        title: '通知内容标题',
        text: '通知内容详情'
    }
    },
    wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
    tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
}
notificationManager.publish(notificationRequest).then(() => { // 发布通知
    console.info('publish success');
}).catch((err: Error) => {
    console.error(`publish failed,message is ${err}`);
});
}

// 2、创建组别2
/**
   * 组通知类型(文本2)
   */
pushTextGroupNotification() {
const notificationRequest: notificationManager.NotificationRequest = {
    // 描述通知的请求
    id: 110, // 通知ID
    groupName: 'textGroup',
    content: {
    // 通知内容
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
    normal: {
        // 基本类型通知内容
        title: '通知内容标题组2',
        text: '通知内容详情组2'
    }
    },
    wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
    tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
}
notificationManager.publish(notificationRequest).then(() => { // 发布通知
    console.info('publish success');
}).catch((err: Error) => {
    console.error(`publish failed,message is ${err}`);
});
}

// 3、视图使用
// 通知组类型
Column() {
Text('通知组测试:')
    .fontSize(20)
    .fontWeight(FontWeight.Bold)
Row({ space: 20 }) {
    Button('文本组1')
    .onClick(() => {
        this.pushTextNotification()
    })

    Button('文本组2')
    .onClick(() => {
        this.pushTextGroupNotification()
    })
}
}

🔥🔥🔥 完整代码*

// 1、用户授权src/main/ets/entryability/EntryAbility.ets
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

windowStage.loadContent('pages/Index', (err) => {
    if (err.code) {
    hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
    return;
    }
    hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
    // TODO: 在这里授权
    notificationManager.requestEnableNotification(this.context).then(() => {
    hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`);
    }).catch((err: BusinessError) => {
    hilog.error(0x0000, 'testTag',
        `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
    });
});
}

// 2、构建视图 src/main/ets/pages/Index.ets
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common, wantAgent, WantAgent } from '@kit.AbilityKit';

@Entry
@Component
struct NotificationCase {
  private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext
  @State curProgress: number = 0
  @State isSupport: boolean = false
  @State wantAgentObj: WantAgent | undefined = undefined // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作
  private bundleName: string = this.context.abilityInfo.bundleName
  private abilityName: string = this.context.abilityInfo.name

  aboutToAppear(): void {
    // 通过该接口查询是否支持对应的通知模板。
    notificationManager.isSupportTemplate('downloadTemplate').then(isSupport => {
      this.isSupport = isSupport
    })

    this.createWantAgent()
  }

  aboutToDisappear(): void {
    notificationManager.cancelAll()
  }

  /**
   * wantAgent创建
   */
  createWantAgent() {
    // 通过WantAgentInfo的operationType设置动作类型
    const wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          deviceId: '',
          bundleName: this.bundleName, // 需要替换为对应的bundleName。
          abilityName: this.abilityName, // 需要替换为对应的abilityName。
          action: '',
          entities: [],
          uri: '',
          parameters: {}
        }
      ],
      actionType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      actionFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
    }

    // 创建WantAgent
    wantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data: WantAgent) => {
      if (err) {
        return;
      }
      this.wantAgentObj = data
    })
  }

  /**
   * 文本通知
   */
  pushTextNotification() {
    const notificationRequest: notificationManager.NotificationRequest = {
      // 描述通知的请求
      id: 1, // 通知ID
      groupName: 'textGroup',
      content: {
        // 通知内容
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
        normal: {
          // 基本类型通知内容
          title: '通知内容标题',
          text: '通知内容详情'
        }
      },
      wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
      tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
    }
    notificationManager.publish(notificationRequest).then(() => { // 发布通知
      console.info('publish success');
    }).catch((err: Error) => {
      console.error(`publish failed,message is ${err}`);
    });
  }

  /**
   * 进度条通知
   */
  pushProgressNotification() {
    if (!this.isSupport) {
      return
    }
    setInterval(() => {
      const template: notificationManager.NotificationTemplate = {
        name: 'downloadTemplate',
        data: {
          title: '进度',
          fileName: '进度',
          progressValue: this.curProgress,
        }
      };
      const notificationRequest: notificationManager.NotificationRequest = {
        id: 5,
        notificationSlotType: notificationManager.SlotType.CONTENT_INFORMATION,
        template: template,
        content: {
          notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
          normal: {
            title: '进度',
            text: ' ',
            additionalText: `${this.curProgress}%`
          }
        },
        wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
        tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
      };

      // 发布通知
      notificationManager.publish(notificationRequest, (err: BusinessError) => {
        if (err) {
          return
        }
      })

      this.curProgress++
    }, 1000)
  }

  /**
   * 组通知类型(文本2)
   */
  pushTextGroupNotification() {
    const notificationRequest: notificationManager.NotificationRequest = {
      // 描述通知的请求
      id: 110, // 通知ID
      groupName: 'textGroup',
      content: {
        // 通知内容
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
        normal: {
          // 基本类型通知内容
          title: '通知内容标题组2',
          text: '通知内容详情组2'
        }
      },
      wantAgent: this.wantAgentObj, // 携带wantAgentObj参数
      tapDismissed: false // 通知是否自动清除。当通知携带wantAgent或actionButtons时该字段生效。默认值为true。
    }
    notificationManager.publish(notificationRequest).then(() => { // 发布通知
      console.info('publish success');
    }).catch((err: Error) => {
      console.error(`publish failed,message is ${err}`);
    });
  }

  build() {
    Column({ space: 20 }) {

      Row({ space: 20 }) {
        Text('文本测试:')
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
        // 文本通知
        Button('文本通知')
          .onClick(() => {
            this.pushTextNotification()
          })
      }

      Column() {
        Text('进度条测试:')
          .fontSize(20)
          .fontWeight(FontWeight.Bold)

        // 进度条通知
        Column({ space: 20 }) {
          Button('进度条点击开始下载 (模拟)')
            .onClick(() => {
              this.pushProgressNotification()
            })
          Progress({ value: this.curProgress, total: 100, type: ProgressType.Linear })
        }
        .padding({ left: 20, right: 20 })
      }


      // 通知组类型
      Column() {
        Text('通知组测试:')
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
        Row({ space: 20 }) {
          Button('文本组1')
            .onClick(() => {
              this.pushTextNotification()
            })

          Button('文本组2')
            .onClick(() => {
              this.pushTextGroupNotification()
            })
        }
      }

    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

📝 通知会在不同场景以不同形式提示用户,例如通知在状态栏上显示为图标、在通知栏上会显示通知详细信息。重要的信息还可以使用横幅通知,浮动在界面顶部显示

🌸🌼🌺

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值