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

公共事件与通知开发概述

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实例程序

效果演示
https://live.csdn.net/v/167732

发布公共事件

四种公共事件:无序的公共事件、带权限的公共事件、有序的公共事件、粘性的公共事件。
发布无序的公共事件:构造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;
    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,295评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,928评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,682评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,209评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,237评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,965评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,586评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,487评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,016评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,136评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,271评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,948评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,619评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,139评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,252评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,598评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,267评论 2 358

推荐阅读更多精彩内容