通知


通知用于在应用程序处于后台时向用户提示必要的信息。如微信好友消息、追剧更新、支付宝付款等。

1 文本通知

在应用中发布通知,手机顶栏出现图标,下拉顶栏显示通知框。

NotificationNormalContent normal =
    new NotificationNormalContent()
    .setTitle("祝您健康") // 标题
    .setText("休息,休息一会……") // 内容
    .setAdditionalText("不会休息就不会工作"); // 次要内容

NotificationContent content =
    new NotificationContent(normal);

NotificationRequest request =
    new NotificationRequest(1001) // 通知ID
    .setContent(content); // ID相同的通知,新的替换旧的

try {
    NotificationHelper.publishNotification(request);
}
catch (RemoteException exception) {
    HiLog.error(label, exception.getLocalizedMessage());
}

例程:TextNotification

...\TextNotification\entry\src\main\resources\base\graphic\background_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="100"/>
    <solid ohos:color="#00a2e8"/>
</shape>

...\TextNotification\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:btn"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="30vp"
        ohos:top_padding="10vp"
        ohos:right_padding="30vp"
        ohos:bottom_padding="10vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="发布通知"
        ohos:text_size="28fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\TextNotification\entry\src\main\java\com\minwei\textnotification\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(
        HiLog.LOG_APP, 0x00101,
        MainAbilitySlice.class.getCanonicalName());

    @Override
    public void onStart(Intent intent) {
        ...
        findComponentById(ResourceTable.Id_btn)
            .setClickedListener(component -> {
                NotificationNormalContent normal =
                    new NotificationNormalContent()
                    .setTitle("祝您健康")
                    .setText("休息,休息一会……")
                    .setAdditionalText("不会休息就不会工作");

                NotificationContent content =
                    new NotificationContent(normal);

                NotificationRequest request =
                    new NotificationRequest(1001)
                    .setContent(content);

                try {
                    NotificationHelper.publishNotification(request);
                }
                catch (RemoteException exception) {
                    HiLog.error(label, exception.getLocalizedMessage());
                }
            });
    }
    ...
}

运行效果如下图所示:

 

2 点击通知

...
NotificationRequest request =
    new NotificationRequest(1001)
    .setContent(content)
    .setIntentAgent(createIntentAgent());
...                         |
                            v
private IntentAgent createIntentAgent() {
    Operation operation = new OperationBuilder()
        .withDeviceId("")
        .withBundleName("com.minwei.clicknotification")
        .withAbilityName(
        "com.minwei.clicknotification.SecondaryAbility")
        .build();
    Intent intent = new Intent();
    intent.setOperation(operation);

    List<Intent> intents = new ArrayList<>();
    intents.add(intent);

    List<Flags> flags = new ArrayList<>();
    flags.add(Flags.ONE_TIME_FLAG);

    IntentAgentInfo info = new IntentAgentInfo(
        200, OperationType.START_ABILITY, flags, intents, null);
    return IntentAgentHelper.getIntentAgent(this, info);
}

例程:ClickNotification

...\ClickNotification\entry\src\main\resources\base\graphic\background_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="100"/>
    <solid ohos:color="#22b14c"/>
</shape>

