# inter-app communication **Repository Path**: cxshu/inter-app-communication ## Basic Information - **Project Name**: inter-app communication - **Description**: 跨应用通信,实现了不同应用之间对公共事件的发布和订阅。 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-02-01 - **Last Updated**: 2022-02-01 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README 我们在entry模块中订阅公共事件 修改entry模块下的MainAbilitySlice代码如下 ``` public class MainAbilitySlice extends AbilitySlice { // 自定义公共事件的名称 static final String EVENT_ACTION = "com.cxs.commoneventtest.event"; // Intent传递数据的Key static final String INTENT_PARAM_KEY = "intent.param.key"; static boolean isSubscribe = false; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); findComponentById(ResourceTable.Id_text_helloworld).setClickedListener(this::subscribe); } private void subscribe(Component component) { if (isSubscribe) { return; } MatchingSkills matchingSkills = new MatchingSkills(); matchingSkills.addEvent(EVENT_ACTION); CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills); CommonEventSubscriber subscriber = new CommonEventSubscriber(subscribeInfo) { @Override public void onReceiveEvent(CommonEventData commonEventData) { Intent intent = commonEventData.getIntent(); int intParam = intent.getIntParam(INTENT_PARAM_KEY, -1); System.out.println("onReceiveEvent:" + intParam); } }; try { // 订阅公共事件 CommonEventManager.subscribeCommonEvent(subscriber); isSubscribe = true; System.out.println("订阅公共事件成功!"); } catch (RemoteException e) { e.printStackTrace(); } } } ``` 新建一个entry模块,名称为entry2,我们在entry2模块中发布公共事件 修改MainAbilitySlice代码如下 ``` public class MainAbilitySlice extends AbilitySlice { // 这里的公共事件的名称必须和entry模块的一样 static final String EVENT_ACTION = "com.cxs.commoneventtest.event"; static final String INTENT_PARAM_KEY = "intent.param.key"; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); findComponentById(ResourceTable.Id_text_helloworld).setClickedListener(this::publishEvent); } /** * 发布公共事件 * @param component */ private void publishEvent(Component component) { // 1. 构建一个Intent对象,包含了自定义的事件的标识符 Intent intent = new Intent(); Operation operation = new Intent.OperationBuilder() .withAction(EVENT_ACTION) // 自定义的事件标识符 .build(); intent.setOperation(operation); intent.setParam(INTENT_PARAM_KEY, "Hello HarmonyOS"); // 2. 构建CommonEventData对象 CommonEventData commonEventData = new CommonEventData(intent); // 3. 核心的发布事件的动作 try { CommonEventManager.publishCommonEvent(commonEventData); System.out.println("发布事件结束"); } catch (RemoteException e) { e.printStackTrace(); } } } ```