openharmony 鸿蒙 js-apis-bluetooth-opp-sys

2025-06-12 浏览 (1)

@ohos.bluetooth.opp (Bluetooth OPP Module) (System API)

The OPP module provides the Bluetooth-based file transfer functions, including sending files, receiving files, and obtaining the file transfer progress.

NOTE

The initial APIs of this module are supported since API version 16. Newly added APIs will be marked with a superscript to indicate their earliest API version.

This topic describes only the system APIs provided by the module.

Modules to Import

import { opp } from '@kit.ConnectivityKit';

createOppServerProfile

createOppServerProfile(): OppServerProfile

Creates an OppServerProfile instance.

System API: This is a system API.

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
OppServerProfileOppServerProfile instance.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
202Non-system applications are not allowed to use system APIs.
801Capability not supported.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let oppProfile = opp.createOppServerProfile();
    console.info('oppServer success');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

OppServerProfile

Represents the OppServerProfile class. Before using APIs of this class, you need to create an OppServerProfile instance by using the createOppServerProfile ().

sendFile

sendFile(deviceId: string, fileHolds: Array<FileHolder<): Promise<void>

Send files over Bluetooth.

System API: This is a system API.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesBluetooth MAC address of the receiver.
fileHoldsArray<FileHolder>YesFile data to transfer. Data is sent according to the sequence it is inserted into the array.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
202Permission denied. Non-system applications are not allowed to use system APIs.
203This function is prohibited by enterprise management policies.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile is not supported.
2900099Failed to send file.
2903001The file type is not supported.
2903002Current Transfer Information is busy.
2903003The file is not accessible.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { opp } from '@kit.ConnectivityKit';
// Create fileHolders.
try {
    let oppProfile = opp.createOppServerProfile();
    let fileHolders : Array<opp.FileHolder> = [];
    // Valid URIs
    let uris: Array<string> = ['test1.jpg', 'test2.jpg'];
    for (let i = 0; i < uris.length; i++) {
        let filePath = uris[i];
        console.info('opp deal filePath is :' + filePath);
        let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
        let stat: fs.Stat = fs.statSync(file.fd);
        let fileHolder: opp.FileHolder = {
        filePath:filePath,
        fileSize:stat.size,
        fileFd:file.fd
        };
        fileHolders.push(fileHolder);
    }
    oppProfile.sendFile("11:22:33:44:55:66", fileHolders);
    // After the file transfer is complete, call fs.close(file.fd) to close the file descriptor.
} catch (err) {
      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

setIncomingFileConfirmation

setIncomingFileConfirmation(accept: boolean, fileFd: number): Promise<void>

Receives files over Bluetooth.

System API: This is a system API.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
acceptbooleanYesWhether to accept the file transfer request. The value true means to accept the file transfer request, and the value false means the opposite.
fileFdnumberYesFile descriptor, which must be enabled during file receiving.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
202Permission denied. Non-system applications are not allowed to use system APIs.
203This function is prohibited by enterprise management policies.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile is not supported.
2900099Failed to confirm the received file information.
2903002Current Transfer Information is busy.
2903003The file is not accessible.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { opp } from '@kit.ConnectivityKit';
// Create fileHolders.
try {
    let oppProfile = opp.createOppServerProfile();
    let pathDir = this.context.filesDir + "/test.jpg";
    let file = fs.openSync(pathDir, fs.OpenMode.CREATE|fs.OpenMode.READ_WRITE);
    oppProfile.setIncomingFileConfirmation(true, file.fd);
    // Close the file descriptor after file receiving is complete. 
    fs.close(file.fd);
} catch (err) {
      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

on('transferStateChange')

on(type: 'transferStateChange', callback: Callback<OppTransferInformation>): void

Subscribes to the progress and status changes of Bluetooth file transfer.

System API: This is a system API.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The field has a fixed value of transferStateChange. After on('transferStateChange') is called, the file transfer progress and status change events will be returned.
callbackCallback<OppTransferInformation>YesCallback used to return the file transfer progress and status change events.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
202Permission denied. Non-system applications are not allowed to use system APIs.
203This function is prohibited by enterprise management policies.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile is not supported.
2903001The file type is not supported.
2903002Current Transfer Information is busy.
2903003The file is not accessible.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { opp } from '@kit.ConnectivityKit';
// Create fileHolders.
try {
    let oppProfile = opp.createOppServerProfile();
    oppProfile.on("transferStateChange", (data: opp.OppTransferInformation) => {
        if (data.status == opp.TransferStatus.PENDING) {
          console.info("[opp_js] waiting to transfer : " + data.remoteDeviceName);
        } else if (data.status == opp.TransferStatus.RUNNING){
          console.info("[opp_js] running data.currentBytes " + data.currentBytes + " data.totalBytes" + data.totalBytes);
        } else if (data.status == opp.TransferStatus.FINISH){
          console.info("[opp_js] transfer finished, result is " + data.result);
        }
      });
} catch (err) {
      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

off('transferStateChange')

off(type: 'transferStateChange', callback?: Callback<OppTransferInformation>): void

Unsubscribes from the progress and status changes of Bluetooth file transfer.

System API: This is a system API.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The field has a fixed value of transferStateChange. After off('transferStateChange') is called, the file transfer progress and status change events will not be returned.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
202Permission denied. Non-system applications are not allowed to use system APIs.
203This function is prohibited by enterprise management policies.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile is not supported.
2903001The file type is not supported.
2903002Current Transfer Information is busy.
2903003The file is not accessible.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { opp } from '@kit.ConnectivityKit';
// Create fileHolders.
try {
    let oppProfile = opp.createOppServerProfile();
    oppProfile.off("transferStateChange");
} catch (err) {
      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

on('receiveIncomingFile')

on(type: 'receiveIncomingFile', callback: Callback<OppTransferInformation>): void

Subscribes to Bluetooth file transfer start events.

System API: This is a system API.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The field has a fixed value of receiveIncomingFile. After on('receiveIncomingFile') is called, an event will be returned when file transfer begins.
callbackCallback<OppTransferInformation>YesCallback used to return the file transfer progress and status change events.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
202Permission denied. Non-system applications are not allowed to use system APIs.
203This function is prohibited by enterprise management policies.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile is not supported.
2903001The file type is not supported.
2903002Current Transfer Information is busy.
2903003The file is not accessible.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { opp } from '@kit.ConnectivityKit';
// Create fileHolders.
try {
    let oppProfile = opp.createOppServerProfile();
    oppProfile.on("receiveIncomingFile", (data: opp.OppTransferInformation) => {
        if (data.status == opp.TransferStatus.PENDING) {
          console.info("[opp_js] received file waiting to confirm : " + data.remoteDeviceName);
        } else if (data.status == opp.TransferStatus.RUNNING){
          console.info("[opp_js] running data.currentBytes " + data.currentBytes + " data.totalBytes" + data.totalBytes);
        } else if (data.status == opp.TransferStatus.FINISH){
          console.info("[opp_js] transfer finished, result is " + data.result);
        }
      });
} catch (err) {
      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

off('receiveIncomingFile')

off(type: 'receiveIncomingFile', callback?: Callback<OppTransferInformation>): void

Unsubscribes from Bluetooth file transfer completion events.

System API: This is a system API.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The field has a fixed value of receiveIncomingFile. After off('receiveIncomingFile') is called, an event will be returned when file transfer is complete.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
202Permission denied. Non-system applications are not allowed to use system APIs.
203This function is prohibited by enterprise management policies.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile is not supported.
2903001The file type is not supported.
2903002Current Transfer Information is busy.
2903003The file is not accessible.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { opp } from '@kit.ConnectivityKit';
// Create fileHolders.
try {
    let oppProfile = opp.createOppServerProfile();
    oppProfile.off("receiveIncomingFile");
} catch (err) {
      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

cancelTransfer

cancelTransfer(): Promise<void>

Cancels Bluetooth file transfer.

System API: This is a system API.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
202Permission denied. Non-system applications are not allowed to use system APIs.
203This function is prohibited by enterprise management policies.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile is not supported.
2900099Failed to cancel the current transfer.
2903002Current Transfer Information is busy.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { opp } from '@kit.ConnectivityKit';
// Create fileHolders.
try {
    let oppProfile = opp.createOppServerProfile();
    oppProfile.cancelTransfer();
} catch (err) {
      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

getCurrentTransferInformation

getCurrentTransferInformation(): Promise<OppTransferInformation>

Obtains the information about the file that is being transferred.

System API: This is a system API.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
202Permission denied. Non-system applications are not allowed to use system APIs.
203This function is prohibited by enterprise management policies.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile is not supported.
2900099Failed to obtain the current transmission information.
2903004Current Transfer Information is empty.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { opp } from '@kit.ConnectivityKit';
// Create fileHolders.
try {
    let oppProfile = opp.createOppServerProfile();
    let data = oppProfile.getCurrentTransferInformation();
    console.info('[opp_js] data ', data.status);
} catch (err) {
      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

setLastReceivedFileUri

setLastReceivedFileUri(uri: string): Promise<void>

Sets the URI of the last received file.

System API: This is a system API.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
uristringYesURI of the last received file.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
202Permission denied. Non-system applications are not allowed to use system APIs.
203This function is prohibited by enterprise management policies.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile is not supported.
2900099Failed to set the URI of the last file.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { opp } from '@kit.ConnectivityKit';
// Create fileHolders.
try {
    let oppProfile = opp.createOppServerProfile();
    oppProfile.setLastReceivedFileUri("file://media/Photo/1/IMG_1739266559_000/screenshot_20250211_173419.jpg ");
} catch (err) {
      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

FileHolder

Describes the information about the file to be sent.

System API: This is a system API.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
filePathstringYesYesURI of the file to be sent, for example, file://media/Photo/1/IMG_1739266559_000/test.jpg.
fileSizenumberYesYesSize of the file to be sent, in bytes.
fileFdnumberYesYesOpened file descriptor of the file to be sent. The file descriptor must be kept open until the file transfer is complete.

OppTransferInformation

Describes the file transfer information.

System API: This is a system API.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
filePathstringYesYesURI of the file to be sent, for example, file://media/Photo/1/IMG_1739266559_000/test.jpg.
remoteDeviceNamestringYesYesName of the peer device.
remoteDeviceIdnumberYesYesMAC address of the peer device.
directionDirectionTypeYesYesTransfer direction.
statusTransferStatusYesYesTransfer status.
resultTransferResultYesYesTransfer result.
currentBytesnumberYesYesNumber of transferred bytes.
totalBytesnumberYesYesTotal number of bytes to be transferred.
currentCountnumberYesYesSequence number of the file to be transferred.
totalCountnumberYesYesTotal number of transferred files.

DirectionType

Enumerates file transfer directions.

System API: This is a system API.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
OUTBOUND0File sending.
INBOUND1File receiving.

TransferStatus

Enumerates the file transfer states.

System API: This is a system API.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
PENDING0Waiting for transfer.
RUNNING1File transfer in progress.
FINISH2File transfer completed.

TransferResult

Enumerates file transfer results.

System API: This is a system API.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
SUCCESS0File transfer is successful.
ERROR_UNSUPPORTED_TYPE1The type of files to be transferred is not supported.
ERROR_BAD_REQUEST2The peer device cannot process the file transfer request.
ERROR_NOT_ACCEPTABLE3The peer device rejects the file transfer request.
ERROR_CANCELED4The peer device cancels the file transfer.
ERROR_CONNECTION_FAILED5The peer device is disconnected.
ERROR_TRANSFER6An error occurs during file transfer.
ERROR_UNKNOWN7An unknown error occurs.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Connectivity Kit (Short-Range Communication Service)

harmony 鸿蒙Bluetooth

harmony 鸿蒙Wifi

harmony 鸿蒙Bluetooth Error Codes

harmony 鸿蒙NFC Error Codes

harmony 鸿蒙SecureElement Error Codes

harmony 鸿蒙Wi-Fi Error Codes

harmony 鸿蒙@ohos.bluetooth.a2dp (Bluetooth A2DP Module) (System API)

harmony 鸿蒙@ohos.bluetooth.a2dp (Bluetooth A2DP Module)

harmony 鸿蒙@ohos.bluetooth.access (Bluetooth Access Module) (System API)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/R0Tgj3