...\ClickNotification\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:btn"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="30vp"
        ohos:top_padding="10vp"
        ohos:right_padding="30vp"
        ohos:bottom_padding="10vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="发布通知"
        ohos:text_size="28fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\ClickNotification\entry\src\main\resources\base\layout\ability_secondary.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical"
    ohos:background_element="#22b14c">

    <Text
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="大大的惊喜"
        ohos:text_size="40fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\ClickNotification\entry\src\main\java\com\minwei\clicknotification\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(
        HiLog.LOG_APP, 0x00101,
        MainAbilitySlice.class.getCanonicalName());

    @Override
    public void onStart(Intent intent) {
        ...
        findComponentById(ResourceTable.Id_btn)
            .setClickedListener(component -> {
                NotificationNormalContent normal =
                    new NotificationNormalContent()
                    .setTitle("别说我没告诉你")
                    .setText("戳我呀!戳我呀!")
                    .setAdditionalText("戳一下给你大大的惊喜");

                NotificationContent content =
                    new NotificationContent(normal);

                NotificationRequest request =
                    new NotificationRequest(1002)
                    .setContent(content)
                    .setIntentAgent(createIntentAgent());

                try {
                    NotificationHelper.publishNotification(request);
                }
                catch (RemoteException exception) {
                    HiLog.error(label, exception.getLocalizedMessage());
                }
            });
    }
    ...
    private IntentAgent createIntentAgent() {
        Operation operation = new OperationBuilder()
            .withDeviceId("")
            .withBundleName("com.minwei.clicknotification")
            .withAbilityName(
                "com.minwei.clicknotification.SecondaryAbility")
            .build();
        Intent intent = new Intent();
        intent.setOperation(operation);

        List<Intent> intents = new ArrayList<>();
        intents.add(intent);

        List<Flags> flags = new ArrayList<>();
        flags.add(Flags.ONE_TIME_FLAG);

        IntentAgentInfo info = new IntentAgentInfo(
            200, OperationType.START_ABILITY, flags, intents, null);
        return IntentAgentHelper.getIntentAgent(this, info);
    }
}

运行效果如下图所示:

3 通知渠道

在鸿蒙操作系统中,可以利用通知渠道定义通知的类别,以方便用户按类别屏蔽、开放,或设置不同的通知。

例程:NotificationSlot

...\NotificationSlot\entry\src\main\resources\base\graphic\background_button_default.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="100"/>
    <solid ohos:color="#00a2e8"/>
</shape>

...\NotificationSlot\entry\src\main\resources\base\graphic\background_button_high.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="100"/>
    <solid ohos:color="#ff7f27"/>
</shape>

...\NotificationSlot\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:btnDefault"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="30vp"
        ohos:top_padding="10vp"
        ohos:right_padding="30vp"
        ohos:bottom_padding="10vp"
        ohos:background_element="$graphic:background_button_default"
        ohos:text="一般通知"
        ohos:text_size="28fp"
        ohos:text_color="#ffffff"
        />

    <Button
        ohos:id="$+id:btnHigh"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="30vp"
        ohos:top_padding="10vp"
        ohos:right_padding="30vp"
        ohos:bottom_padding="10vp"
        ohos:top_margin="20vp"
        ohos:background_element="$graphic:background_button_high"
        ohos:text="重要通知"
        ohos:text_size="28fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\NotificationSlot\entry\src\main\java\com\minwei\notificationslot\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(
        HiLog.LOG_APP, 0x00101,
        MainAbilitySlice.class.getCanonicalName());

    @Override
    public void onStart(Intent intent) {
        ...
        NotificationSlot slotDefault = new NotificationSlot(
            "slotDefault", "一般通知", NotificationSlot.LEVEL_DEFAULT);
        slotDefault.setDescription("针对一般事件的通知");
        try {
            NotificationHelper.addNotificationSlot(slotDefault);
        }
        catch (RemoteException exception) {
            HiLog.error(label, exception.getLocalizedMessage());
        }

        findComponentById(ResourceTable.Id_btnDefault)
            .setClickedListener(component -> {
                NotificationNormalContent normal =
                    new NotificationNormalContent()
                    .setTitle("一般通知")
                    .setText("挺好,发型不错……")
                    .setAdditionalText("好的发型是成功的一半");

                NotificationContent content =
                    new NotificationContent(normal);

                NotificationRequest request =
                    new NotificationRequest(1003)
                    .setContent(content)
                    .setSlotId("slotDefault");

                try {
                    NotificationHelper.publishNotification(request);
                }
                catch (RemoteException exception) {
                    HiLog.error(label, exception.getLocalizedMessage());
                }
            });

        NotificationSlot slotHigh = new NotificationSlot(
            "slotHigh", "重要通知", NotificationSlot.LEVEL_HIGH);
        slotHigh.setDescription("针对重要事件的通知");
        slotHigh.setEnableVibration(true);
        slotHigh.setLockscreenVisibleness(
            NotificationRequest.VISIBLENESS_TYPE_PUBLIC);
        slotHigh.enableBypassDnd(true);
        slotHigh.setEnableLight(true);
        slotHigh.setLedLightColor(Color.RED.getValue());
        try {
            NotificationHelper.addNotificationSlot(slotHigh);
        }
        catch (RemoteException exception) {
            HiLog.error(label, exception.getLocalizedMessage());
        }

        findComponentById(ResourceTable.Id_btnHigh)
            .setClickedListener(component -> {
                NotificationNormalContent normal =
                    new NotificationNormalContent()
                    .setTitle("重要通知")
                    .setText("注意,老板来了!")
                    .setAdditionalText("上班打游戏是不明智的");

                NotificationContent content =
                    new NotificationContent(normal);

                NotificationRequest request =
                    new NotificationRequest(1004)
                    .setContent(content)
                    .setSlotId("slotHigh");

                try {
                    NotificationHelper.publishNotification(request);
                }
                catch (RemoteException exception) {
                    HiLog.error(label, exception.getLocalizedMessage());
                }
            });
    }
    ...
}

