【鸿蒙应用开发系列】- 事件订阅者CommonEventSubscriber使用

在Android开发中,有一个Android四大组件之一的BroadcastReceiver, 也就是我们常说的广播接收器,可用于消息的订阅接收。

那在鸿蒙开发中,有没有提供相应的事件通知机制呢? 答案是有的,那就是我们本文要讲的CommonEventSubscriber,顾名思义,这是一个常用事件订阅者,可用于事件(消息)的订阅,相信很多Harmony开发者也见过或者使用过这个类,那这里作为代码记录,跟大家简单的讲解下具体的使用方式。

1、定义事件接收器

public class MessageCommonEventSubscriber extends CommonEventSubscriber {


    public static final String ACTION_MESSAGE = "action_message";
    public static final String KEY_MESSAGE = "key_message";

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

    @Override
    public void onReceiveEvent(CommonEventData commonEventData) {
        
        if (commonEventData.getIntent() == null) {
            return;
        }

        Intent intent = commonEventData.getIntent();
        String action = intent.getAction();
       
        if (ACTION_MESSAGE.equals(action)) {

            if (intent.hasParameter(KEY_MESSAGE)) {

                String data = intent.getStringParam(KEY_MESSAGE);

            }

        }
    }
}

我们定义一个MessageCommonEventSubscriber 类,继承自CommonEventSubscriber,然后实现onReceiveEvent方法,在方法中获取消息事件。

由于一个事件订阅者可以订阅多个action(多个事件),因此我们这里通过getAction获取到对应的事件意图,然后再获取传递的数据。

2、注册事件订阅者

private void subscribeCommonEvent() {
        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(MessageCommonEventSubscriber.ACTION_MESSAGE);
        matchingSkills.addEvent("actionxxx");
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        CommonEventSubscriber subscriber = new MessageCommonEventSubscriber(subscribeInfo);
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            LogUtil.error("subscribeCommonEvent", e.getMessage());
        }
    }

通过调用CommonEventManager管理器的subscribeCommonEvent方法进行事件订阅,这样就可以收到相应的消息事件了。

上面一个事件订阅者注册需要进行订阅信息的包装,App中可能存在多个订阅者需要注册订阅,场景多了,不免繁琐。下面提供一个注册的封装方法,仅供参考(代码记录哈哈)

public <T extends CommonEventSubscriber> void subscribeMessage(Class<T> tClass, String action) {

        if (tClass == null) {
            return;
        }
        try {
            MatchingSkills matchingSkills = new MatchingSkills();
            matchingSkills.addEvent(action);
            CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
            CommonEventSubscriber subscriber = tClass
                    .getDeclaredConstructor(CommonEventSubscribeInfo.class)
                    .newInstance(subscribeInfo);
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
            LogUtil.error("subscribeMessage", e.getMessage());
        }
    }

这里采用反射获取事件订阅者的对象,实参只需要提供一个事件订阅者的类、一个action事件字符串,就可以完成事件订阅注册,这里如果有多个action,自行调整为数组实现即可。

3、解除注册事件订阅者

...
CommonEventManager.unsubscribeCommonEvent(subscriber);

通过调用CommonEventManager管理器的unsubscribeCommonEvent方法进行解除订阅,解除订阅后,就不会接收到对应action的消息事件。

切记,在页面级别生命周期里,订阅事件跟解除订阅事件,需要配合使用,如果在页面中订阅了事件通知,在页面关闭的时候没有解除订阅,会造成内存泄露,可能会导致一些异常闪退问题。

题外话:这里的事件订阅者订阅是在代码中手动触发订阅,鸿蒙SDK只提供了这种订阅方式,在Android中我们叫动态注册,Android那种在AndroidManifest中添加配置进行静态注册的方式,鸿蒙暂不支持。

4、消息事件发送

    public void sendMessageEvent() {
        try {
            Intent intent = new Intent();
            Intent.OperationBuilder builder = new Intent.OperationBuilder();
            builder.withAction(MessageCommonEventSubscriber.ACTION_MESSAGE);// 设置事件的 action
            intent.setOperation(builder.build());
            //鸿蒙3.0系统后才支持传序列化对象
//            IntentParams intentParams = new IntentParams();
//            intentParams.setClassLoader(getContext().getClassloader());
//            intentParams.setParam(MessageCommonEventSubscriber.KEY_MESSAGE, message);
//            intent.setParams(intentParams);
            Gson gson = new Gson();
            intent.setParam(MessageCommonEventSubscriber.KEY_MESSAGE, gson.toJson(message));
            CommonEventData eventData = new CommonEventData(intent);
            CommonEventManager.publishCommonEvent(eventData);

        } catch (Exception e) {
            LogUtil.info(TAG, "publishCommonEvent occur exception.");
        }
    }

上面通过CommonEventManager.publishCommonEvent就完成了一个消息事件的发送。

注意:在鸿蒙3.0系统之前,CommonEventSubscriber不支持传递序列化对象数据,如果要传递一个对象,这里采用了json的形式,先将对象转成json数据,然后在接收数据的时候进行反序列处理。

到此,本文就完毕了,如果有什么疑问,欢迎评论区沟通探讨。谢谢阅读!

猜你喜欢

转载自blog.csdn.net/q919233914/article/details/126845926
今日推荐