HarmonyOS通知的各種寫法

前言

通知(Notification)是應用為用戶顯示重要信息提示的一種工具妓柜。系統(tǒng)為開發(fā)者提供了不同種類的通知樣式模板可以使用,開發(fā)者也可以根據自己需要自定義通知樣式黎休。

代碼結構

與通知相關的主要邏輯在NotificationSlot撕阎、NotificationRequestNotificationHelper這三個類中宇智。

1炼邀、NotificationSlot

這是一個定義通知的主題類,它可以設置通知的特征集合鞍盗,包括通知到來時的提示音調、振動跳昼、鎖屏顯示以及設置通知的重要級別等般甲。一般可以在應用的AbilityPackage里設置,用以統(tǒng)一整個應用的通知主題特征庐舟,一個應用也可以關聯(lián)多個不同NotificationSlot的欣除。
重點說下NotificationSlot的幾個重要級別住拭,也可以查看官方Api文檔挪略,里面說明的更加詳細:

  • LEVEL_NONE: 表示通知不發(fā)布。

  • LEVEL_MIN:表示通知可以發(fā)布滔岳,但是不顯示在通知欄杠娱,不自動彈出,無提示音谱煤;該級別不適用于前臺服務的場景摊求。

  • LEVEL_LOW:表示通知可以發(fā)布且顯示在通知欄,不自動彈出刘离,無提示音室叉。

  • LEVEL_DEFAULT:表示通知發(fā)布后可在通知欄顯示睹栖,不自動彈出,觸發(fā)提示音茧痕。

  • LEVEL_HIGH:表示通知發(fā)布后可在通知欄顯示野来,自動彈出,觸發(fā)提示音踪旷。

    基本的使用
        // 創(chuàng)建notificationSlot對象
        NotificationSlot slot = new NotificationSlot(id, "testSlot", NotificationSlot.LEVEL_HIGH);
        slot.setDescription("create notificationSlot description");
        slot.setLevel(NotificationSlot.LEVEL_HIGH);
        // 設置振動提醒
        slot.setEnableVibration(true);
        // 設置鎖屏模式
        slot.setLockscreenVisibleness(NotificationRequest.VISIBLENESS_TYPE_PUBLIC);
        // 設置開啟呼吸燈提醒
        slot.setEnableLight(true);
        // 設置呼吸燈的提醒顏色
        slot.setLedLightColor(Color.RED.getValue());
        slot.enableBypassDnd(true);
        slot.enableBadge(true);
        try {
            NotificationHelper.addNotificationSlot(slot);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
關于設置呼吸燈說明曼氛,由于手上只有一部P40Pro不帶呼吸燈,所以無法驗證實際效果令野。

2舀患、NotificationRequest

NotificationRequest是通知最主要的部分,主要設置通知的樣式气破,HarmonyOS主要提供了6種類型的樣式:普通文本NotificationNormalContent聊浅、長文本NotificationLongTextContent、圖片NotificationPictureContent堵幽、多行NotificationMultiLineContent狗超、社交NotificationConversationalContent、媒體NotificationMediaContent朴下。另外還有一種自定義樣式努咐,這些會在后面具體介紹。
雖然通知中提供了各種屬性的設置殴胧,但是一個通知對象渗稍,有幾個屬性是必須要設置的,其他的屬性均是可選的团滥,必須設置的屬性如下:

  • 小圖標竿屹,使用setLittleIcon()方法設置。
  • 標題灸姊,使用setTitle()方法設置拱燃。
  • 文本內容,使用setText()方法設置力惯。
調用setIntentAgent()設置通知可以觸發(fā)的事件
        Intent intent = new Intent();
        // 指定要啟動的Ability的BundleName和AbilityName字段
        // 將Operation對象設置到Intent中
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(OtherAbility.class.getName())
                .build();
        intent.setOperation(operation);
        List<Intent> intentList = new ArrayList<>();
        intentList.add(intent);
        // 定義請求碼
        int requestCode = 200;
        // 設置flags
        List<IntentAgentConstant.Flags> flags = new ArrayList<>();
        flags.add(IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG);
        // 指定啟動一個有頁面的Ability
        IntentAgentInfo paramsInfo = new IntentAgentInfo(requestCode, 
                IntentAgentConstant.OperationType.START_ABILITY, flags, intentList, null);
        // 獲取IntentAgent實例
        IntentAgent agent = IntentAgentHelper.getIntentAgent(this, paramsInfo);
        setIntentAgent(agent );

具體API就不一一介紹了碗誉,可以參考官方

3、NotificationHelper

該靜態(tài)類主要是管理通知父晶,提供了發(fā)布哮缺、更新、刪除通知等靜態(tài)方法甲喝;
主要接口如下:

  • publishNotification(NotificationRequest request)尝苇,發(fā)布通知,當NotificationRequest被設置后,通過該接口去發(fā)布通知糠溜;
  • cancelNotification(int notificationId)淳玩,取消通知,每個NotificationRequest創(chuàng)建時都必須有一個notificationId,可以通過這個接口取消創(chuàng)建的通知;
  • cancelAllNotifications()汁蝶,取消之前發(fā)布的所以通知岩榆;
  • addNotificationSlot(NotificationSlot slot),創(chuàng)建一個NotificationSlot;
  • setNotificationBadgeNum(int num),設置通知的角標;

通知的代碼結構基本就是圍繞這三個類來構建的悄雅,其中最重要的就是NotificationRequest這個類,整個HarmonyOS各種酷炫通知都是基于這個類來定制的铁蹈,所以研究通知宽闲,不如說其實就是研究NotificationRequest。下面就來介紹下HarmonyOS官方提供的6中樣式以及自定義樣式握牧,基本也就包含日常所有的通知需求了容诬。

各種各樣的通知

1、普通文本NotificationNormalContent

這是通知最基礎也是最常用的樣式沿腰,對應設置NotificationRequest.setLittleIcon()览徒、NotificationNormalContent.setTitle()、NotificationNormalContent.setText()颂龙;

  • 效果圖


    screenshot_20210809093847407.png
  • 代碼示例
        int notificationId = 1;
        NotificationRequest request = new NotificationRequest(notificationId);
        request.setSlotId(slotId);
        request.setLittleIcon(littleIcon);

        // 普通文本
        NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
        content.setTitle(title)
                .setText(countent);
        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
        // 設置通知的內容
        request.setContent(notificationContent);
        request.setIntentAgent(intentAgent);
        try {
            NotificationHelper.publishNotification(request);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    /**
     * 圖片轉換工具方法
     *
     * @param drawableId
     * @return
     */
    private PixelMap getPixelMap(int drawableId) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = context.getResourceManager().getResource(drawableId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            ImageSource imageSource = ImageSource.create(drawableInputStream, sourceOptions);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            return imageSource.createPixelmap(decodingOptions);
        } catch (IOException | NotExistException e) {
            e.getMessage();
        } finally {
            if (drawableInputStream != null) {
                try {
                    drawableInputStream.close();
                } catch (IOException e) {
                    e.getMessage();
                }
            }
        }
        return null;
    }

2习蓬、長文本NotificationLongTextContent

  • 效果圖


    screenshot_20210809100231171.png
screenshot_20210809100255454.png
  • 代碼示例
int notificationId = 2;
        NotificationRequest request = new NotificationRequest(notificationId);
        request.setSlotId(slotId);
        request.setLittleIcon(littleIcon);
        // request.setBigIcon(bigIcon);

        // 長文本
        NotificationRequest.NotificationLongTextContent contentLong = new NotificationRequest.NotificationLongTextContent();
        contentLong.setTitle(title)
                .setLongText(longText);
        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(contentLong);
        // 設置通知的內容
        request.setContent(notificationContent);
        request.setIntentAgent(intentAgent);
        try {
            NotificationHelper.publishNotification(request);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

3、圖片NotificationPictureContent

  • 效果圖


    screenshot_20210809102703996.png
screenshot_20210809102723253.png
  • 代碼示例
        int notificationId = 4;
        NotificationRequest request = new NotificationRequest(notificationId);
        request.setSlotId(slotId);
        request.setLittleIcon(littleIcon);
        request.setBigIcon(icon);

        // 圖片通知
        NotificationRequest.NotificationPictureContent contentLong = new NotificationRequest.NotificationPictureContent();
        contentLong.setTitle(title)
                .setBigPicture(icon)
                .setExpandedTitle(title)
                .setText(context);
        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(contentLong);
        // 設置通知的內容
        request.setContent(notificationContent);
        request.setIntentAgent(intentAgent);
        try {
            NotificationHelper.publishNotification(request);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

4措嵌、多行NotificationMultiLineContent

  • 效果圖


    screenshot_20210809105650615.png
screenshot_20210809105706324.png
  • 代碼示例
        int notificationId = 5;
        NotificationRequest request = new NotificationRequest(notificationId);
        request.setSlotId(slot.getId());
        request.setLittleIcon(littleIcon);

        // 多行文本
        NotificationRequest.NotificationMultiLineContent multiLineContent = new NotificationRequest.NotificationMultiLineContent();
        multiLineContent.setTitle("工資單")
                .setText("保密文件躲叼,禁止傳遞")
                .addSingleLine("基礎工資: 210000")
                .addSingleLine("加班補助: 97630")
                .addSingleLine("餐補: 900")
                .addSingleLine("交通補助: 1200")
                .addSingleLine("出差補助: 9800")
                .setExpandedTitle("張學友工資單");
        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(multiLineContent);
        // 設置通知的內容
        request.setContent(notificationContent);
        request.setIntentAgent(intentAgent);
        try {
            NotificationHelper.publishNotification(request);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

5、社交NotificationConversationalContent

  • 效果圖


    screenshot_20210809110547240.png
screenshot_20210809110602434.png
  • 代碼示例
        ArrayList<String> arrayListStr = new ArrayList<>();
        arrayListStr.add("結婚以后兩個人在一起最重要的是什么企巢?");
        arrayListStr.add("你是如何走出人生的陰霾的枫慷?");
        arrayListStr.add("怎么不回復我?浪规?我生氣了;蛱!");
        arrayListStr.add("我真生氣了B薹帷I袼АT俟谩C鹊帧!你聽見了嗎!");
        arrayListStr.add("為什么新聞放完了總是要播出他們在收拾稿子的片段?");

        MessageUser messageUser = new MessageUser();
        messageUser.setName(name);
        messageUser.setPixelMap(icon);

        int notificationId = 3;
        NotificationRequest request = new NotificationRequest(notificationId);
        request.setSlotId(slot.getId());
        request.setLittleIcon(littleIcon);
        request.addMessageUser(messageUser);

        // 社交
        NotificationRequest.NotificationConversationalContent content = new NotificationRequest.NotificationConversationalContent(messageUser);
        content.setConversationTitle("[" + arrayListStr.size() + "條]" + name)
                .setConversationGroup(true);
        for (int i = 0; i < arrayListStr.size(); i++) {
            content.addConversationalMessage(arrayListStr.get(i), 1, messageUser);
        }

        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
        // 設置通知的內容
        request.setContent(notificationContent);
        request.setIntentAgent(intentAgent);
        try {
            NotificationHelper.publishNotification(request);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

6绍填、媒體NotificationMediaContent

具體媒體會話管理霎桅,請參考開發(fā)-媒體會話管理開發(fā)指導

  • 效果圖


    screenshot_20210809145747418.png
  • 代碼示例
        // 按鈕文字設置無效,圖標顏色也不生效讨永,默認都是灰色
        NotificationActionButton.Builder builder = new NotificationActionButton.Builder(pixelMap1, "btn1", null);
        NotificationActionButton.Builder builder1 = new NotificationActionButton.Builder(pixelMap2, "btn2", null);
        NotificationActionButton.Builder builder2 = new NotificationActionButton.Builder(pixelMap3, "btn3", null);

        int notificationId = 1;
        NotificationRequest request = new NotificationRequest(notificationId);
        request.setSlotId(slot.getId());
        request.setLittleIcon(littleIcon);
        request.addActionButton(builder.build());
        request.addActionButton(builder1.build());
        request.addActionButton(builder2.build());

        int[] a = {0, 1, 2};
        // 普通文本
       // setAVToken 將指定的AVToken附加滔驶,連接AVToken后,此通知可以與關聯(lián)的AVSession交互卿闹,以便用戶可以在此通知中控制媒體播放
        NotificationRequest.NotificationMediaContent mediaContent = new NotificationRequest.NotificationMediaContent();
        mediaContent.setTitle(title)
                .setText(conStr)
                .setAVToken(avBrowser.getAVToken())
                .setShownActions(a);
        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(mediaContent);
        // 設置通知的內容
        request.setContent(notificationContent);
        try {
            NotificationHelper.publishNotification(request);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

7揭糕、自定義通知樣式

  • 效果圖


    screenshot_20210809150635715.png
  • 代碼示例
        NotificationRequest request = new NotificationRequest(context, 5);
        request.setSlotId(slot.getId());
        request.setLittleIcon(littleIcon);

        String title = "";
        String text = "";
        NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
        content.setTitle(title).setText(text);
        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
        request.setContent(notificationContent);

        // layoutId就是自己定義的xml布局,需要在xml的父布局中設置一個卡片屬性“ohos:remote="true"”锻霎,否則自定義效果無法出現
        ComponentProvider componentProvider = new ComponentProvider(layoutId, context); // 創(chuàng)建ComponentProvider對象
//        componentProvider.setString(ResourceTable.Id_ongoing_card_text, "setText", "TextContent"); // 設置布局中的文本內容
        request.setCustomView(componentProvider);
        request.setIntentAgent(intentAgent);

        try {
            NotificationHelper.publishNotification(request);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

上面這些就是通知常用的幾種效果著角,有很多其他的屬性沒有在demo中展示出來,比如角標旋恼、通知欄進度條等吏口,這些都有屬性可以設置的,相比android冰更,鴻蒙的通知樣式更加全面也更加統(tǒng)一一些产徊,android在不同版本上樣式展示不一樣,相對來說開發(fā)的成本也更高一些蜀细,希望鴻蒙發(fā)展的越來越好舟铜。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市奠衔,隨后出現的幾起案子深滚,更是在濱河造成了極大的恐慌,老刑警劉巖涣觉,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件痴荐,死亡現場離奇詭異,居然都是意外死亡官册,警方通過查閱死者的電腦和手機生兆,發(fā)現死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來膝宁,“玉大人鸦难,你說我怎么就攤上這事≡币” “怎么了合蔽?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長介返。 經常有香客問我拴事,道長沃斤,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任刃宵,我火速辦了婚禮衡瓶,結果婚禮上,老公的妹妹穿的比我還像新娘牲证。我一直安慰自己哮针,他們只是感情好,可當我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布坦袍。 她就那樣靜靜地躺著十厢,像睡著了一般。 火紅的嫁衣襯著肌膚如雪捂齐。 梳的紋絲不亂的頭發(fā)上寿烟,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天,我揣著相機與錄音辛燥,去河邊找鬼筛武。 笑死,一個胖子當著我的面吹牛挎塌,可吹牛的內容都是我干的徘六。 我是一名探鬼主播,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼榴都,長吁一口氣:“原來是場噩夢啊……” “哼待锈!你這毒婦竟也來了?” 一聲冷哼從身側響起嘴高,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤竿音,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后拴驮,有當地人在樹林里發(fā)現了一具尸體春瞬,經...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年套啤,在試婚紗的時候發(fā)現自己被綠了宽气。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡潜沦,死狀恐怖萄涯,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情唆鸡,我是刑警寧澤涝影,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站争占,受9級特大地震影響燃逻,放射性物質發(fā)生泄漏序目。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一唆樊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧刻蟹,春花似錦逗旁、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至英古,卻和暖如春淀衣,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背召调。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工膨桥, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人唠叛。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓只嚣,卻偏偏與公主長得像,于是被迫代替她去往敵國和親艺沼。 傳聞我的和親對象是個殘疾皇子册舞,可洞房花燭夜當晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內容