运行效果如下图所示:

4 长文通知

NotificationLongTextContent longText =
    new NotificationLongTextContent()
    .setTitle("逍遥游")
    .setExpandedTitle("逍遥游·庄子")
    .setLongText(...)
    .setAdditionalText("庄子");

NotificationContent content =
    new NotificationContent(longText);
...

例程:LongNotification

...\LongNotification\entry\src\main\resources\base\graphic\background_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="100"/>
    <solid ohos:color="#254061"/>
</shape>

...\LongNotification\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:btn"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="30vp"
        ohos:top_padding="10vp"
        ohos:right_padding="30vp"
        ohos:bottom_padding="10vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="发布通知"
        ohos:text_size="28fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\LongNotification\entry\src\main\java\com\minwei\longnotification\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(
        HiLog.LOG_APP, 0x00101,
        MainAbilitySlice.class.getCanonicalName());

    @Override
    public void onStart(Intent intent) {
        ...
        findComponentById(ResourceTable.Id_btn)
            .setClickedListener(component -> {
                NotificationLongTextContent longText =
                    new NotificationLongTextContent()
                    .setTitle("逍遥游")
                    .setExpandedTitle("逍遥游·庄子")
                    .setLongText("北冥有鱼其名为鲲鲲之大不知其几千里也化而为鸟其名为鹏鹏之背不知其几千里也怒而飞其翼若垂天之云是鸟也海运则将徙于南冥南冥者天池也齐谐者志怪者也谐之言曰鹏之徙于南冥也水击三千里抟扶摇而上者九万里去以六月息者也野马也尘埃也生物之以息相吹也天之苍苍其正色邪其远而无所至极邪其视下也亦若是则已矣且夫水之积也不厚则其负大舟也无力覆杯水于坳堂之上则芥为之舟置杯焉则胶水浅而舟大也风之积也不厚则其负大翼也无力故九万里则风斯在下矣而后乃今培风背负青天而莫之夭阏者而后乃今将图南蜩与学鸠笑之曰我决起而飞抢榆枋而止时则不至而控于地而已矣奚以之九万里而南为适莽苍者三餐而反腹犹果然适百里者宿舂粮适千里者三月聚粮之二虫又何知小知不及大知小年不及大年奚以知其然也朝菌不知晦朔蟪蛄不知春秋此小年也楚之南有冥灵者以五百岁为春五百岁为秋上古有大椿者以八千岁为春八千岁为秋此大年也而彭祖乃今以久特闻众人匹之不亦悲乎")
                    .setAdditionalText("庄子");

                NotificationContent content =
                    new NotificationContent(longText);

                NotificationRequest request =
                    new NotificationRequest(1005)
                    .setContent(content);

                try {
                    NotificationHelper.publishNotification(request);
                }
                catch (RemoteException exception) {
                    HiLog.error(label, exception.getLocalizedMessage());
                }
            });
    }
    ...
}

运行效果如下图所示:

5 多行通知

