鴻蒙HarmonyOS NEXT開發:給應用添加基礎類型通知和進度條類型通知(API 12)

一、通知介紹

通知旨在讓用戶以合適的方式及時獲得有用的新消息,幫助用戶高效地處理任務。應用可以通過通知接口發送通知消息,用戶可以通過通知欄查看通知內容,也可以點擊通知來打開應用,通知主要有以下使用場景:

  • 顯示接收到的短消息、即時消息等。
  • 顯示應用的推送消息,如廣告、版本更新等。
  • 顯示當前正在進行的事件,如下載等。

1、通知表現形式

通知會在不同場景以不同形式提示用戶,例如通知在狀態欄上顯示為圖標、在通知欄上會顯示通知詳細信息。重要的信息還可以使用橫幅通知,浮動在界面頂部顯示。

0000000000011111111.20240831114611.52263784648924323943901764523007.png

2、通知結構

下面以基礎的文本通知為例,介紹通知的基本結構。

0000000000011111111.20240831114611.84896828121631342175896810656584.png
  1. 通知小圖標:表示通知的功能與類型。

  2. 通知名稱:應用名稱或功能名稱。

  3. 時間:發送通知的時間,系統默認顯示。

  4. 展開箭頭:點擊標題區,展開被折疊的內容和按鈕。若無折疊的內容和按鈕,不顯示此箭頭。

  5. 內容標題:描述簡明概要。

  6. 內容詳情:描述具體內容或詳情。

3、請求通知授權

應用需要獲取用戶授權才能發送通知。在通知發布前調用requestEnableNotification()方法,彈窗讓用戶選擇是否允許發送通知,后續再次調用requestEnableNotification()方法時,則不再彈窗。

  • 導入NotificationManager模塊。
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
  • 請求通知授權。

可通過requestEnableNotification的錯誤碼判斷用戶是否授權。

