DEV Community

SameX
SameX

Posted on

HarmonyOS Cross - Device Communication: Implementation of RPC Data Transmission for Multi - Device Collaboration

This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now), and is summarized based on actual development practices. It mainly serves as a carrier for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.
In today's era of increasingly popular smart devices, multi - device collaborative work has become a common requirement. Imagine that you can use your mobile phone to control the smart TV at home to play videos, or view and edit documents on your computer on a tablet. These scenarios all rely on cross - device inter - process communication (IPC) and remote procedure call (RPC) technologies. Today, let's deeply study how to implement cross - device IPC and RPC in HarmonyOS to achieve data transmission and synchronization between multiple devices. It is like building an invisible bridge to connect different smart devices and realize the free flow of information.

Cross - Device Communication Scenarios and RPC Characteristics

Design Requirements for Cross - Device Communication and the Application of RPC in Device Collaboration

The design requirements for cross - device communication are diverse. In the smart home scenario, users hope to be able to control various smart devices at home, such as lights, air conditioners, curtains, etc., through mobile phone apps. These devices may come from different manufacturers and run on different operating systems, but through the RPC technology of HarmonyOS, they can achieve seamless collaborative work. For example, when the user returns home at night, the mobile phone can automatically detect the user's location and send instructions to the smart lighting system at home through RPC to turn on the lights in the living room and create a warm atmosphere.
In the office scenario, RPC also plays an important role. For example, a team is collaborating on a project, and members use different devices (such as laptops, tablets, smartphones). Through RPC, they can share documents in real time and synchronize the editing progress, just like everyone is working around the same desk. This greatly improves work efficiency and breaks the boundaries between devices.
The key characteristic of RPC in device collaboration is that it can achieve remote method calls as conveniently as local calls. It hides the complexity of cross - device communication and allows developers to focus on the implementation of business logic. For example, in a multi - device game, the player can control the movement of the game character on the mobile phone, while the game's screen rendering and calculation can be performed on a more powerful computer or game console. Through RPC, communication between the mobile phone and other devices is achieved to ensure the smoothness and responsiveness of the game.

Cross - Device Communication Configuration and Implementation

Configure RPC Drivers and Soft Bus for Multi - Device Data Synchronization

To achieve cross - device communication, the RPC driver and soft bus need to be configured first. The RPC driver is responsible for handling the details of communication between devices, just like a traffic controller, ensuring the safe and efficient transmission of data between different devices. The soft bus provides functions such as device discovery and connection management. It is like an invisible information highway that connects various smart devices.
In HarmonyOS application development, we need to correctly set the RPC - related parameters in the project configuration file to enable the RPC driver and soft bus functions. For example, specify the communication protocol, port number, and other information (the specific configuration method may vary depending on the project structure and development tools). At the same time, it is also necessary to ensure that the network connection between devices is normal, whether it is through Wi - Fi, Bluetooth, or other network technologies. This is the foundation of cross - device communication.

Distributed System and the Use of Device Identifiers

Use distributedDeviceManager to Obtain the Device NetworkId for Cross - Device Communication

In cross - device communication, accurately identifying different devices is crucial. HarmonyOS provides distributedDeviceManager to obtain the NetworkId of the device. It is like assigning a unique ID card number to each device. Through this NetworkId, we can explicitly specify the target device for communication and ensure that the data is accurately transmitted to the correct device.
The following is a simple sample code showing how to use distributedDeviceManager to obtain the device NetworkId and perform cross - device communication (using Java instead of Arkts):