NotificationMultiLineContent multiLine =
    new NotificationMultiLineContent()
    .setTitle("悯农")
    .setExpandedTitle("悯农·李绅")
    .setText("唐诗一首")
    .addSingleLine("锄禾日当午")
    .addSingleLine("汗滴禾下土")
    .addSingleLine("谁知盘中餐")
    .addSingleLine("粒粒皆辛苦")
    .setAdditionalText("李绅");

NotificationContent content =
    new NotificationContent(multiLine);
...

例程:MultilineNotification

...\MultilineNotification\entry\src\main\resources\base\graphic\background_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="100"/>
    <solid ohos:color="#632523"/>
</shape>

...\MultilineNotification\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:btn"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="30vp"
        ohos:top_padding="10vp"
        ohos:right_padding="30vp"
        ohos:bottom_padding="10vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="发布通知"
        ohos:text_size="28fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\MultilineNotification\entry\src\main\java\com\minwei\multilinenotification\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(
        HiLog.LOG_APP, 0x00101,
        MainAbilitySlice.class.getCanonicalName());

    @Override
    public void onStart(Intent intent) {
        ...
        findComponentById(ResourceTable.Id_btn)
            .setClickedListener(component -> {
                NotificationMultiLineContent multiLine =
                    new NotificationMultiLineContent()
                    .setTitle("悯农")
                    .setExpandedTitle("悯农·李绅")
                    .setText("唐诗一首")
                    .addSingleLine("锄禾日当午")
                    .addSingleLine("汗滴禾下土")
                    .addSingleLine("谁知盘中餐")
                    .addSingleLine("粒粒皆辛苦")
                    .setAdditionalText("李绅");

                NotificationContent content =
                    new NotificationContent(multiLine);

                NotificationRequest request =
                    new NotificationRequest(1006)
                    .setContent(content);

                try {
                    NotificationHelper.publishNotification(request);
                }
                catch (RemoteException exception) {
                    HiLog.error(label, exception.getLocalizedMessage());
                }
            });
    }
    ...
}

运行效果如下图所示:

6 图片通知

NotificationPictureContent picture =
    new NotificationPictureContent()
    .setTitle("小新")
    .setExpandedTitle("野原新之助")
    .setText("我叫野原新之助,今年五岁,不爱吃青椒。")
    .setBriefText("大家叫我小新,我喜欢的内裤图案是动感超人哦!")
    .setBigPicture(getPixelMap(ResourceTable.Media_xiaoxin))
    .setAdditionalText("蜡笔小新");

NotificationContent content =
    new NotificationContent(picture);
...

例程:PictureNotification

...\PictureNotification\entry\src\main\resources\base\media\xiaoxin.png

...\PictureNotification\entry\src\main\resources\base\graphic\background_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="100"/>
    <solid ohos:color="#385723"/>
</shape>

...\PictureNotification\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:btn"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="30vp"
        ohos:top_padding="10vp"
        ohos:right_padding="30vp"
        ohos:bottom_padding="10vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="发布通知"
        ohos:text_size="28fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\PictureNotification\entry\src\main\java\com\minwei\picturenotification\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(
        HiLog.LOG_APP, 0x00101,
        MainAbilitySlice.class.getCanonicalName());

    @Override
    public void onStart(Intent intent) {
        ...
        findComponentById(ResourceTable.Id_btn)
            .setClickedListener(component -> {
                NotificationPictureContent picture =
                    new NotificationPictureContent()
                    .setTitle("小新")
                    .setExpandedTitle("野原新之助")
                    .setText("我叫野原新之助,今年五岁。我不爱吃青椒。")
                    .setBriefText("大家叫我小新,我喜欢的内裤图案是动感超人哦!")
                    .setBigPicture(getPixelMap(ResourceTable.Media_xiaoxin))
                    .setAdditionalText("蜡笔小新");

                NotificationContent content =
                    new NotificationContent(picture);

                NotificationRequest request =
                    new NotificationRequest(1007)
                    .setContent(content);

                try {
                    NotificationHelper.publishNotification(request);
                }
                catch (RemoteException exception) {
                    HiLog.error(label, exception.getLocalizedMessage());
                }
            });
    }
    ...
    private PixelMap getPixelMap(int id) {
        PixelMap map = null;

        ResourceManager manager = getResourceManager();
        try {
            String path = manager.getMediaPath(id);
            RawFileEntry entry = manager.getRawFileEntry(path);
            Resource resource = entry.openRawFile();
            ImageSource source = ImageSource.create(resource, null);
            map = source.createPixelmap(null);
        }
        catch (IOException | NotExistException |
            WrongTypeException exception) {
            HiLog.error(label, exception.getLocalizedMessage());
        }

        return map;
    }
}

