【鸿蒙开发】接收通知

ZJKJTL ZJKJTL 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

 在开发过程中我我们可能需要接收一些通知,例如网络的改变,蓝牙的连接,短信接收等等。有助于我们为用户提供更好的体验。

首先我们需要创建通知的订阅者,需要继承CommonEventSubscriber类并实现其抽象方法。

public class MyCommonEventSubscriber extends CommonEventSubscriber {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "MyCommonEventSubscriber");

    public MyCommonEventSubscriber(CommonEventSubscribeInfo subscribeInfo) {
        super(subscribeInfo);
    }

    @Override
    public void onReceiveEvent(CommonEventData commonEventData) {
        // 当应用程序收到新的公共事件时回调
        Intent intent = commonEventData.getIntent();

        // 判断动作类型
        switch (intent.getAction()){
            case CommonEventSupport.COMMON_EVENT_CONFIGURATION_CHANGED:
                HiLog.info(LABEL_LOG,"屏幕旋转");
                break;

            case CommonEventSupport.COMMON_EVENT_SCREEN_ON:
                HiLog.info(LABEL_LOG,"亮屏");
                break;

            default:
                break;
        }
    }
}

然后需要在Ability中设置我们需要订阅哪些通知。

MatchingSkills matchingSkills = new MatchingSkills();
matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_SCREEN_ON); // 亮屏事件
matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_CONFIGURATION_CHANGED); // 屏幕旋转事件
CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
MyCommonEventSubscriber subscriber = new MyCommonEventSubscriber(subscribeInfo);
try {
    CommonEventManager.subscribeCommonEvent(subscriber);
} catch (RemoteException e) {
    e.printStackTrace();
}

启动对应的Ability就可以接收通知了。具体支持哪些通知我们可以看看CommonEventSupport类 

...全文
评论 1
收藏 已收藏
分享
返回顶部