HarmonyOS鸿蒙Next应用开发-公共事件处理

HarmonyOS鸿蒙Next应用开发-公共事件处理 在开发过程中service想要控制多个ability时,可以考虑使用公共事件处理。

发布无序的公共事件:

//发布公共事件 同步修改卡片与页面 public void subscribeEvent(String id,String status) { try { Intent intent = new Intent(); Operation operation = new Intent.OperationBuilder() .withAction(“play”) .build(); intent.setOperation(operation); intent.setParam(“id”,id); intent.setParam(“status”,status); CommonEventData eventData = new CommonEventData(intent); CommonEventManager.publishCommonEvent(eventData); HiLog.info(TAG, “Publish succeeded”); } catch (RemoteException e) { HiLog.error(TAG, “Exception occurred during publishCommonEvent invocation.”); } }


订阅该公共事件:


class MyCommonEventSubscriber extends CommonEventSubscriber {
    MyCommonEventSubscriber(CommonEventSubscribeInfo info) {
        super(info);
    }

    @Override
    public void onReceiveEvent(CommonEventData commonEventData) {
        HiLog.info(TAG,"订阅Seccess");
        id= Integer.parseInt(commonEventData.getIntent().getStringParam("id"));
        status=commonEventData.getIntent().getStringParam("status");
        HiLog.info(TAG,"订阅数据状态="+status);
        HiLog.info(TAG,"订阅数据歌曲id="+id);
    }
}

本文根据官方文档学习体验整理


更多关于HarmonyOS鸿蒙Next应用开发-公共事件处理的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next应用开发-公共事件处理的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next应用开发中,公共事件处理是核心功能之一。开发者可以通过订阅系统或应用内的事件,实现跨应用或跨设备的数据交互。使用CommonEventManager类,可以注册和接收公共事件,处理如网络状态变化、设备连接等系统事件。通过定义自定义事件,还能实现应用间的通信。确保在config.json中声明所需权限,并在代码中处理事件回调,以提升应用的响应性和用户体验。

回到顶部