运行效果如下图所示:

7 社交通知

MessageUser usr1 = new MessageUser()
    .setName("风间")
    .setPixelMap(getPixelMap(ResourceTable.Media_fengjian));
...

ConversationalMessage msg1 = new ConversationalMessage(
    "我要去上芭蕾课。", Time.getCurrentTime(), usr1);
...

NotificationConversationalContent conversational =
    new NotificationConversationalContent(user)
    .setConversationTitle("向日葵小班")
    .addConversationalMessage(msg1)
    ...;

NotificationContent content =
    new NotificationContent(conversational);
...

例程:ConversationalNotification

...\ConversationalNotification\entry\src\main\resources\base\media\xiaoxin.png

...\ConversationalNotification\entry\src\main\resources\base\media\fengjian.png

...\ConversationalNotification\entry\src\main\resources\base\media\zhengnan.png

...\ConversationalNotification\entry\src\main\resources\base\media\nini.png

...\ConversationalNotification\entry\src\main\resources\base\media\adai.png

...\ConversationalNotification\entry\src\main\resources\base\graphic\background_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="100"/>
    <solid ohos:color="#ff0000"/>
</shape>

...\ConversationalNotification\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:btn"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="30vp"
        ohos:top_padding="10vp"
        ohos:right_padding="30vp"
        ohos:bottom_padding="10vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="发布通知"
        ohos:text_size="28fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\ConversationalNotification\entry\src\main\java\com\minwei\conversationalnotification\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(
        HiLog.LOG_APP, 0x00101,
        MainAbilitySlice.class.getCanonicalName());

    @Override
    public void onStart(Intent intent) {
        ...
        findComponentById(ResourceTable.Id_btn)
            .setClickedListener(component -> {
                MessageUser user = new MessageUser()
                    .setName("小新")
                    .setPixelMap(getPixelMap(ResourceTable.Media_xiaoxin));
                MessageUser usr1 = new MessageUser()
                    .setName("风间")
                    .setPixelMap(getPixelMap(ResourceTable.Media_fengjian));
                MessageUser usr2 = new MessageUser()
                    .setName("正男")
                    .setPixelMap(getPixelMap(ResourceTable.Media_zhengnan));
                MessageUser usr3 = new MessageUser()
                    .setName("妮妮")
                    .setPixelMap(getPixelMap(ResourceTable.Media_nini));
                MessageUser usr4 = new MessageUser()
                    .setName("阿呆")
                    .setPixelMap(getPixelMap(ResourceTable.Media_adai));

                ConversationalMessage msg1 = new ConversationalMessage(
                    "我要去上芭蕾课。", Time.getCurrentTime(), usr1);
                ConversationalMessage msg2 = new ConversationalMessage(
                    "好可怕,快逃呀!", Time.getCurrentTime(), usr2);
                ConversationalMessage msg3 = new ConversationalMessage(
                    "我们玩家家酒吧?", Time.getCurrentTime(), usr3);
                ConversationalMessage msg4 = new ConversationalMessage(
                    "。。。。。。。。", Time.getCurrentTime(), usr4);

                NotificationConversationalContent conversational =
                    new NotificationConversationalContent(user)
                    .setConversationTitle("向日葵小班")
                    .addConversationalMessage(msg1)
                    .addConversationalMessage(msg2)
                    .addConversationalMessage(msg3)
                    .addConversationalMessage(msg4);

                NotificationContent content =
                    new NotificationContent(conversational);

                NotificationRequest request =
                    new NotificationRequest(1008)
                    .setContent(content);

                try {
                    NotificationHelper.publishNotification(request);
                }
                catch (RemoteException exception) {
                    HiLog.error(label, exception.getLocalizedMessage());
                }
            });
    }
    ...
    private PixelMap getPixelMap(int id) {
        PixelMap map = null;

        ResourceManager manager = getResourceManager();
        try {
            String path = manager.getMediaPath(id);
            RawFileEntry entry = manager.getRawFileEntry(path);
            Resource resource = entry.openRawFile();
            ImageSource source = ImageSource.create(resource, null);
            map = source.createPixelmap(null);
        }
        catch (IOException | NotExistException |
            WrongTypeException exception) {
            HiLog.error(label, exception.getLocalizedMessage());
        }

        return map;
    }
}

