普通通知:
?
通知渠道,彈出消息后,自動消失
長文本通知
//多行文本通知
//圖片通知
//社交通知
//媒體通知--經測試,圖片無法顯示,文字不顯示
場景介紹
HarmonyOS提供了通知功能,即在一個應用的UI界面之外顯示的消息,主要用來提醒用戶有來自該應用中的信息。當應用向系統發出通知時,它將先以圖標的形式顯示在通知欄中,用戶可以下拉通知欄查看通知的詳細信息。常見的使用場景:
- 顯示接收到短消息、即時消息等。
- 顯示應用的推送消息,如廣告、版本更新等。
- 顯示當前正在進行的事件,如播放音樂、導航、下載等。
接口說明
通知相關基礎類包含NotificationSlot、NotificationRequest和NotificationHelper。基礎類之間的關系如下所示:
圖1?通知基礎類關系圖
- NotificationSlot
NotificationSlot可以對提示音、振動、重要級別等進行設置。一個應用可以創建一個或多個NotificationSlot,在發布通知時,通過綁定不同的NotificationSlot,實現不同用途。
說明
NotificationSlot需要先通過NotificationHelper的addNotificationSlot(NotificationSlot)方法發布后,通知才能綁定使用;所有綁定該NotificationSlot的通知在發布后都具備相應的特性,對象在創建后,將無法更改這些設置,對于是否啟動相應設置,用戶有最終控制權。
不指定NotificationSlot時,當前通知會使用默認的NotificationSlot,默認的NotificationSlot優先級為LEVEL_DEFAULT。
NotificationSlot的級別目前支持如下幾種, 由低到高:表1?NotificationSlot主要接口 接口名
描述
NotificationSlot(String id, String name, int level)
構造NotificationSlot。
setLevel(int level)
設置NotificationSlot的級別。
setName(String name)
設置NotificationSlot的命名。
setDescription(String description)
設置NotificationSlot的描述信息。
enableBypassDnd(boolean bypassDnd)
設置是否繞過系統的免打擾模式。
setEnableVibration(boolean vibration)
設置收到通知時是否使能振動。
setEnableLight(boolean isLightEnabled)
設置收到通知時是否開啟呼吸燈,前提是當前硬件支持呼吸燈。
setLedLightColor(int color)
設置收到通知時的呼吸燈顏色。
setSlotGroup(String groupId)
綁定當前NotificationSlot到一個NotificationSlot組。
- LEVEL_NONE: 表示通知不發布。
- LEVEL_MIN:表示通知可以發布,但不在狀態欄顯示,不自動彈出,無提示音;該級別不適用于前臺服務的場景。
- LEVEL_LOW:表示通知發布后在狀態欄顯示,不自動彈出,無提示音。
- LEVEL_DEFAULT:表示通知發布后在狀態欄顯示,不自動彈出,觸發提示音。
- LEVEL_HIGH:表示通知發布后在狀態欄顯示,自動彈出,觸發提示音。
- NotificationRequest
NotificationRequest用于設置具體的通知對象,包括設置通知的屬性,如:通知的分發時間、小圖標、大圖標、自動刪除等參數,以及設置具體的通知類型,如普通文本、長文本等。
具體的通知類型:目前支持六種類型,包括普通文本NotificationNormalContent、長文本NotificationLongTextContent、圖片NotificationPictureContent、多行NotificationMultiLineContent、社交NotificationConversationalContent、媒體NotificationMediaContent。表2?NotificationRequest主要接口 接口名
描述
NotificationRequest()
構建一個通知。
NotificationRequest(int notificationId)
構建一個通知,指定通知的id。通知的Id在應用內具有唯一性,如果不指定,默認為0。
setNotificationId?(int notificationId)
設置當前通知id。
setAutoDeletedTime?(long time)
設置通知自動取消的時間戳。
setContent?(NotificationRequest.NotificationContent content)
設置通知的具體內容。
setDeliveryTime?(long deliveryTime)
設置通知分發的時間戳。
setSlotId(String slotId)
設置通知的NotificationSlot id。
setTapDismissed?(boolean tapDismissed)
設置通知在用戶點擊后是否自動取消。
setLittleIcon?(PixelMap smallIcon)
設置通知的小圖標,在通知左上角顯示。
setBigIcon(PixelMap bigIcon)
設置通知的大圖標,在通知的右邊顯示。
setGroupValue(String groupValue)
設置分組通知,相同分組的通知在通知欄顯示時,將會折疊在一組應用中顯示。
addActionButton(NotificationActionButton actionButton)
設置通知添加通知ActionButton。
setIntentAgent(IntentAgent agent)
設置通知承載指定的IntentAgent,在通知中實現即將觸發的事件。
表3?通知類型的主要接口 類名
接口名
描述
NotificationNormalContent
setTitle(String title)
設置通知標題。
NotificationNormalContent
setText?(String text)
設置通知內容。
NotificationNormalContent
setAdditionalText(String additionalText)
設置通知次要內容,是對通知內容的補充。
NotificationPictureContent
setBriefText(String briefText)
設置通知概要內容,是對通知內容的總結。
NotificationPictureContent
setExpandedTitle(String expandedTitle)
設置附加圖片的通知展開時的標題。
NotificationPictureContent
setBigPicture(PixelMap bigPicture)
設置通知的圖片內容,附加在setText?(String text)下方。
NotificationLongTextContent
setLongText?(String longText)
設置通知的長文本。
NotificationConversationalContent
setConversationTitle(String conversationTitle)
設置社交通知的標題。
NotificationConversationalContent
addConversationalMessage(ConversationalMessage message)
通知添加一條消息。
NotificationMultiLineContent
addSingleLine(String line)
在當前通知中添加一行文本。
NotificationMediaContent
setAVToken(AVToken avToken)
將媒體通知綁定指定的AVToken。
NotificationMediaContent
setShownActions(int[] actions)
設置媒體通知待展示的按鈕。
說明
通知發布后,通知的設置不可修改。如果下次發布通知使用相同的id,就會更新之前發布的通知。
- NotificationHelperNotificationHelper封裝了發布、更新、刪除通知等靜態方法。
表4?NotificationHelper主要接口 接口名
描述
publishNotification(NotificationRequest request)
發布一條通知。
publishNotification(String tag, NotificationRequest request)
發布一條帶TAG的通知。
cancelNotification(int notificationId)
取消指定的通知。
cancelNotification(String tag, int notificationId)
取消指定的帶TAG的通知。
cancelAllNotifications()
取消之前發布的所有通知。
addNotificationSlot(NotificationSlot slot)
創建一個NotificationSlot。
getNotificationSlot(String slotId)
獲取NotificationSlot。
removeNotificationSlot(String slotId)
刪除一個NotificationSlot。
getActiveNotifications()
獲取當前應用發的活躍通知。
getActiveNotificationNums()
獲取系統中當前應用發的活躍通知的數量。
setNotificationBadgeNum(int num)
設置通知的角標。
setNotificationBadgeNum()
設置當前應用中活躍狀態通知的數量在角標顯示。
開發步驟
通知的開發指導分為創建NotificationSlot、發布通知和取消通知等開發場景。
創建NotificationSlot
NotificationSlot可以設置公共通知的震動,重要級別等,并通過調用NotificationHelper.addNotificationSlot()發布NotificationSlot對象。
- NotificationSlot slot = new NotificationSlot("slot_001", "slot_default", NotificationSlot.LEVEL_MIN); // 創建notificationSlot對象
- slot.setDescription("NotificationSlotDescription");
- slot.setEnableVibration(true); // 設置振動提醒
- slot.setEnableLight(true); // 設置開啟呼吸燈提醒
- slot.setLedLightColor(Color.RED.getValue());// 設置呼吸燈的提醒顏色
- try {
- NotificationHelper.addNotificationSlot(slot);
- } catch (RemoteException ex) {
- HiLog.error(LABEL, "Exception occurred during addNotificationSlot invocation.");
- }
發布通知
- 構建NotificationRequest對象,應用發布通知前,通過NotificationRequest的setSlotId()方法與NotificationSlot綁定,使該通知在發布后都具備該對象的特征。
- int notificationId = 1;
- NotificationRequest request = new NotificationRequest(notificationId);
- request.setSlotId(slot.getId());
- 調用setContent()設置通知的內容。
- String title = "title";
- String text = "There is a normal notification content.";
- NotificationNormalContent content = new NotificationNormalContent();
- content.setTitle(title)
- .setText(text);
- NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
- request.setContent(notificationContent); // 設置通知的內容
- 調用publishNotification()發布通知。
- try {
- NotificationHelper.publishNotification(request);
- } catch (RemoteException ex) {
- HiLog.error(LABEL, "Exception occurred during publishNotification invocation.");
- }
?
顯示另外一個頁面。
?
?
MainAbilitySlice.java?
package com.example.myapplication.slice;import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.render.opengl.Utils;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.event.intentagent.IntentAgent;
import ohos.event.intentagent.IntentAgentConstant;
import ohos.event.intentagent.IntentAgentHelper;
import ohos.event.intentagent.IntentAgentInfo;
import ohos.event.notification.*;
import ohos.global.resource.NotExistException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;
import ohos.miscservices.timeutility.Time;
import ohos.rpc.RemoteException;import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.List;public class MainAbilitySlice extends AbilitySlice {@Overridepublic void onStart(Intent intent) {super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);Button btn1 = (Button) findComponentById(ResourceTable.Id_btn1);btn1.setClickedListener(new Component.ClickedListener() {@Overridepublic void onClick(Component component) {ShowNoti1();}});Button btn2 = (Button) findComponentById(ResourceTable.Id_btn2);btn2.setClickedListener(new Component.ClickedListener() {@Overridepublic void onClick(Component component) {IntentAgent agent = createOpenThisAbilityIntentAgent1();NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent().setTitle("notification test").setText("單擊打開PageAbility頁面");//創建頁面方法,參考這里。https://txwtech.blog.csdn.net/article/details/135095068NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);NotificationRequest request = new NotificationRequest(1002).setContent(notificationContent).setIntentAgent(agent);try{NotificationHelper.publishNotification(request);}catch (Exception ex){}}});//創建通知渠道NotificationSlot slot = new NotificationSlot("slot1","一般性通知",NotificationSlot.LEVEL_DEFAULT);slot.setDescription("一般性通知");NotificationSlot slot2 = new NotificationSlot("slot2","特別重要通知",NotificationSlot.LEVEL_HIGH);slot2.setDescription("特別重要通知");//震動提醒slot2.setEnableVibration(true);//鎖屏通知slot2.setLockscreenVisibleness(NotificationRequest.VISIBLENESS_TYPE_PUBLIC);//跳過免打擾模式slot2.enableBypassDnd(true);//開啟呼吸燈提醒slot2.setEnableLight(true);//設置呼吸燈的提醒顏色slot2.setLedLightColor(Color.RED.getValue());try{NotificationHelper.addNotificationSlot(slot);NotificationHelper.addNotificationSlot(slot2);}catch (RemoteException e){//加入通知渠道失敗ToastDialog toastDialog = new ToastDialog(this);toastDialog.setTransparent(true).setDuration(2000).setAlignment(LayoutAlignment.BOTTOM+LayoutAlignment.HORIZONTAL_CENTER).setOffset(0,200)//距離底邊距離.show();}Button button_qudao = (Button) findComponentById(ResourceTable.Id_btn3_qudao);button_qudao.setClickedListener(new Component.ClickedListener() {@Overridepublic void onClick(Component component) {QudaoNotification();}});Button button_long_text = (Button) findComponentById(ResourceTable.Id_btn4_long_text);button_long_text.setClickedListener(new Component.ClickedListener() {@Overridepublic void onClick(Component component) {LongTextNotification();}});Button button_duohang = (Button) findComponentById(ResourceTable.Id_btn5_duohang);button_duohang.setClickedListener(new Component.ClickedListener() {@Overridepublic void onClick(Component component) {MultiTextNotification();}});Button button_pic = (Button) findComponentById(ResourceTable.Id_btn3_picture);button_pic.setClickedListener(new Component.ClickedListener() {@Overridepublic void onClick(Component component) {PictureNotification();}});Button button_social = (Button) findComponentById(ResourceTable.Id_btn4_social);button_social.setClickedListener(new Component.ClickedListener() {@Overridepublic void onClick(Component component) {SocialNotification();}});Button button_media = (Button) findComponentById(ResourceTable.Id_btn5_media);button_media.setClickedListener(new Component.ClickedListener() {@Overridepublic void onClick(Component component) {MediaNotification();}});}public void ShowNoti1(){NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent().setTitle("標題Title").setText("內容Text").setAdditionalText("次要內容");//創建notificationContent通知內容對象NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);//創建notificationRequest通知請求對象NotificationRequest request = new NotificationRequest(1001).setContent(notificationContent);try{//發布通知NotificationHelper.publishNotification(request);}catch (RemoteException ex){HiLog.info(new HiLogLabel(1,1,null),"aa");}}//創建方法private IntentAgent createOpenThisAbilityIntentAgent1(){//創建打開ablity的Itent對象Operation operation = new Intent.OperationBuilder().withDeviceId("").withBundleName("com.example.myapplication").withAbilityName("com.example.myapplication.PageAbility").build();Intent intent = new Intent();intent.setOperation(operation);//將Intent對象添加到List<intent>對象中List<Intent> intents = new ArrayList<>();intents.add(intent);//創建flags對象List<IntentAgentConstant.Flags> flags = new ArrayList<>();flags.add(IntentAgentConstant.Flags.ONE_TIME_FLAG);//創建啟動Ability的ItentAgentInfo對象IntentAgentInfo info = new IntentAgentInfo(200,IntentAgentConstant.OperationType.START_ABILITIES,flags,intents,null);//通過IntentAgentHelper創建IntentAgent對象IntentAgent agent = IntentAgentHelper.getIntentAgent(this,info);return agent;}//通知渠道public void QudaoNotification(){//普通文本通知內容NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent().setTitle("重要通知").setText("雨天路滑,注意安全");//創建notificationContent通知內容對象NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);NotificationRequest request = new NotificationRequest(1003).setContent(notificationContent).setSlotId("slot2");try{//發布通知NotificationHelper.publishNotification(request);}catch (RemoteException e){}}/*長文本通知*/public void LongTextNotification(){NotificationRequest.NotificationLongTextContent content = new NotificationRequest.NotificationLongTextContent();content.setTitle("標題title").setExpandedTitle("擴展標題expandedtitle").setAdditionalText("額外內容addtitionalText").setLongText("長文本,longtext,longtext");//創建通知內容對象NotificationRequest.NotificationContent notificationContent= new NotificationRequest.NotificationContent(content);//創建通知請求對象NotificationRequest request = new NotificationRequest(1004).setContent(notificationContent);try{//發布通知NotificationHelper.publishNotification(request);}catch (RemoteException ex){}}//多行文本通知public void MultiTextNotification(){NotificationRequest.NotificationMultiLineContent multiLineContent = new NotificationRequest.NotificationMultiLineContent();multiLineContent.setTitle("多行文本").setText("內容text").setExpandedTitle("擴展標題").addSingleLine("行1內容").addSingleLine("行2內容").addSingleLine("行3內容");NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(multiLineContent);NotificationRequest notificationRequest = new NotificationRequest(1005);notificationRequest.setContent(notificationContent);try{NotificationHelper.publishNotification(notificationRequest);}catch (RemoteException ex){}}//圖片通知public void PictureNotification(){NotificationRequest.NotificationPictureContent notificationPictureContent = new NotificationRequest.NotificationPictureContent();notificationPictureContent.setTitle("圖片標題-荷花").setText("內容。。。").setBriefText("春天來了,天氣不錯,記得曬太陽哦").setExpandedTitle("溫馨提示").setBigPicture(getPixelMap((ResourceTable.Media_hehua)));NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(notificationPictureContent);NotificationRequest request = new NotificationRequest(1006);request.setContent(notificationContent);try{NotificationHelper.publishNotification(request);}catch (RemoteException ex){}}//圖片通知private PixelMap getPixelMap(int drawableId){InputStream drawableInputStream = null;try{drawableInputStream = getResourceManager().getResource(drawableId);ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();sourceOptions.formatHint="image/png";ImageSource imageSource = ImageSource.create(drawableInputStream,sourceOptions);ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();decodingOptions.desiredSize = new Size(0,0);decodingOptions.desiredRegion = new Rect(0,0,0,0);decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);return pixelMap;}catch (Exception ex){ex.printStackTrace();}finally {try{if(drawableInputStream!=null){drawableInputStream.close();}}catch (Exception e){e.printStackTrace();}}return null;}//社交通知private void SocialNotification(){MessageUser user1 = new MessageUser();user1.setName("張大天");user1.setPixelMap(getPixelMap(ResourceTable.Media_dog1));MessageUser user2 = new MessageUser();user2.setName("小明");user2.setPixelMap(getPixelMap(ResourceTable.Media_rabit));//社交通知內容NotificationRequest.NotificationConversationalContent notificationConversationalContent = new NotificationRequest.NotificationConversationalContent(user1);notificationConversationalContent.setConversationTitle("即時消息").addConversationalMessage(new NotificationRequest.NotificationConversationalContent.ConversationalMessage("您好", Time.getCurrentTime(),user1)).addConversationalMessage(new NotificationRequest.NotificationConversationalContent.ConversationalMessage("在哦,您好",Time.getCurrentTime(),user2));NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(notificationConversationalContent);NotificationRequest notificationRequest = new NotificationRequest(1007);notificationRequest.setContent(notificationContent);try{NotificationHelper.publishNotification(notificationRequest);}catch (RemoteException ex){}}//媒體通知--經測試,圖片無法顯示,文字不顯示private void MediaNotification(){NotificationRequest.NotificationMediaContent content = new NotificationRequest.NotificationMediaContent();content.setTitle("標題title").setText("媒體通知--內容text").setAdditionalText("額外內容").setShownActions(new int[]{0});//定義3個按鈕NotificationActionButton btn1 = new NotificationActionButton.Builder(getPixelMap(ResourceTable.Media_play),"開始",null).build();NotificationActionButton btn2 = new NotificationActionButton.Builder(getPixelMap(ResourceTable.Media_heart),"喜歡",null).build();NotificationActionButton btn3 = new NotificationActionButton.Builder(getPixelMap(ResourceTable.Media_start),"收藏",null).build();NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);NotificationRequest notificationRequest = new NotificationRequest(1008).setContent(notificationContent).addActionButton(btn1).addActionButton(btn2).addActionButton(btn3);try{NotificationHelper.publishNotification(notificationRequest);}catch (RemoteException ex){}}@Overridepublic void onActive() {super.onActive();}@Overridepublic void onForeground(Intent intent) {super.onForeground(intent);}
}
?項目工程代碼:
待更新。。。