import ohos.distributedhardware.devicemanager.DeviceManager;
import ohos.distributedhardware.devicemanager.DeviceManagerCallback;
import ohos.distributedhardware.devicemanager.DeviceManagerException;
import ohos.distributedhardware.devicemanager.LocalDevice;
import ohos.distributedhardware.devicemanager.LocalDeviceChangeListener;
import ohos.distributedhardware.devicemanager.RemoteDevice;
import ohos.distributedhardware.devicemanager.utils.LogUtil;
public class CrossDeviceCommunication {
    private static final String TAG = "CrossDeviceCommunication";
    private DeviceManager deviceManager;
    public CrossDeviceCommunication() {
        try {
            // Get the DeviceManager instance
            deviceManager = DeviceManager.getDeviceManager(null);
        } catch (DeviceManagerException e) {
            LogUtil.error(TAG, "Failed to get DeviceManager: " + e.getMessage());
        }
    }
    // Get local device information
    public void getLocalDeviceInfo() {
        try {
            LocalDevice localDevice = deviceManager.getLocalDevice();
            LogUtil.info(TAG, "Local Device Name: " + localDevice.getDeviceName());
            LogUtil.info(TAG, "Local Device NetworkId: " + localDevice.getNetworkId());
        } catch (DeviceManagerException e) {
            LogUtil.error(TAG, "Failed to get local device info: " + e.getMessage());
        }
    }
    // Device discovery callback
    private DeviceManagerCallback deviceManagerCallback = new DeviceManagerCallback() {
        @Override
        public void onDeviceFound(RemoteDevice remoteDevice) {
            LogUtil.info(TAG, "Device found: " + remoteDevice.getDeviceName() + ", NetworkId: " + remoteDevice.getNetworkId());
            // Here, you can establish a connection and communicate with the discovered device according to your needs
        }
        @Override
        public void onDeviceLost(RemoteDevice remoteDevice) {
            LogUtil.info(TAG, "Device lost: " + remoteDevice.getDeviceName());
        }
        @Override
        public void onDeviceOnline(RemoteDevice remoteDevice) {
            LogUtil.info(TAG, "Device online: " + remoteDevice.getDeviceName());
        }
        @Override
        public void onDeviceOffline(RemoteDevice remoteDevice) {
            LogUtil.info(TAG, "Device offline: " + remoteDevice.getDeviceName());
        }
        @Override
        public void onDeviceReady(RemoteDevice remoteDevice) {
            LogUtil.info(TAG, "Device ready: " + remoteDevice.getDeviceName());
        }
    };
    // Register a device discovery listener
    public void registerDeviceDiscoveryListener() {
        try {
            deviceManager.addDeviceDiscoveryListener(deviceManagerCallback);
        } catch (DeviceManagerException e) {
            LogUtil.error(TAG, "Failed to register device discovery listener: " + e.getMessage());
        }
    }
    // Unregister a device discovery listener
    public void unregisterDeviceDiscoveryListener() {
        try {
            deviceManager.removeDeviceDiscoveryListener(deviceManagerCallback);
        } catch (DeviceManagerException e) {
            LogUtil.error(TAG, "Failed to unregister device discovery listener: " + e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above code, we first obtain the DeviceManager instance, and then obtain the information of the local device through it, including the device name and NetworkId. Then, we register a device discovery listener. When a new device goes online or the device status changes, the corresponding callback notification will be received. In actual applications, we can select the target device according to the result of device discovery and establish a communication connection to achieve data transmission and synchronization.

Code Example and Architecture Diagram: RPC Cross - Device Connection Code and the Communication Flowchart between Devices

The following is a simple RPC cross - device connection code example (in Java language, assuming that the RPC - related environment has been correctly configured):

import ohos.rpc.IRemoteBroker;
import ohos.rpc.IRemoteObject;
import ohos.rpc.MessageOption;
import ohos.rpc.MessageParcel;
import ohos.rpc.RemoteException;
import ohos.rpc.RemoteObject;
// Define the RPC service interface
public interface MyRemoteService extends IRemoteBroker {
    int ADD_SERVICE_ID = 1;
    int add(int a, int b) throws RemoteException;
}
// Service side implementation
public class MyRemoteServiceImpl extends RemoteObject implements MyRemoteService {
    public MyRemoteServiceImpl() {
        super("MyRemoteService");
    }
    @Override
    public int add(int a, int b) throws RemoteException {
        return a + b;
    }
    @Override
    public IRemoteObject asObject() {
        return this;
    }
}
// Client call
public class RpcClient {
    private MyRemoteService myRemoteService;
    public RpcClient(IRemoteObject remoteObject) {
        myRemoteService = IRemoteProxy.asInterface(remoteObject);
    }
    public int callAddService(int a, int b) throws RemoteException {
        MessageParcel data = MessageParcel.obtain();
        MessageParcel reply = MessageParcel.obtain();
        MessageOption option = new MessageOption();
        data.writeInt(a);
        data.writeInt(b);
        try {
            myRemoteService.add(a, b);
            myRemoteService.asObject().sendRequest(ADD_SERVICE_ID, data, reply, option);
        } catch (RemoteException e) {
            e.printStackTrace();
        } finally {
            data.reclaim();
            reply.reclaim();
        }
        return reply.readInt();
    }
}
Enter fullscreen mode Exit fullscreen mode

The communication flowchart between devices is as follows (a simple schematic):
| Step | Description |
|---|---|
| Device Discovery | The client discovers the target device through distributedDeviceManager and obtains its NetworkId. |
| Connection Establishment | The client uses the NetworkId and related configuration information of the target device to establish an RPC connection with the server. |
| Data Transmission | The client packages the request data into MessageParcel and sends it to the server through the sendRequest method. |
| Server Processing | The server receives the request, parses the MessageParcel, and calls the corresponding service method for processing. |
| Result Return | The server packages the processing result into MessageParcel and returns it to the client through the RPC driver. |
| Client Reception | The client receives the MessageParcel returned by the server, parses the result, and performs subsequent processing. |
Through the above introduction to the implementation of cross - device IPC and RPC, including cross - device communication scenarios, configuration and implementation methods, the use of device identifiers, and code examples and communication flowcharts, we can see that HarmonyOS provides strong support for multi - device collaborative communication. In actual development, developers can flexibly use these technologies according to specific application requirements to create more intelligent and convenient multi - device collaborative applications. It is like conducting a wonderful symphony, allowing different instruments (devices) to play a beautiful movement together in a harmonious melody (achieving multi - device collaborative work). Haha, I hope everyone has a smooth journey in exploring HarmonyOS cross - device communication. Let's learn more interesting technical knowledge together next time!

Top comments (0)