运行效果如下图所示:

8 媒体通知

NotificationMediaContent media =
    new NotificationMediaContent()
    .setTitle("北琦玉布鲁斯")
    .setText("蜡笔小新原声带")
    .setAdditionalText("藤原启治")
    .setShownActions(new int[]{0});

NotificationContent content =
    new NotificationContent(media);

NotificationActionButton btnPlay =
    new NotificationActionButton.Builder(
    getPixelMap(ResourceTable.Media_play), "播放", null)
    .build();
...

NotificationRequest request =
    new NotificationRequest(1009)
    .setContent(content)
    .addActionButton(btnPlay)
    ...;

例程:MediaNotification

...\MediaNotification\entry\src\main\resources\base\media\play.png

...\MediaNotification\entry\src\main\resources\base\media\like.png

...\MediaNotification\entry\src\main\resources\base\media\favorite.png

...\MediaNotification\entry\src\main\resources\base\graphic\background_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="100"/>
    <solid ohos:color="#804080"/>
</shape>

...\MediaNotification\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:btn"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="30vp"
        ohos:top_padding="10vp"
        ohos:right_padding="30vp"
        ohos:bottom_padding="10vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="发布通知"
        ohos:text_size="28fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\MediaNotification\entry\src\main\java\com\minwei\medianotification\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel label = new HiLogLabel(
        HiLog.LOG_APP, 0x00101,
        MainAbilitySlice.class.getCanonicalName());

    @Override
    public void onStart(Intent intent) {
        ...
        findComponentById(ResourceTable.Id_btn)
            .setClickedListener(component -> {
                NotificationMediaContent media =
                    new NotificationMediaContent()
                    .setTitle("北琦玉布鲁斯")
                    .setText("蜡笔小新原声带")
                    .setAdditionalText("藤原启治")
                    .setShownActions(new int[]{0});

                NotificationContent content =
                    new NotificationContent(media);

                NotificationActionButton btnPlay =
                    new NotificationActionButton.Builder(
                    getPixelMap(ResourceTable.Media_play), "播放", null)
                    .build();
                NotificationActionButton btnLike =
                    new NotificationActionButton.Builder(
                    getPixelMap(ResourceTable.Media_like), "喜欢", null)
                    .build();
                NotificationActionButton btnFavorite =
                    new NotificationActionButton.Builder(
                    getPixelMap(ResourceTable.Media_favorite), "收藏", null)
                    .build();

                NotificationRequest request =
                    new NotificationRequest(1009)
                    .setContent(content)
                    .addActionButton(btnPlay)
                    .addActionButton(btnLike)
                    .addActionButton(btnFavorite);

                try {
                    NotificationHelper.publishNotification(request);
                }
                catch (RemoteException exception) {
                    HiLog.error(label, exception.getLocalizedMessage());
                }
            });
    }
    ...
    private PixelMap getPixelMap(int id) {
        PixelMap map = null;

        ResourceManager manager = getResourceManager();
        try {
            String path = manager.getMediaPath(id);
            RawFileEntry entry = manager.getRawFileEntry(path);
            Resource resource = entry.openRawFile();
            ImageSource source = ImageSource.create(resource, null);
            map = source.createPixelmap(null);
        }
        catch (IOException | NotExistException |
            WrongTypeException exception) {
            HiLog.error(label, exception.getLocalizedMessage());
        }

        return map;
    }
}

运行效果如下图所示:

更多精彩,敬请期待……


达内集团C++教学部 2021年9月25日