HarmonyOS学习路之开发篇——公共事件与通知(一)

简介: HarmonyOS通过CES(Common Event Service,公共事件服务)为应用程序提供订阅、发布、退订公共事件的能力,通过ANS(Advanced Notification Service,即通知增强服务)系统服务来为应用程序提供发布通知的能力。

公共事件与通知开发概述

HarmonyOS通过CES(Common Event Service,公共事件服务)为应用程序提供订阅、发布、退订公共事件的能力,通过ANS(Advanced Notification Service,即通知增强服务)系统服务来为应用程序提供发布通知的能力。


公共事件可分为系统公共事件和自定义公共事件。

系统公共事件:系统将收集到的事件信息,根据系统策略发送给订阅该事件的用户程序。例如:用户可感知亮灭屏事件,系统关键服务发布的系统事件(例如:USB插拔,网络连接,系统升级等)。

自定义公共事件:应用自定义一些公共事件用来处理业务逻辑。

通知提供应用的即时消息或通信消息,用户可以直接删除或点击通知触发进一步的操作。

IntentAgent封装了一个指定行为的Intent,可以通过IntentAgent启动Ability和发布公共事件。

应用如果需要接收公共事件,需要订阅相应的事件。


公共事件开发

接口说明

公共事件相关基础类包含CommonEventData、CommonEventPublishInfo、CommonEventSubscribeInfo、CommonEventSubscriber和CommonEventManager。基础类之间的关系如下图所示:


图1 公共事件基础类关系图

CommonEventData

CommonEventData封装公共事件相关信息。用于在发布、分发和接收时处理数据。在构造CommonEventData对象时,相关参数需要注意以下事项:


code为有序公共事件的结果码,data为有序公共事件的结果数据,仅用于有序公共事件场景。

intent不允许为空,否则发布公共事件失败。

CommonEventPublishInfo

CommonEventPublishInfo封装公共事件发布相关属性、限制等信息,包括公共事件类型(有序或粘性)、接收者权限等。


有序公共事件:主要场景是多个订阅者有依赖关系或者对处理顺序有要求,例如:高优先级订阅者可修改公共事件内容或处理结果,包括终止公共事件处理;或者低优先级订阅者依赖高优先级的处理结果等。

粘性公共事件:指公共事件的订阅动作是在公共事件发布之后进行,订阅者也能收到的公共事件类型。主要场景是由公共事件服务记录某些系统状态,如蓝牙、WLAN、充电等事件和状态。

CommonEventSubscribeInfo

CommonEventSubscribeInfo封装公共事件订阅相关信息,比如优先级、线程模式、事件范围等。

线程模式(ThreadMode):设置订阅者的回调方法执行的线程模式。ThreadMode有HANDLER,POST,ASYNC,

BACKGROUND四种模式,目前只支持HANDLER模式。

HANDLER:在Ability的主线程上执行。

POST:在事件分发线程执行。

ASYNC:在一个新创建的异步线程执行。

BACKGROUND:在后台线程执行。

CommonEventSubscriber

CommonEventSubscriber封装公共事件订阅者及相关参数。


CommonEventSubscriber.AsyncCommonEventResult类处理有序公共事件异步执行。

目前只能通过调用CommonEventManagersubscribeCommonEvent()进行订阅。

CommonEventManager

CommonEventManager是为应用提供订阅、退订和发布公共事件的静态接口类。


Demo实例程序

效果演示



HarmonyOS 公共事件Demo演示


发布公共事件

四种公共事件:无序的公共事件、带权限的公共事件、有序的公共事件、粘性的公共事件。

发布无序的公共事件:构造CommonEventData对象,设置Intent,通过构造operation对象把需要发布的公共事件信息传入intent对象。然后调用 CommonEventManager.publishCommonEvent(CommonEventData) 接口发布公共事件。


    public void publishDisorderedEvent() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withAction(event).build();
        intent.setOperation(operation);
        CommonEventData eventData = new CommonEventData(intent);
        try {
            CommonEventManager.publishCommonEvent(eventData);
            showTips(context, "Publish succeeded");
        } catch (RemoteException e) {
            HiLog.error(LABEL_LOG, "%{public}s", "publishDisorderedEvent remoteException.");
        }
    }

发布携带权限的公共事件:构造CommonEventPublishInfo对象,设置订阅者的权限。


在config.json中申请所需的权限

 

    "reqPermissions": [
      {
        "name": "ohos.samples.permission",
        "reason": "get right",
        "usedScene": {
          "ability": [
            ".MainAbilitySlice"
          ],
          "when": "inuse"
        }
      }
    ]

发布带权限的公共事件示例代码如下

public void publishPermissionEvent() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withAction(event).build();
        intent.setOperation(operation);
        CommonEventData eventData = new CommonEventData(intent);
        CommonEventPublishInfo publishInfo = new CommonEventPublishInfo();
        String[] permissions = {"ohos.sample.permission"};
        publishInfo.setSubscriberPermissions(permissions);
        try {
            CommonEventManager.publishCommonEvent(eventData, publishInfo);
            showTips(context, "Publish succeeded");
        } catch (RemoteException e) {
            HiLog.error(LABEL_LOG, "%{public}s", "publishPermissionEvent remoteException.");
        }
    }

