项目 / don/cordova-plugin-ble-central
用于 Apache Cordova 的蓝牙低功耗中央设备插件,让手机应用扫描、连接 BLE 外设,并读写特征值、接收通知,也可经 L2CAP 传送数据。
本站整理,非 GitHub 官方 description。
官方快照(gh_history.db,2026-11-25):总榜 未进 Top50 · 日榜 未进 Top50 · 周榜未满 7 天基线(官方不生成) · 月榜暂无官方口径;下方四卡为站内趋势聚合(周卡按上榜次数,非官方 7 日增量窗)。
以下三段按该项目自己的 GitHub README 章节摘录(可合理截断并标明);README 没有对应章节的留空,不编造。
为 iOS、Android(建议 8.1 及以上)及支持 Web Bluetooth 的浏览器提供同一套 JavaScript API。扫描时可得到广播信息,连接后按服务与特征 UUID 访问,由插件内部管理句柄,并支持同时连接多台外设。不用于扫描信标。
来自 GitHub 仓库 README / 主页介绍正文,正文较长,已截断:保留前 20000 字符(原始 60,796 字节),完整内容见 GitHub 仓库。
# Bluetooth Low Energy (BLE) Central Plugin for Apache Cordova
[](https://www.npmjs.com/package/cordova-plugin-ble-central)  [](https://github.com/don/cordova-plugin-ble-central/actions/workflows/cordova.yaml?query=branch%3Amaster) [](https://github.com/don/cordova-plugin-ble-central/actions/workflows/capacitor.yaml?query=branch%3Amaster) [](https://www.npmjs.com/package/cordova-plugin-ble-central)
This plugin enables communication between a phone and Bluetooth Low Energy (BLE) peripherals.
The plugin provides a simple [JavaScript API](#api) for iOS and Android.
- Scan for peripherals
- Connect to a peripheral
- Read the value of a characteristic
- Write new value to a characteristic
- Get notified when characteristic's value changes
- Transfer data via L2CAP channels
Advertising information is returned when scanning for peripherals.
Service, characteristic, and property info is returned when connecting to a peripheral.
All access is via service and characteristic UUIDs. The plugin manages handles internally.
Simultaneous connections to multiple peripherals are supported.
_This plugin isn't intended for scanning beacons._ Try [cordova-plugin-ibeacon](https://github.com/petermetz/cordova-plugin-ibeacon) for iBeacons.<br/>
If you want to create Bluetooth devices, try [cordova-plugin-ble-peripheral](https://github.com/don/cordova-plugin-ble-peripheral).
See the [examples](https://github.com/don/cordova-plugin-ble-central/tree/master/examples) for ideas on how this plugin can be used.
## Supported Platforms
- iOS
- Android 6+ (8.1 or greater recommended)
- Browser (where navigator.bluetooth is supported)
# Installing
## Capacitor
$ npm install cordova-plugin-ble-central
$ npx cap sync
The plugin can be further configured via the cordova preferences section of the [capacitor config file](https://capacitorjs.com/docs/cordova/migrating-from-cordova-to-capacitor#cordova-plugin-preferences):
```typescript
const config = {
...
cordova: {
preferences: {
...
bluetooth_restore_state: "true",
accessBackgroundLocation: "false",
},
}
}
```
- `bluetooth_restore_state`: [**iOS**] Enable Bluetooth state restoration, allowing an app to be woken up to receive scan results and peripheral notifications. This is needed for background scanning support. See [iOS restore state](https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html#//apple_ref/doc/uid/TP40013257-CH7-SW13). For more information about background operation with this plugin, see [Background Scanning and Notifications on iOS](#background-scanning-and-notifications-on-ios).
- `accessBackgroundLocation`: [**Android**] Tells the plugin to request the `ACCESS_BACKGROUND_LOCATION` permission on Android 10 & Android 11 in order for scanning to function when the app is not visible.
### iOS
After installation, the following additions should be made to the app's `Info.plist`
- Set [NSBluetoothAlwaysUsageDescription](https://developer.apple.com/documentation/bundleresources/information_property_list/nsbluetoothalwaysusagedescription?language=objc) to a descriptive text, to be shown to the user on first access to the Bluetooth adapter. **If this is not defined the app will crash**.
- _(Optional)_ Add `bluetooth-central` to [UIBackgroundModes](https://developer.apple.com/documentation/bundleresources/information_property_list/uibackgroundmodes?language=objc) to enable background receipt of scan information and BLE notifications
## Cordova
`$ cordova plugin add cordova-plugin-ble-central --variable BLUETOOTH_USAGE_DESCRIPTION="Your description here" --variable IOS_INIT_ON_LOAD=true|false --variable BLUETOOTH_RESTORE_STATE=true|false --variable ACCESS_BACKGROUND_LOCATION=true|false`
It's recommended to always use the latest cordova and cordova platform packages in order to ensure correct function. This plugin generally best supports the following platforms and version ranges:
| cordova | cordova-ios | cordova-android | cordova-browser |
| ------- | ----------- | --------------- | --------------- |
| 10+ | 6.2.0+ | 12.0+ | not tested |
All variables can be modified after installation by updating the values in `package.json`.
- `BLUETOOTH_USAGE_DESCRIPTION`: [**iOS**] defines the values for [NSBluetoothAlwaysUsageDescription](https://developer.apple.com/documentation/bundleresources/information_property_list/nsbluetoothalwaysusagedescription?language=objc).
- `IOS_INIT_ON_LOAD`: [**iOS**] Prevents the Bluetooth plugin from being initialised until first access to the `ble` window object. This allows an application to warn the user before the Bluetooth access permission is requested.
- `BLUETOOTH_RESTORE_STATE`: [**iOS**] Enable Bluetooth state restoration, allowing an app to be woken up to receive scan results and peripheral notifications. This is needed for background scanning support. See [iOS restore state](https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html#//apple_ref/doc/uid/TP40013257-CH7-SW13). For more information about background operation with this plugin, see [Background Scanning and Notifications on iOS](#background-scanning-and-notifications-on-ios).
- `ACCESS_BACKGROUND_LOCATION`: [**Android**] Tells the plugin to request the ACCESS_BACKGROUND_LOCATION permission on Android 10 & Android 11 in order for scanning to function when the app is not visible.
## TypeScript
TypeScript definitions are provided by this plugin. These can be added to a file by adding a [triple-slash reference](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-types-) at the top of any file using this plugin:
```typescript
/// <reference types="cordova-plugin-ble-central" />
```
## Android permission conflicts
If you are having Android permissions conflicts with other plugins, try using the `slim` variant of the plugin instead with `cordova plugin add cordova-plugin-ble-central@slim`. This variant excludes all Android permissions, leaving it to the developer to ensure the right entries are added manually to the `AndroidManifest.xml` (see below for an example).
To include the default set of permissions the plugin installs on Android SDK v31+, add the following snippet in your `config.xml` file, in the `<platform name="android">` section:
```xml
<config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
</config-file>
```
For the best understanding about which permissions are needed for which combinations of target SDK version & OS version, see [Android Bluetooth permissions](https://developer.android.com/guide/topics/connectivity/bluetooth/permissions)
# API
- [ble.scan](#scan)
- [ble.startScan](#startscan)
- [ble.startScanWithOptions](#startscanwithoptions)
- [ble.stopScan](#stopscan)
- [ble.setPin](#setpin)
- [ble.bond](#bond)
- [ble.unbond](#unbond)
- [ble.readBondState](#readbondstate)
- [ble.connect](#connect)
- [ble.autoConnect](#autoconnect)
- [ble.disconnect](#disconnect)
- [ble.requestMtu](#requestmtu)
- [ble.requestConnectionPriority](#requestconnectionpriority)
- [ble.refreshDeviceCache](#refreshdevicecache)
- [ble.read](#read)
- [ble.write](#write)
- [ble.writeWithoutResponse](#writewithoutresponse)
- [ble.startNotification](#startnotification)
- [ble.stopNotification](#stopnotification)
- [ble.isConnected](#isconnected)
- [ble.isEnabled](#isenabled)
- [ble.isLocationEnabled](#islocationenabled)
- [ble.startLocationStateNotifications](#startlocationstatenotifications)
- [ble.stopLocationStateNotifications](#stoplocationstatenotifications)
- [ble.startStateNotifications](#startstatenotifications)
- [ble.stopStateNotifications](#stopstatenotifications)
- [ble.showBluetoothSettings](#showbluetoothsettings)
- [ble.enable](#enable)
- [ble.readRSSI](#readrssi)
- [ble.connectedPeripheralsWithServices](#connectedperipheralswithservices)
- [ble.peripheralsWithIdentifiers](#peripheralswithidentifiers)
- [ble.restoredBluetoothState](#restoredbluetoothstate)
- [ble.list](#list)
- [ble.bondedDevices](#bondeddevices)
- [ble.l2cap.open](#l2capopen)
- [ble.l2cap.close](#l2capclose)
- [ble.l2cap.receiveData](#l2capreceivedata)
- [ble.l2cap.write](#l2capwrite)
## scan
Scan and discover BLE peripherals.
```javascript
ble.scan(services, seconds, success, failure);
```
### Description
Function `scan` scans for BLE devices. The success callback is called each time a peripheral is discovered. Scanning automatically stops after the specified number of seconds.
```json
{
"name": "TI SensorTag",
"id": "BD922605-1B07-4D55-8D09-B66653E51BBA",
"rssi": -79,
"advertising": /* ArrayBuffer or map */
}
```
Advertising information format varies depending on your platform. See [Advertising Data](#advertising-data) for more information.
### Location Permission Notes
With Android SDK >= 23 (6.0), additional permissions are required for Bluetooth low energy scanning. The location permission [ACCESS_COARSE_LOCATION](https://developer.android.com/reference/android/Manifest.permission.html#ACCESS_COARSE_LOCATION) is required because Bluetooth beacons can be used to determine a user's location. If necessary, the plugin will prompt the user to allow the app to access to device's location. If the user denies permission, the scan failure callback will receive the error "Location permission not granted".
Location Services must be enabled for Bluetooth scanning. If location services are disabled, the failure callback will receive the error "Location services are disabled". If you want to manage location permission and screens, try the [cordova-diagonostic-plugin](https://github.com/dpa99c/cordova-diagnostic-plugin) or the Ionic Native [Diagnostic plugin](https://ionicframework.com/docs/native/diagnostic/).
### Parameters
- **services**: List of services to discover, or [] to find all devices
- **seconds**: Number of seconds to run discovery
- **success**: Success callback function that is invoked which each discovered device.
- **failure**: Error callback function, invoked when error occurs. [optional]
### Quick Example
```javascript
ble.scan(
[],
5,
function (device) {
console.log(JSON.stringify(device));
},
failure
);
```
## startScan
Scan and discover BLE peripherals.
```javascript
ble.startScan(services, success, failure);
```
### Description
Function `startScan` scans for BLE devices. The success callback is called each time a peripheral is discovered. Scanning will continue until `stopScan` is called.
```json
{
"name": "TI SensorTag",
"id": "BD922605-1B07-4D55-8D09-B66653E51BBA",
"rssi": -79,
"advertising": /* ArrayBuffer or map */
}
```
Advertising information format varies depending on your platform. See [Advertising Data](#advertising-data) for more information.
See the [location permission notes](#location-permission-notes) above for information about Location Services in Android SDK >= 23.
### Parameters
- **services**: List of services to discover, or [] to find all devices
- **success**: Success callback function that is invoked which each discovered device.
- **failure**: Error callback function, invoked when error occurs. [optional]
### Quick Example
```javascript
ble.startScan(
[],
function (device) {
console.log(JSON.stringify(device));
},
failure
);
setTimeout(
ble.stopScan,
5000,
function () {
console.log('Scan complete');
},
function () {
console.log('stopScan failed');
}
);
```
## startScanWithOptions
Scan and discover BLE peripherals, specifying scan options.
```javascript
ble.startScanWithOptions(services, options, success, failure);
```
### Description
Function `startScanWithOptions` scans for BLE devices. It operates similarly to the `startScan` function, but allows you to specify extra options (like allowing duplicate device reports). The success callback is called each time a peripheral is discovered. Scanning will continue until `stopScan` is called.
```json
{
"name": "TI SensorTag",
"id": "BD922605-1B07-4D55-8D09-B66653E51BBA",
"rssi": -79,
"advertising": /* ArrayBuffer or map */
}
```
Advertising information format varies depending on your platform. See [Advertising Data](#advertising-data) for more information.
See the [location permission notes](#location-permission-notes) above for information about Location Services in Android SDK >= 23.
### Parameters
- **services**: List of services to discover, or [] to find all devices
- **options**: an object specifying a set of name-value pairs. The currently acceptable options are:
- _reportDuplicates_: _true_ if duplicate devices should be reported, _false_ (default) if devices should only be reported once.
- _duration_: time in seconds to scan for. (default) Scans forever when not specified.
- _scanMode_: String defines [setScanMode()](https://developer.android.com/reference/kotlin/android/bluetooth/le/ScanSettings.Builder#setscanmode) argument on Android. Default on Android is _lowPower_. When interactive scanning from an app, _lowLatency_ can boost how quickly the device is found, at the expense of using more battery power.
Can be one of: _lowPower_ | _balanced_ | _lowLatency_ | _opportunistic_
- _callbackType_: String defines [setCallbackType()](https://developer.android.com/reference/kotlin/android/bluetooth/le/ScanSettings.Builder#setcallbacktype) argument on Android.
Can be one of: _all_ | _first_ | _lost_
- _matchMode_: String defines [setMatchMode()](https://developer.android.com/reference/kotlin/android/bluetooth/le/ScanSettings.Builder#setmatchmode) argument on Android.
Can be one of: _aggressive_ | _sticky_
- _numOfMatches_: String defines [setNumOfMatches()](https://developer.android.com/reference/kotlin/android/bluetooth/le/ScanSettings.Builder#setnumofmatches) argument on Android.
Can be one of: _one_ | _few_ | _max_
- _phy_: String for [setPhy()](https://developer.android.com/reference/kotlin/android/bluetooth/le/ScanSettings.Builder#setphy) on Android.
Can be one of: _1m_ | _coded_ | _all_
- _legacy_: _true_ or _false_ to [control filtering](https://developer.android.com/reference/kotlin/android/bluetooth/le/ScanSettings.Builder#setlegacy) bluetooth spec.pre-4.2 advertisements on Android.
- _forceScanFilter_: _true_ or _false_ to [to force an empty scan filter](https://github.com/don/cordova-plugin-ble-central/issues/987) if no other filters are provided on Android.
- _reportDelay_: Milliseconds for [setReportDelay()](https://developer.android.com/reference/kotlin/android/bluetooth/le/ScanSettings.Builder#setreportdelay) on Android. _0_ to be notified of results immediately. Values > _0_ causes the scan results to be queued up and delivered after the requested delay or when the internal buffers fill up.
- **success**: Success callback function that is invoked which each discovered device.
- **failure**: Error callback function, invoked when error occurs. [optional]
### Quick Example
```javascript
ble.startScanWithOptions([],
{ reportDuplicates: true }
function(device) {
console.log(JSON.stringify(device));
},
failure);
setTimeout(ble.stopScan,
5000,
function() { console.log("Scan complete"); },
function() { console.log("stopScan failed"); }
);
```
## stopScan
Stop scanning for BLE peripherals.
```javascript
ble.stopScan(success, failure);
// Or using await with promises
await ble.withPromises.stopScan();
```
### Description
Function `stopScan` stops scanning for BLE devices.
### Parameters
- **success**: Success callback function, invoked when scanning is stopped. [optional]
- **failure**: Error callback function, invoked when error occurs. [optional]
### Quick Example
```javascript
ble.startScan(
[],
function (device) {
console.log(JSON.stringify(device));
},
failure
);
setTimeout(
ble.stopScan,
5000,
function () {
console.log('Scan complete');
},
function () {
console.log('stopScan failed');
}
);
/* Alternate syntax
setTimeout(function() {
ble.stopScan(
function() { console.log("Scan complete"); },
function() { console.log("stopScan failed"); }
);
}, 5000);
*/
```
## setPin
Set device pin
```javascript
ble.setPin(pin, [success], [failure]);
// Or using await with promises
await ble.withPromises.setPin(pin);
```
### Description
Function `setPin` sets the pin when device requires it.
### Parameters
- **pin**: Pin of the device as a string
- **success**: Success callback function that is invoked when the function is invoked. [optional]
- **failure**: Error callback function, invoked when error occurs. [optional]
## bond
Initiate a bond with a remote device
```javascript
ble.bond(device_id, [success], [failure], [options]);
// Or using await with promises
await ble.withPromises.bond(device_id);
await ble.withPromises.bond(device_id, { usePairingDialog: true });
```
### Description
Function `bond` initialises a bond with a peripheral. The success callback will be called when the
bonding is complete. The bonding process may prompt the user to confirm the pairing process.
### Parameters
- **device_id**: UUID or MAC address of the peripheral
- **success**: Success callback function that is invoked when the bonding succeeds. [optional]
- **failure**: Error callback function, invoked when the bonding fails. [optional]
- **options**: an object specifying a set of name-value pairs. The currently acceptable options are:
- _usePairingDialog_: _true_ (default) Show pairing request as a dialog rather than a notification [optional]
### Supported Platforms
- Android
## unbond
Remove a bond for a remote device
```javascript
ble.unbond(device_id, [success], [failure]);
// Or using await with promises
await ble.withPromises.unbond(device_id);
```
### Description
Function `unbond` removes an existing bond for a remote device. The success callback will be called when the
bond has been removed.
### Parameters
- **device_id**: UUID or MAC address of the peripheral
- **success**: Success callback function that is invoked when the bond is removed. [optional]
- **failure**: Error callback function, inv