DEV Community

Cover image for Cross-device file access
liu yang
liu yang

Posted on • Edited on

Cross-device file access

Development Steps for Distributed Networking and Cross-Device File Access in HarmonyOS

Completing Distributed Networking

To enable distributed networking and cross-device communication in HarmonyOS, you need to ensure that both devices are logged into the same account and have Bluetooth and Wi-Fi enabled. This setup allows devices to discover and communicate with each other without requiring Bluetooth pairing or connecting to the same Wi-Fi network.

Steps to Enable Distributed Networking

  1. Log in to the Same Account: Ensure both devices are logged into the same HarmonyOS account. This account synchronization is crucial for device discovery and communication.
  2. Enable Bluetooth and Wi-Fi: Both devices must have Bluetooth and Wi-Fi enabled. These technologies facilitate device discovery and data transfer.
  3. No Pairing Required: Unlike traditional Bluetooth communication, HarmonyOS does not require explicit pairing between devices. The distributed networking feature handles device discovery and connection automatically.

Accessing Cross-Device Files

To enable cross-device file access, you need to place the relevant files in the distributed files directory of the app's sandbox. This directory is synchronized across devices running the same app.

Creating a Test File on Device A

The following code demonstrates how to create and write to a test file in the distributed files directory on Device A.

import { fileIo as fs } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let context = getContext(this) as common.UIAbilityContext;
let pathDir: string = context.distributedFilesDir;
let filePath: string = pathDir + '/test.txt';

try {
  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  fs.writeSync(file.fd, 'content');
  fs.closeSync(file.fd);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to openSync / writeSync / closeSync. Code: ${err.code}, message: ${err.message}`);
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  • fileIo Module: The fileIo module provides file operations such as opening, reading, writing, and closing files.
  • distributedFilesDir: This property of the UIAbilityContext object provides the path to the distributed files directory.
  • OpenMode: The OpenMode enum specifies the mode for opening the file (e.g., read/write or create).

Reading the Test File on Device B

The following code demonstrates how to read the test file created on Device A from Device B.

import { fileIo as fs } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';
import { distributedDeviceManager } from '@kit.DistributedServiceKit';

let dmInstance = distributedDeviceManager.createDeviceManager("com.example.hap");
let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync();
let networkId = deviceInfoList[0].networkId;

let listeners: fs.DfsListeners = {
  onStatus: (networkId: string, status: number): void => {
    console.info('Failed to access public directory');
  }
};

fs.connectDfs(networkId, listeners).then(() => {
  let context = getContext() as common.UIAbilityContext;
  let pathDir: string = context.distributedFilesDir;
  let filePath: string = pathDir + '/test.txt';

  try {
    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
    let arrayBuffer = new ArrayBuffer(4096);
    class Option {
        public offset: number = 0;
        public length: number = 0;
    }
    let option = new Option();
    option.length = arrayBuffer.byteLength;
    let num = fs.readSync(file.fd, arrayBuffer, option);
    let buf = buffer.from(arrayBuffer, 0, num);
    console.info('read result: ' + buf.toString());
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`);
  }
}).catch((error: BusinessError) => {
  console.error(`Failed to connectDfs Code: ${error.code}, message: ${error.message}`);
});
Enter fullscreen mode Exit fullscreen mode

Explanation

  • distributedDeviceManager: This module provides methods for managing distributed devices, including getting the list of available devices.
  • connectDfs: This method connects to the distributed file system of the specified device.
  • DfsListeners: This interface provides a callback for status updates during the connection process.
  • Reading the File: After connecting to the distributed file system, the file is opened, read, and its content is logged to the console.

Disconnecting the Link on Device B

To disconnect from the distributed file system, use the disconnectDfs method.

import { distributedDeviceManager } from '@kit.DistributedServiceKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';

let dmInstance = distributedDeviceManager.createDeviceManager("com.example.hap");
let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync();
let networkId = deviceInfoList[0].networkId;

fs.disconnectDfs(networkId).then(() => {
  console.info("Success to disconnectDfs");
}).catch((error: BusinessError) => {
  console.error(`Failed to disconnectDfs Code: ${error.code}, message: ${err.message}`);
});
Enter fullscreen mode Exit fullscreen mode

Explanation

  • disconnectDfs: This method disconnects from the distributed file system of the specified device.
  • Error Handling: The catch block handles any errors that occur during disconnection.

Practical Use Cases

  • File Synchronization: Use distributed networking to synchronize files across multiple devices, ensuring that users have access to the latest versions of their files.
  • Multi-Device Applications: Develop applications that leverage the capabilities of multiple devices, such as sharing data between a smartphone and a smartwatch.
  • Enhanced User Experience: Provide a seamless user experience by allowing users to access and modify files on any device running the same app.

Top comments (0)