发布有序的公共事件:构造CommonEventPublishInfo对象,通过setOrdered(true)指定公共事件属性为有序公共事件,也可以指定一个最后的公共事件接收者。


public void publishOrderlyEvent() {
        MatchingSkills skills = new MatchingSkills();
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withAction(event).build();
        intent.setOperation(operation);
        CommonEventData eventData = new CommonEventData(intent);
        skills.addEvent(event);
        CommonEventPublishInfo publishInfo = new CommonEventPublishInfo();
        publishInfo.setOrdered(true);
        try {
            CommonEventManager.publishCommonEvent(eventData, publishInfo);
            showTips(context, "Publish succeeded");
        } catch (RemoteException e) {
            HiLog.error(LABEL_LOG, "%{public}s", "publishOrderlyEvent remoteException.");
        }
    }

发布粘性公共事件:构造CommonEventPublishInfo对象,通过setSticky(true)指定公共事件属性为粘性公共事件。


发布者首先在config.json中申请发布粘性公共事件所需的权限

    "reqPermissions": [
      {
        "name": "ohos.permission.COMMONEVENT_STICKY",
        "reason": "get right",
        "usedScene": {
          "ability": [
            ".MainAbilitySlice"
          ],
          "when": "inuse"
        }
      }
    ]

发布粘性公共事件

public void publishStickyEvent() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withAction(event).build();
        intent.setOperation(operation);
        CommonEventData eventData = new CommonEventData(intent);
        CommonEventPublishInfo publishInfo = new CommonEventPublishInfo();
        publishInfo.setSticky(true);
        try {
            CommonEventManager.publishCommonEvent(eventData, publishInfo);
            showTips(context, "Publish succeeded");
        } catch (RemoteException e) {
            HiLog.error(LABEL_LOG, "%{public}s", "publishStickyEvent remoteException.");
        }
    }

订阅公共事件

1、创建CommonEventSubscriber派生类,在onReceiveEvent()回调函数中处理公共事件。


class TestCommonEventSubscriber extends CommonEventSubscriber {
        TestCommonEventSubscriber(CommonEventSubscribeInfo info) {
            super(info);
        }
        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
        }
    }

2、构造MyCommonEventSubscriber对象,调用CommonEventManager.subscribeCommonEvent()接口进行订阅。


String event = "测试";
MatchingSkills matchingSkills = new MatchingSkills();
matchingSkills.addEvent(event); // 自定义事件
CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
TestCommonEventSubscribersubscriber = new TestCommonEventSubscriber(subscribeInfo);
try {
    CommonEventManager.subscribeCommonEvent(subscriber); 
} catch (RemoteException e) {
    HiLog.error(LABEL, "Exception occurred during subscribeCommonEvent invocation."); 
}

如果订阅的公共事件是有序的,可以调用setPriority()指定优先级。

String event = "测试";
MatchingSkills matchingSkills = new MatchingSkills();
matchingSkills.addEvent(event); // 自定义事件
CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
subscribeInfo.setPriority(100); // 设置优先级,优先级取值范围[-1000,1000],值默认为0。
TestCommonEventSubscribersubscriber subscriber = new TestCommonEventSubscribersubscriber (subscribeInfo);
try {
     CommonEventManager.subscribeCommonEvent(subscriber); 
} catch (RemoteException e) {
     HiLog.error(LABEL, "Exception occurred during subscribeCommonEvent invocation."); 
}

3、针对在onReceiveEvent中不能执行耗时操作的限制,可以使用CommonEventSubscriber的goAsyncCommonEvent()来实现异步操作,函数返回后仍保持该公共事件活跃,且执行完成后必须调用AsyncCommonEventResult .finishCommonEvent()来结束。



EventRunner runner = EventRunner.create(); // EventRunner创建新线程,将耗时的操作放到新的线程上执行
MyEventHandler myHandler = new MyEventHandler(runner); // MyEventHandler为EventHandler的派生类,在不同线程间分发和处理事件和Runnable任务
@Override
public void onReceiveEvent(CommonEventData commonEventData){
    final AsyncCommonEventResult result = goAsyncCommonEvent();
    Runnable task = new Runnable() {
        @Override
        public void run() {
            ........         // 待执行的操作,由开发者定义
            result.finishCommonEvent(); // 调用finish结束异步操作
        }
    };
    myHandler.postTask(task);
} 


退订公共事件

在Ability的onStop()中调用CommonEventManager.unsubscribeCommonEvent()方法来退订公共事件。调用后,之前订阅的所有公共事件均被退订。


public void unSubscribeEvent() {
        if (subscriber == null) {
            HiLog.info(LABEL_LOG, "%{public}s", "CommonEvent onUnsubscribe commonEventSubscriber is null");
            return;
        }
        try {
            CommonEventManager.unsubscribeCommonEvent(subscriber);
            showTips(context, "UnSubscribe succeeded");
        } catch (RemoteException e) {
            HiLog.error(LABEL_LOG, "%{public}s", "unsubscribeEvent remoteException.");
        }
        destroy();
    }
    private void destroy() {
        subscriber = null;
        eventListener = null;
        unSubscribe = true;
    }