let context = getContext(this) as common.UIAbilityContext;
notificationManager.isNotificationEnabled().then((data: boolean) => {
  console.info("isNotificationEnabled success");
  if(!data){
    notificationManager.requestEnableNotification(context).then(() => {
      console.info(`requestEnableNotification success`);
    }).catch((err : BusinessError) => {
      if(1600004 == err.code){
        console.error(`requestEnableNotification refused, code is ${err.code}, message is ${err.message}`);
      } else {
        console.error(`requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
      }
    });
  }
}).catch((err : BusinessError) => {
    console.error(`isNotificationEnabled fail, code is ${err.code}, message is ${err.message}`);
});

二、創建通知

本節將介紹幾種常見類型通知的創建,在創建通知前需要先導入notificationManager模塊,該模塊提供通知管理的能力,包括發布、取消發布通知,創建、獲取、移除通知通道等能力。

import { notificationManager } from '@kit.NotificationKit';

1、發布基礎類型通知

基礎類型通知主要應用于發送短信息、提示信息、廣告推送等,支持普通文本類型、長文本類型、多行文本類型,可以通過ContentType指定通知的內容類型。下面以普通文本類型為例來介紹基礎通知的發布,其它基礎類型您可以查閱API。

微信圖片_20240712144927.png

發布普通文本類型通知,需要設置ContentType類型為ContentType.NOTIFICATION_CONTENT_BASIC_TEXT。

@Entry 
@Component 
struct NotificationDemo { 
  publishNotification() { 
    let notificationRequest: notificationManager.NotificationRequest = { // 描述通知的請求 
      id: 1, // 通知ID  
      content: { // 通知內容 
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本類型通知 
        normal: { // 基本類型通知內容 
          title: '通知內容標題', 
          text: '通知內容詳情' 
        } 
      } 
    } 
    notificationManager.publish(notificationRequest).then(() => { // 發布通知 
      console.info('publish success'); 
    }).catch((err: Error) => { 
      console.error(`publish failed,message is ${err}`); 
    }); 
  } 
 
  build() { 
    Column() { 
      Button('發送通知') 
        .onClick(() => { 
          this.publishNotification() 
        }) 
    } 
    .width('100%') 
  } 
}
微信圖片_20241101162239.png

2、發布進度類型通知

進度條通知也是常見的通知類型,主要應用于文件下載、事務處理進度顯示。目前系統模板僅支持進度條模板,效果示意如下圖所示:


1718527263488.gif

核心代碼

  /**
   * 查詢系統是否支持進度條模板
   */
    notificationManager.isSupportTemplate('downloadTemplate').then(isSupport => {
      // isSupport的值為true表示支持downloadTemplate模板類通知,false表示不支持
      this.isSupport = isSupport;
    });

  /**
   * 開始下載
   */
  download() {
  //通過定時器更新進度到通知
    this.interval = setInterval(() => {
      if (this.downloadProgress === 100) {
        this.downloadStatus = 3;
        this.notificationTitle = '已完成'
        clearInterval(this.interval);
      } else {
        this.downloadProgress += 2
      }
      if (this.isSupport) {
        this.publishNotification(this.downloadProgress, this.notificationTitle, this.wantAgentObj);
      }
    }, 1000);
  }


  /**
   * 發布通知
   */
  publishNotification(progress: number, title: string, wantAgentObj: object) {
    //構造進度條模板對象
    let template: notificationManager.NotificationTemplate = {
      // 構造進度條模板,name字段當前需要固定配置為downloadTemplate
      name: 'downloadTemplate',
      data: {
        title: `${title}`,
        fileName: `鴻蒙教程文件.zip`,
        progressValue: progress,
        progressMaxValue: 100,
        isProgressIndeterminate: false
      }
    };
    let notificationRequest: notificationManager.NotificationRequest = {
      id: 10000,
      //內容資訊
      notificationSlotType: notificationManager.SlotType.CONTENT_INFORMATION,
      template: template,
      content: {
        //普通類型通知
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: `鴻蒙教程文件.zip`,
          text: ' ',
          additionalText: `${progress}%`
        }
      },
      wantAgent: wantAgentObj
    };
    // 發布通知
    notificationManager.publish(notificationRequest).catch((err: Error) => {
      console.error(`publish failed,message is ${err}`);
    });
  }
微信圖片_20241104110721.png

3、更新通知

在發出通知后,使用您之前使用的相同通知ID,再次調用notificationManager.publish來實現通知的更新。如果之前的通知是關閉的,將會創建新通知。

4、移除通知

  • 通過通知ID和通知標簽取消已發布的通知。
    notificationManager.cancel(notificationId)

  • 取消所有已發布的通知。
    notificationManager.cancelAll()

三、設置通知通道

通過通知通道,您可讓通知有不同的表現形式,比如社交類型的通知是橫幅顯示的,并且有提示音,而一般的通知則不會橫幅顯示,您可以使用slotType來實現,設置slotType為SlotType.SOCIAL_COMMUNICATION,表示為社交類型通知。

示例代碼如下:

notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION).then(() => {
  console.info("addSlot success");
}).catch((err: Base.BusinessError) => {
  console.error(`addSlot fail: ${JSON.stringify(err)}`);
});

效果圖如下:

0000000000011111111.20240831114611.83103277592538093209223763047772.png

1、通知通道類型

不同類型的通知渠道對應的通知提醒方式不同,詳見下表。其中,Y代表支持,N代表不支持。

微信圖片_20241101160615.png

四、創建通知組

將不同類型的通知分為不同的組,以便用戶可以更好的管理他們。當同組的通知有多條的時候,會自動折疊起來,避免通知比較多的時候,通知界面比較雜亂,例如當通知欄里有聊天消息通知和商品推薦通知時,我們只需要通過設置字段groupName,就可以對通知進行分組,給groupName設置不同的值可以將通知分為不同的組。

0000000000011111111.20240831114611.68819239599944078582458528232618.png

您可以使用groupName來指定通知組來實現,

示例代碼如下:

let notifyId = 0; 
 
let chatRequest: notificationManager.NotificationRequest = {  
  id: notifyId++, 
  groupName:'ChatGroup', 
  content: { 
    //... 
   } 
 }; 
 
let productRequest: notificationManager.NotificationRequest = {  
  id: notifyId++, 
  groupName: 'ProductGroup', 
  content: { 
    //... 
   } 
 };

五、為通知添加行為意圖

WantAgent提供了封裝行為意圖的能力,這里所說的行為意圖主要是指拉起指定的應用組件及發布公共事件等能力。給通知添加行為意圖后,點擊通知后可以拉起指定的UIAbility或者發布公共事件,您可以按照以下步驟來實現:

1、導入模塊。

import { notificationManager } from '@kit.NotificationKit'; 
import { wantAgent, WantAgent } from '@kit.AbilityKit';

2、創建WantAgentInfo信息。

  • 場景一:拉起UIAbility。
let wantAgentInfo = { 
  wants: [ 
    { 
      bundleName: "com.example.notification", 
      abilityName: "EntryAbility" 
    } 
  ], 
  operationType: wantAgent.OperationType.START_ABILITY, 
  requestCode: 100 
}
  • 場景二:發布公共事件。
let wantAgentInfo = { 
  wants: [ 
    { 
      action: 'event_name', // 設置事件名 
      parameters: {}, 
    } 
  ], 
  operationType: wantAgent.OperationType.SEND_COMMON_EVENT, 
  requestCode: 100, 
  wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG], 
}

4、創建WantAgent對象。

let wantAgentObj = null;  
wantAgent.getWantAgent(wantAgentInfo) 
  .then((data) => { 
    wantAgentObj = data; 
  }) 
  .catch((err: Error) => { 
    console.error(`get wantAgent failed because ${JSON.stringify(err)}`); 
  })

5、構造NotificationRequest對象。

let notificationRequest: notificationManager.NotificationRequest = {
  id: 1, 
  content: { 
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, 
    normal: { 
      title: "通知標題", 
      text: "通知內容" 
    } 
  }, 
  wantAgent: wantAgentObj 
};

6、發布WantAgent通知。

notificationManager.publish(notificationRequest).then(() => { // 發布通知
  console.info("publish success"); 
}).catch((err: Error) => { 
  console.error(`publish failed, code is ${err.code}, message is ${err.message}`); 
});  

用戶通過點擊通知欄上的通知,即可觸發WantAgent的動作。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容