Android:

@CmlModule(alias = "event")
public class EventModule {

    private Map<String, Map<String, CmlCallback<JSONObject>>> callbackMap = new HashMap<>();

    @CmlMethod(alias = "on")
    public void on(ICmlInstance instance,
                   @CmlParam(name = "key") String key,
                   @CmlParam(name = "id") String id,
                   CmlCallback<JSONObject> callback) {
        Map<String, CmlCallback<JSONObject>> map = callbackMap.get(key);
        if (null == map) {
            map = new HashMap<>();
            callbackMap.put(key, map);
        }
        map.put(id, callback);
    }

    @CmlMethod(alias = "off")
    public void off(ICmlInstance instance,
                    @CmlParam(name = "key") String key,
                    @CmlParam(name = "id") String id) {
        Map<String, CmlCallback<JSONObject>> map = callbackMap.get(key);
        if (null == map) {
            return;
        }
        map.remove(id);
    }

    @CmlMethod(alias = "commit")
    public void commit(ICmlInstance instance,
                       @CmlParam(name = "key") String key,
                       @CmlParam(name = "data") JSONObject data) {
        Map<String, CmlCallback<JSONObject>> map = callbackMap.get(key);
        if (null == map) {
            return;
        }
        for (CmlCallback<JSONObject> callback : map.values()) {
            try {
                callback.onCallback(data);
            } catch (Exception e) {
                Log.d(EventModule.class.getSimpleName(), e.getMessage(), e);
            }
        }
    }
}

JS

    mounted() {
        bridge.callNative(
            'event', // 模块名
            'on', // 方法名
            {
                key: "test", // 事件名
                id: "test1" // 监听id 取消监听时有用
            },
            res => {
                cml.showToast({
                    message: 'App Event: ' + res.data.msg,
                    duration: 1000,
                });
            }
        );
    }
    destroyed() {
        bridge.callNative(
            'event', // 模块名
            'off', // 方法名
            {
                key: "test", // 事件名
                id: "test1" // 监听id
            }
        );
    }
    methods = {
        event() {
            bridge.callNative(
                'event', // 模块名
                'commit', // 方法名
                {
                    key: "test", // 事件名
                    data: {
                        msg: "test"
                    }
                }
            );
        },
    }

 

 

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