相关文章
|
2月前
|
缓存 API 数据安全/隐私保护
自学记录:学习HarmonyOS Location Kit构建智能定位服务
作为一名对新技术充满好奇心的开发者,我选择了HarmonyOS Next 5.0.1(API 13)作为挑战对象,深入研究其强大的定位服务API——Location Kit。从权限管理、获取当前位置、逆地理编码到地理围栏,最终成功开发了一款智能定位应用。本文将结合代码和开发过程,详细讲解如何实现这些功能,并分享遇到的挫折与兴奋时刻。希望通过我的经验,能帮助其他开发者快速上手HarmonyOS开发,共同探索更多可能性。
133 5
|
1月前
|
存储 人工智能 JavaScript
Harmony OS开发-ArkTS语言速成二
本文介绍了ArkTS基础语法,包括三种基本数据类型(string、number、boolean)和变量的使用。重点讲解了let、const和var的区别,涵盖作用域、变量提升、重新赋值及初始化等方面。期待与你共同进步!
103 47
Harmony OS开发-ArkTS语言速成二
|
2月前
|
前端开发 API 数据库
鸿蒙开发:异步并发操作
在结合async/await进行使用的时候,有一点需要注意,await关键字必须结合async,这两个是搭配使用的,缺一不可,同步风格在使用的时候,如何获取到错误呢,毕竟没有catch方法,其实,我们可以自己创建try/catch来捕获异常。
105 3
鸿蒙开发:异步并发操作
|
2月前
|
API
鸿蒙开发:实现popup弹窗
目前提供了两种方式实现popup弹窗,主推系统实现的方式,几乎能满足我们常见的所有场景,当然了,文章毕竟有限,尽量还是以官网为主。
106 2
鸿蒙开发:实现popup弹窗
|
1月前
|
存储 JSON 区块链
【HarmonyOS NEXT开发——ArkTS语言】购物商城的实现【合集】
HarmonyOS应用开发使用@Component装饰器将Home结构体标记为一个组件,意味着它可以在界面构建中被当作一个独立的UI单元来使用,并且按照其内部定义的build方法来渲染具体的界面内容。txt:string定义了一个名为Data的接口,用于规范表示产品数据的结构。src:类型为,推测是用于引用资源(可能是图片资源等)的一种特定类型,用于指定产品对应的图片资源。txt:字符串类型,用于存放产品的文字描述,比如产品名称等相关信息。price:数值类型,用于表示产品的价格信息。
56 5
|
1月前
|
开发工具 开发者 容器
【HarmonyOS NEXT开发——ArkTS语言】欢迎界面(启动加载页)的实现【合集】
从ArkTS代码架构层面而言,@Entry指明入口、@Component助力复用、@Preview便于预览,只是初窥门径,为开发流程带来些许便利。尤其动画回调与Blank组件,细节粗糙,后续定当潜心钻研,力求精进。”,字体颜色为白色,字体大小等设置与之前类似,不过动画配置有所不同,时长为。,不过这里没有看到额外的动画效果添加到这个特定的图片元素上(与前面带动画的元素对比而言)。这是一个显示文本的视图,文本内容为“奇怪的知识”,设置了字体颜色为灰色(的结构体,它代表了整个界面组件的逻辑和视图结构。
51 1
|
2月前
|
开发框架 物联网 API
HarmonyOS开发:串行通信开发详解
在电子设备和智能系统的设计中,数据通信是连接各个组件和设备的核心,串行通信作为一种基础且广泛应用的数据传输方式,因其简单、高效和成本效益高而被广泛采用。HarmonyOS作为一个全场景智能终端操作系统,不仅支持多种设备和场景,还提供了强大的开发框架和API,使得开发者能够轻松实现串行通信功能。随着技术的不断进步,串行通信技术也在不断发展。在HarmonyOS中,串行通信的开发不仅涉及到基本的数据发送和接收,还包括设备配置、错误处理和性能优化等多个方面。那么本文就来深入探讨在HarmonyOS中如何开发串行通信应用,包括串行通信的基础知识、HarmonyOS提供的API、开发步骤和实际代码示例
58 2
|
2月前
鸿蒙语言开发 几十套鸿蒙ArkTs app毕业设计及课程作业
鸿蒙语言开发 几十套鸿蒙ArkTs app毕业设计及课程作业
45 1
|
容器
HarmonyOS的组件、布局和事件三者的关系
HarmonyOS的组件、布局和事件三者的关系
178 0
HarmonyOS的组件、布局和事件三者的关系
|
2月前
|
API 索引
鸿蒙开发:实现一个超简单的网格拖拽
实现拖拽,最重要的三个方法就是,打开编辑状态editMode,实现onItemDragStart和onItemDrop,设置拖拽移动动画和交换数据,如果想到开启补位动画,还需要实现supportAnimation方法。
85 13
鸿蒙开发:实现一个超简单的网格拖拽

热门文章

最新文章