poweredbyHarmonyOS基础技术更多信息请访问:Harmonyos技术社区https://harmonyos.51cto.comEventService,公共事件服务)为应用提供订阅、发布、并取消订阅公共事件。公共事件可以分为系统公共事件和自定义公共事件。系统公共事件:系统根据系统策略将收集到的事件信息发送给订阅该事件的用户程序。公共事件包括:终端设备用户可感知的开关机屏幕事件、关键系统服务发布的系统事件(如USB插拔、网络连接、系统升级)等。自定义公共事件:应用自定义一些公共事件处理业务逻辑。场景介绍每个应用都可以订阅自己感兴趣的公共事件,订阅成功并发布公共事件后,系统会将其发送给应用。这些公共事件可以来自系统、其他应用程序和应用程序本身。HarmonyOS提供了一套完整的API来支持用户订阅、发布和接收公共事件。发布公共事件需要借助CommonEventData对象,接收公共事件需要继承CommonEventSubscriber类并实现onReceiveEvent回调函数。开发者可以发布四种公共事件:无序公共事件、授权公共事件、有序公共事件和粘性公共事件。这篇文章的重点是无序的公共事件。其他类型的事件可以参考华为官方开发文档进行学习。指南1.发布公共事件:自定义字符串类型的try{Intentintent=newIntent();Operationoperation=newIntent.OperationBuilder().withAction(“my.action”)//action.build();intent.setOperation(操作);intent.setParam("result","commonEventData");intent.setParam("isCommonEvent",true);CommonEventDataeventData=newCommonEventData(intent);CommonEventManager.publishCommonEvent(eventData);LogUtils.info(TAG,"PublishCommonEventSUCCESS");}catch(RemoteExceptione){LogUtils.error(TAG,"ExceptionoccurredduringpublishCommonEventinvocation.");}2.订阅公共事件1)创建一个CommonEventSubscriber派生类,在onReceiveEvent()中处理公共事件回调函数。privateclassMyCommonEventSubscriberextendsCommonEventSubscriber{MyCommonEventSubscriber(CommonEventSubscribeInfoinfo){super(info);}@OverridepublicvoidonReceiveEvent(CommonEventDatacommonEventData){}2)构造一个MyCommonEventSubscriber对象并调用CommonEventManager.Esubscribe(CommonEventManager.Esubscribe)接口。MatchingSkillsmatchingSkills=newMatchingSkills();//添加自定义的ationmatchingSkills.addEvent(ACTION);matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_BOOT_COMPLETED);//开机完成事件matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_CHARGING);//正在充电事件CommonEventSubscribeInfosubscribeInfo=newCommonEventSubscribeInfo(matchingSkills);subscriber=newMyCommonEventSubscriber(subscribeInfo);try{CommonEventManager.subscribeCommonEvent(subscriber);LogUtils.info(TAG,"SubscribeCommonEventSUCCESS");}catch(RemoteExceptione){LogUtils.error(TAG,"CommonEventsoccurred}3)对于onReceiveEvent不能进行耗时操作的限制,可以使用CommonEventSubscriber的goAsyncCommonEvent()实现异步操作,函数返回后,common事件仍然是活跃的,执行完必须调用。//EventRunner创建一个新线程,并在新线程上执行耗时操作eventRunner);privateclassMyCommonEventSubscriberextendsCommonEventSubscriber{MyCommonEventSubscriber(CommonEventSubscribeInfoinfo){super(info);}@OverridepublicvoidonReceiveEvent(CommonEventDatacommonEventData){//以下为如果有耗时操作时,执行的代码finalAsyncCommonEventResultresult=goAsyncCommonEvent();Runnablerunnable=newRunnable(){@Overridepublicvoidrun(){//要执行的操作,由开发者定义myEventHandle.sendEvent(100);result.finishCommonEvent();//调用finish结束异步操作}};myEventHandle.postTask(runnable);}}privateclassMyEventHandleextendsEventHandler{publicMyEventHandle(EventRunnerrunner)throwsIllegalArgumentException{super(runner);}@OverrideprotectedvoidprocessEvent(InnerEventevent){super.processEvent(event);//处理事件,开发者写的intevnetID=event.eventId;LogUtils.info(TAG,"evnetID:"+evnetID);}}3.退订普通事件://在Ability的onStop()中调用CommonEventManager.unsubscribeCommonEvent()方法取消订阅普通事件后,之前订阅的所有普通事件都会被取消订阅。@OverrideprotectedvoidonStop(){super.onStop();try{CommonEventManager.unsubscribeCommonEvent(subscriber);LogUtils.info(TAG,"unsubscribeCommonEventsuccess.");}catch(RemoteExceptione){LogUtils.error(TAG,"Exceptionoccurredduringonsubscribensubscribe";}}实现效果1、启动APP时,如下图:2、先点击“订阅公共事件”,再点击“发布无序公共事件”。打印的log:09-0210:31:07.69310390-10390/com.zel.commoneventdemoI00000/LogUtil:MainAbilitySlice:SubscribeCommonEventSUCCESS09-0210:31:09.79510390-10390/com.zel.commoneventdemoI00000/LogUtil:MainAbilitySlice:PublishCommonEventSUCCESS09-0210:31:09.79810390-10390/com.zel.commoneventdemoI00000/LogUtil:MainAbilitySlice:action:action.send.message/result:commonEventData/isCommonEvent:true09-0210:31:09.79910390-12455/com.zel.commoneventdemoI0000e:ManetAbility:in/LogUtil100附上源码1.MainAbilitySlicepublicclassMainAbilitySliceextendsAbilitySliceimplementsClickedListener{privateStringTAG="MainAbilitySlice";privateMyCommonEventSubscribersubscriber;privatestaticfinalStringACTION="action.send.message";@OverridepublicvoidonStart(Intentintent){super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);ButtonbtPublisher=(Button)findComponentById(ResourceTable.Id_btPublisher);ButtonbtSubscriber=(Button)findComponentById(资源ceTable.Id_btSubscriber);btPublisher.setClickedListener(this);btSubscriber.setClickedListener(this);}@OverridepublicvoidonActive(){super.onActive();}@OverridepublicvoidonForeground(Intentintent){super.onForeground(intent);}@OverridepublicvoidonClick(组件组件){switch(component.getId()){caseResourceTable.Id_btPublisher:try{Intentintent=newIntent();Operationoperation=newIntent.OperationBuilder().withAction(ACTION).build();intent.setOperation(operation);intent.setParam("result","commonEventData");intent.setParam("isCommonEvent",true);CommonEventDataeventData=newCommonEventData(intent);CommonEventManager.publishCommonEvent(eventData);LogUtils.info(TAG,"PublishCommonEventSUCCESS");}catch(RemoteExceptione){LogUtils.error(TAG,"ExceptionoccurredduringpublishCommonEventinvocation.");}break;caseResourceTable.Id_btSubscriber:MatchingSkillsmatchingSkills=newMatchingSkills();//添加自定义的ationmatchingSkills.addEvent(ACTION);//自定义事件matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_BOOT_COMPLETED);//开机完成事件matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_CHARGING);//正在充电事件CommonEventSubscribeInfosubscribeInfo=newCommonEventSubscribeInfo(matchingSkills);subscriber=newMyCommonEventSubscriber(subscribeInfo);try{CommonEventManager.subscribeCommonEvent(subscriber);LogUtils.info(TAG,"SubscribeCommonEventSUCCESS");}catch(RemoteExceptione){LogUtils.error(TAG,"ExceptionoccurredduringsubscribeCommonEventinvocation.");}/break;}}/EventRunner创建一个新线程,并在新线程上执行耗时操作eventRunner);privateclassMyCommonEventSubscriberextendsCommonEventSubscriber{MyCommonEventSubscriber(CommonEventSubscribeInfoinfo){super(info);}/***针对onReceiveEvent中不能进行耗时操作的限制,可以使用CommonEventSubscriber的goAsyncCommonEvent()实现异步操作,*函数返回后,普通事件仍然活跃,执行完成后,必须调用AsyncCommonEventResult.finishCommonEvent()结束*@paramcommonEventData*/@OverridepublicvoidonReceiveEvent(CommonEventDatacommonEventData){//非执行耗时操作,下面代码可以Intentintent=commonEventData.getIntent();Stringaction=intent.getAction();switch(action){//自定义事件caseACTION:Stringresult=intent.getStringParam("result");booleanisCommonEventData=intent.getBooleanParam("isCommonEvent",false);LogUtils.info(TAG,"action:"+action+"/result:"+result+"/isCommonEvent:"+isCommonEventData);break;//开机完成事件caseCommonEventSupport.COMMON_EVENT_BOOT_COMPLETED:LogUtils.info(TAG,"action:"+action);break;//充电事件caseCommonEventSupport.COMMON_EVENT_CHARGING:LogUtils.info(TAG,"action:"+action);break;}//下面是如果有耗时操作要执行的代码.sendEvent(100);result.finishCommonEvent();//调用finish结束异步操作}};myEventHandle.postTask(runnable);}}privateclassMyEventHandleextendsEventHandler{publicMyEventHandle(EventRunnerrunner)throwsIllegalArgumentException{super(runner);}@OverrideprotectedvoidprocessEvent(InnerEventevent){super.processEvent(event);//处理事件,由开发者编写intevnetID=event.event.event.d(event.event.d;LogUTA:"+evnetID);}}@OverrideprotectedvoidonStop(){super.onStop();try{CommonEventManager.unsubscribeCommonEvent(subscriber);LogUtils.info(TAG,"unsubscribeCommonEventsuccess.");}catch(RemoteExceptione){LogUtils.error(TAG,"ExceptionoccurredduringunsubscribeCommonEventinvocation.");}}}2.LogUtilspublicclassLogUtils{privatestaticfinalStringTAG_LOG="LogUtil";privatestaticfinalHiLogLabelLABEL_LOG=newHiLogLabel(0,0,LogUtils.TAG_LOG);privatestaticfinalStringLOG_FORMAT="%{public}s:%{public}s";privateLogUtils(){}/***Printdebuglog**@paramtaglogtag*@parammsglogmessage*/publicstaticvoiddebug(Stringtag,Stringmsg){HiLog.debug(LABEL_LOG,LOG_FORMAT,tag,msg);}/***Printinfolog**@paramtaglogtag*@paramsglogmessage*/publicstaticvoidinfo(Stringtag,Stringmsg){HiLog.info(LABEL_LOG,LOG_FORMAT,tag,msg);}/***Printwarnlog**@paramtaglogtag*@parammsglogmessage*/publicstaticvoidwarn(Stringtag,Stringmsg){HiLog.warn(LABEL_LOG,LOG_FORMAT,tag,msg);}/***Printererrorlog**@paramtaglogtag*@parammsglogmessage*/publicstaticvoiderror(Stringtag,Stringmsg){HiLog.error(LABEL_LOG,LOG_FORMAT,tag,msg);}}3。xml发布文件:
