DEV Community

SameX
SameX

Posted on

Technical Analysis of Cross-device Clipboard in HarmonyOS Next

Technical Analysis of Cross-device Clipboard in HarmonyOS Next

In the HarmonyOS Next system, the emergence of the cross-device clipboard has made data sharing between multiple devices easy and efficient. Let's first talk about its principle. When a user copies data on device A, the system clipboard service will process the data, and then synchronize the data to the clipboard service of device B through the connection channel between devices (such as Wi-Fi or Bluetooth, and the effect is better when they are on the same local area network). During this process, both device A and device B need to log in with the same Huawei account and turn on the Wi-Fi and Bluetooth switches to ensure that the data can be transmitted accurately.

From the perspective of the data synchronization mechanism, it is somewhat like express delivery. The clipboard service of each device is like an express delivery station, and the data is like a package. When the data is copied, it will be "packaged" and sent to the "station" (clipboard service) of the target device through a specific "transport route" (device connection channel). Moreover, the data copied across devices is valid within two minutes. Just like an express package has a shelf life, the data will become invalid after this time.

Let's talk about the lifecycle of the clipboard data. From the moment the data is copied into the clipboard until it is pasted or expires, the system will manage the data during this process. Within the valid time, the data is ready to be pasted onto other devices at any time. Once it expires, it will be cleared to ensure the space of the clipboard and the timeliness of the data.

In actual development, the use of the cross-device clipboard API is the key point. First, look at getSystemPasteboard(). This is like opening the door to the device's clipboard repository. Through it, we can obtain the system clipboard object, and all subsequent operations on the clipboard need to be carried out through this object.

The setData() method is used to "put" the data we want to share into the clipboard repository. For example, if we have a piece of text or a picture to copy, we use this method to store the data. However, when accessing the clipboard in the background of a custom control, don't forget to apply for the ohos.permission.READ_PASTEBOARD permission, otherwise, we won't be able to store the data successfully.

The getData() method is used to "fetch" data from the clipboard repository. When we want to paste data on device B, we call this method, and it will return the data we copied previously. Then we can process this data, such as displaying it on the interface or performing other operations.

Here is an actual development case for you to see how to copy text and pictures between different devices. First, look at the code for device A to copy data:

import pasteboard from '@ohos.pasteboard';
import { BusinessError } from '@ohos.base';

export async function setPasteDataTest(): Promise<void> {
    // Prepare the text to be copied
    let text: string = 'This is a piece of text copied across devices';
    // Create a clipboard data object of plain text type
    let pasteData: pasteboard.PasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
    // Get the system clipboard object
    let systemPasteBoard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
    // Write the data to the clipboard
    await systemPasteBoard.setData(pasteData).catch((err: BusinessError) => {
        console.error(`Failed to set pastedata. Code: ${err.code}, message: ${err.message}`);
    });
}
Enter fullscreen mode Exit fullscreen mode

In this code, we first define the text to be copied, then use the createData() method to create a clipboard data object that conforms to the plain text format. Then we obtain the system clipboard object through getSystemPasteboard(), and finally use setData() to write the data to the clipboard. If there is an error during the writing process, the error information will be printed in the console.

Next, look at the code for device B to paste data:

import pasteboard from '@ohos.pasteboard';
import { BusinessError } from '@ohos.base';

export async function getPasteDataTest(): Promise<void> {
    // Get the system clipboard object
    let systemPasteBoard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
    // Get data from the clipboard
    systemPasteBoard.getData((err: BusinessError, data: pasteboard.PasteData) => {
        if (err) {
            console.error(`Failed to get pastedata. Code: ${err.code}, message: ${err.message}`);
            return;
        }
        // Get the number of data records in the clipboard
        let recordCount: number = data.getRecordCount(); 
        // Get the data type in the clipboard
        let types: string = data.getPrimaryMimeType(); 
        // Get the content of the data in the clipboard
        let primaryText: string = data.getPrimaryText(); 
        console.log(`Number of clipboard data records: ${recordCount}`);
        console.log(`Data type: ${types}`);
        console.log(`Data content: ${primaryText}`);
    });
}
Enter fullscreen mode Exit fullscreen mode

On device B, we also first obtain the system clipboard object, and then use the getData() method to get data from the clipboard. Here, we process the obtained data through a callback function. If there is an error during the acquisition process, the error information will also be printed. After obtaining the data, we can further process it. Here, we just simply print out the relevant information of the data.

If we want to copy a picture, the principle is similar, but the data type is not plain text, but the MIME type corresponding to the picture. For example, to copy a picture on device A:

import pasteboard from '@ohos.pasteboard';
import { BusinessError } from '@ohos.base';

export async function setImagePasteDataTest(): Promise<void> {
    // Assume there is a path or binary data of an image resource here
    let imageData = getImageDataSomehow(); 
    let pasteData: pasteboard.PasteData = pasteboard.createData(pasteboard.MIMETYPE_IMAGE_PNG, imageData);
    let systemPasteBoard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
    await systemPasteBoard.setData(pasteData).catch((err: BusinessError) => {
        console.error(`Failed to set pastedata. Code: ${err.code}, message: ${err.message}`);
    });
}
Enter fullscreen mode Exit fullscreen mode

When pasting image data on device B, corresponding processing is required according to the image type, such as displaying it on the interface:

import pasteboard from '@ohos.pasteboard';
import { BusinessError } from '@ohos.base';

export async function getImagePasteDataTest(): Promise<void> {
    let systemPasteBoard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
    systemPasteBoard.getData((err: BusinessError, data: pasteboard.PasteData) => {
        if (err) {
            console.error(`Failed to get pastedata. Code: ${err.code}, message: ${err.message}`);
            return;
        }
        if (data.getPrimaryMimeType() === pasteboard.MIMETYPE_IMAGE_PNG) {
            let imageData = data.getPrimaryImage(); 
            // Here, imageData can be used to display the picture on the interface
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

The above is the technical analysis and actual development cases of the cross-device clipboard in HarmonyOS Next. I hope it will be helpful to you. If you have any questions during the development process, you are welcome to communicate and discuss together.

Top comments (0)