HarmonyOS NEXT之通知与窗口管理实战

59 阅读1分钟

通知系统架构

HarmonyOS的通知系统支持跨设备流转,结合窗口管理实现沉浸式交互体验。

通知流程:

在这里插入图片描述

沉浸式通知实现

// ImmersiveNotification.ets
import { Notification, notification } from '@ohos.notification';
import { window } from '@ohos.window';

@Entry
@Component
struct ImmersiveApp {
  @State showNotification: boolean = false;
  private windowStage: window.WindowStage | null = null;

  aboutToAppear() {
    // 获取窗口上下文
    window.getTopWindow(this.context).then((stage) => {
      this.windowStage = stage;
    });
  }

  // 发送沉浸式通知
  sendImmersiveNotification() {
    // 创建通知请求
    const request: Notification.Request = {
      content: {
        contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '会议提醒',
          text: '10分钟后与开发团队会议',
          additionalText: '点击加入'
        }
      },
      isAlertOnce: true, // 是否只提醒一次
      tapDismissed: true // 点击后消失
    };
    
    // 发布通知
    notification.publish(request).then(() => {
      console.info('通知发布成功');
      this.showNotification = true;
    });
    
    // 切换沉浸式窗口
    if (this.windowStage) {
      this.windowStage.setWindowSystemBarEnable(['status']).then(() => {
        this.windowStage.setWindowLayoutFullScreen(true);
      });
    }
  }

  // 处理通知点击
  onNotificationClick() {
    // 恢复窗口状态
    if (this.windowStage) {
      this.windowStage.setWindowSystemBarEnable(['status', 'navigation']);
      this.windowStage.setWindowLayoutFullScreen(false);
    }
    this.showNotification = false;
  }

  build() {
    Stack() {
      // 主应用内容
      Column() {
        Button('发送会议提醒')
          .onClick(() => this.sendImmersiveNotification())
          .width(200)
          .height(60)
          .margin(20)
      }
      .width('100%')
      .height('100%')
      
      // 沉浸式通知
      if (this.showNotification) {
        Column() {
          Text('会议提醒')
            .fontSize(20)
            .fontWeight(FontWeight.Bold)
            .margin({ top: 30, bottom: 10 })
          
          Text('10分钟后与开发团队会议')
            .fontSize(16)
            .margin({ bottom: 30 })
          
          Button('立即加入')
            .onClick(() => this.onNotificationClick())
            .width(120)
        }
        .width('100%')
        .height(200)
        .backgroundColor('#ffffff')
        .position({ y: 0 })
        .zIndex(999)
      }
    }
    .onClick(() => {
      if (this.showNotification) {
        this.onNotificationClick();
      }
    })
  }
}

窗口管理关键技术

  1. 沉浸式模式:
// 设置沉浸式状态栏
windowStage.setWindowSystemBarEnable(['status']);

// 全屏布局
windowStage.setWindowLayoutFullScreen(true);
  1. 窗口层级控制:
// 设置窗口位置
.position({ y: 0 })

// 设置Z轴层级
.zIndex(999)
  1. 通知交互:
    • 点击通知回调处理

    • 自动消失设置(tapDismissed)

    • 防止重复提醒(isAlertOnce)