开发者社区
社区提问意见反馈
开发者钉组织
扫描二维码
加入支付宝开发者钉组织
基础 api
基础
应用级事件
界面
跳转
多媒体
缓存
文件
位置
网络
设备
系统信息
网络状态
截屏
剪贴板
摇一摇
振动
加速度计
陀螺仪
罗盘
设备方向
拨打电话
获取服务器时间
用户截屏事件
屏幕亮度
设置
添加手机联系人
无障碍
权限引导
扫码
内存不足告警
获取设备电量
蓝牙
低功耗蓝牙
传统蓝牙
ibeacon
wi-fi
短信
worker
数据安全
分享
收藏
自定义通用菜单
更新管理
web-view组件控制
升级支付宝最新版本
隐私信息授权
小程序广告
开放能力 api
开发 > api > 基础 api > 设备 > 蓝牙 > 传统蓝牙 > my.openbluetoothadapter
评论
收藏
我的文档
设置

my.openbluetoothadapter(object object)

支付宝客户端 10.0.18 或更高版本; 若版本较低,建议采取 兼容处理

小程序开发者工具: 不支持。 请使用真机调试

主体: 企业支付宝小程序个人支付宝小程序

相关文档: 蓝牙 api 错误码对照表蓝牙 api 概览my.closebluetoothadapter

my.openbluetoothadapter 初始化蓝牙适配器。关闭蓝牙适配器请使用 my.closebluetoothadapter
注意:只有蓝牙适配器成功初始化以后,蓝牙相关的其他 api 才能正常使用。

object object

查看示例
属性类型默认值必填描述
autoclosebooleantrue表示是否在离开当前页面时自动断开蓝牙.
注意:仅支持 android 系统。
successfunction-调用成功的回调函数。
failfunction-调用失败的回调函数。
completefunction-调用结束的回调函数(调用成功、失败都会执行)。

success 回调函数

参数

object res

属性类型描述
issupportbleboolean该设备是否支持 ble。

fail 回调的参数为 object,error 属性为错误码,errormessage 属性为错误消息。

错误码错误消息凯发app官方网站的解决方案
14设备蓝牙未授权引导用户授权支付宝使用蓝牙功能。注:该错误玛仅限 ios 端。
2001用户不允许授权。用户拒绝为当前小程序授权。
请在交互中考虑此情况。如有需要,请向用户强调该授权的必要性。
2002用户不允许授权。用户拒绝为当前小程序授权,并勾选了“总是保持以上选择”后,再次调用授权接口产生的报错。
如有需要,提醒或引导用户手动授权:小程序右上角胶囊按钮->设置->打开权限开关;或者通过调用 my.opensetting 帮助用户打开设置页面。
2003用户勾选了不允许授权选项。用户拒绝为当前小程序授权,并勾选了“总是保持以上选择”。
如有需要,提醒或引导用户手动授权:小程序右上角胶囊按钮->设置->打开权限开关;或者通过调用 my.opensetting 帮助用户打开设置页面。

完整的错误码信息请查看蓝牙 api 错误码对照表

代码示例
扫码体验
axml 代码
js 代码

<view class="page">
  <view class="page-description">蓝牙 apiview>
  <view class="page-section">
    <view class="page-section-title">本机蓝牙开关状态view>
    <view class="page-section-demo">
       <button type="primary" ontap="openbluetoothadapter">初始化蓝牙button>
       <button type="primary" ontap="closebluetoothadapter">关闭本机蓝牙button>
       <button type="primary" ontap="getbluetoothadapterstate">获取蓝牙状态button>
    view>
    <view class="page-section-title">扫描蓝牙设备view>
    <view class="page-section-demo">
       <button type="primary" ontap="startbluetoothdevicesdiscovery">开始搜索button>
       <button type="primary" ontap="getbluetoothdevices">所有搜索到的设备button>
       <button type="primary" ontap="getconnectedbluetoothdevices">所有已连接的设备button>
       <button type="primary" ontap="stopbluetoothdevicesdiscovery">停止搜索button>
    view>
    <view class="page-section-title">连接设备view>
    <view class="page-section-demo">
       <input class="input" oninput="bindkeyinput" type="{{text}}" placeholder="输入要连接的设备的deviceid">input>
       <button type="primary" ontap="connectbledevice">连接设备button>
       <button type="primary" ontap="getbledeviceservices">获取设备服务button>
       <button type="primary" ontap="getbledevicecharacteristics">获取读写特征button>
       <button type="primary" ontap="disconnectbledevice">断开设备连接button>
    view>
     <view class="page-section-title">读写数据view>
     <view class="page-section-demo">
       <button type="primary" ontap="notifyblecharacteristicvaluechange">监听特征值数据变化button>
       <button type="primary" ontap="readblecharacteristicvalue">读取数据button>
       <button type="primary" ontap="writeblecharacteristicvalue">写入数据button>
       <button type="primary" ontap="offblecharacteristicvaluechange">取消特征值监听button>
    view>
     <view class="page-section-title">其他事件view>
     <view class="page-section-demo">
       <button type="primary" ontap="bluetoothadapterstatechange">本机蓝牙状态变化button>
       <button type="primary" ontap="offbluetoothadapterstatechange">取消本机蓝牙状态监听button>
       <button type="primary" ontap="bleconnectionstatechanged">蓝牙连接状态变化button>
       <button type="primary" ontap="offbleconnectionstatechanged">取消蓝牙连接状态监听button>
    view>
  view>
view>
// .js
page({
  data: {
    devid: '0d9c82ad-1cc0-414d-9526-119e08d28124',
    serid: 'fee7',
    notifyid: '36f6',
    writeid: '36f5',
    charid: '',
    alldev: [{ deviceid: '' }],
  },
  //获取本机蓝牙开关状态
  openbluetoothadapter() {
    my.openbluetoothadapter({
      success: res => {
        if (!res.issupportble) {
          my.alert({ content: '抱歉,您的手机蓝牙暂不可用' });
          return;
        }
        my.alert({ content: '初始化成功!' });
      },
      fail: error => {
        console.error('初始化失败: ', json.stringify(error));
      },
    });
  },
  closebluetoothadapter() {
    my.closebluetoothadapter({
      success: () => {
        my.alert({ content: '关闭蓝牙成功!' });
      },
      fail: error => {
        console.error('关闭蓝牙失败: ', json.stringify(error));
      },
    });
  },
  getbluetoothadapterstate() {
    my.getbluetoothadapterstate({
      success: res => {
        if (!res.available) {
          my.alert({ content: '抱歉,您的手机蓝牙暂不可用' });
          return;
        }
        my.alert({ content: json.stringify(res) });
      },
      fail: error => {
        console.error('获取信息失败: ', json.stringify(error));
      },
    });
  },
  //扫描蓝牙设备
  startbluetoothdevicesdiscovery() {
    my.startbluetoothdevicesdiscovery({
      allowduplicateskey: false,
      success: () => {
        my.onbluetoothdevicefound(res => {
          var devicearray = res.devices;
          for (var i = devicearray.length - 1; i >= 0; i--) {
            var deviceobj = devicearray[i];
            //通过设备名称或者广播数据匹配目标设备,然后记录deviceid后面使用
            if (deviceobj.name == this.data.name) {
              my.alert({ content: '目标设备被找到' });
              my.offbluetoothdevicefound();
              this.setdata({
                deviceid: deviceobj.deviceid,
              });
              break;
            }
          }
        });
      },
      fail: error => {
        console.error('启动扫描失败: ', json.stringify(error));
      },
    });
  },
  //停止扫描
  stopbluetoothdevicesdiscovery() {
    my.stopbluetoothdevicesdiscovery({
      success: res => {
        my.offbluetoothdevicefound();
        my.alert({ content: '操作成功!' });
      },
      fail: error => {
        console.error('停止扫描失败: ', json.stringify(error));
      },
    });
  },
  //获取正在连接中的设备
  getconnectedbluetoothdevices() {
    my.getconnectedbluetoothdevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '没有在连接中的设备!' });
          return;
        }
        my.alert({ content: json.stringify(res) });
        this.setdata({
          devid: res.devices[0].deviceid,
        });
      },
      fail: error => {
        console.error('获取信息失败: ', json.stringify(error));
      },
    });
  },
  //获取所有搜索到的设备
  getbluetoothdevices() {
    my.getbluetoothdevices({
      success: res => {
        my.alert({ content: json.stringify(res) });
      },
      fail: error => {
        console.error('获取信息失败: ', json.stringify(error));
      },
    });
  },
  bindkeyinput(e) {
    this.setdata({
      devid: e.detail.value,
    });
  },
  //连接设备
  connectbledevice() {
    my.connectbledevice({
      deviceid: this.data.devid,
      success: res => {
        my.alert({ content: '连接成功' });
      },
      fail: error => {
        console.error('连接失败: ', json.stringify(error));
      },
    });
  },
  //断开连接
  disconnectbledevice() {
    my.disconnectbledevice({
      deviceid: this.data.devid,
      success: () => {
        my.alert({ content: '断开连接成功!' });
      },
      fail: error => {
        console.error('断开连接失败: ', json.stringify(error));
      },
    });
  },
  //获取连接设备的server,必须要再连接状态状态之下才能获取
  getbledeviceservices() {
    my.getconnectedbluetoothdevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '没有已连接的设备' });
          return;
        }
        my.getbledeviceservices({
          deviceid: this.data.devid,
          success: res => {
            my.alert({ content: json.stringify(res) });
            this.setdata({
              serid: res.services[0].serviceid,
            });
          },
          fail: error => {
            console.error('获取信息失败: ', json.stringify(error));
          },
        });
      },
    });
  },
  //获取连接设备的charid,必须要再连接状态状态之下才能获取(这里分别筛选出读写特征字)
  getbledevicecharacteristics() {
    my.getconnectedbluetoothdevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '没有已连接的设备' });
          return;
        }
        this.setdata({
          devid: res.devices[0].deviceid,
        });
        my.getbledevicecharacteristics({
          deviceid: this.data.devid,
          serviceid: this.data.serid,
          success: res => {
            my.alert({ content: json.stringify(res) });
            //特征字对象属性见文档,根据属性匹配读写特征字并记录,然后后面读写使用
            this.setdata({
              charid: res.characteristics[0].characteristicid,
            });
          },
          fail: error => {
            console.error('获取信息失败: ', json.stringify(error));
          },
        });
      },
    });
  },
  //读写数据
  readblecharacteristicvalue() {
    my.getconnectedbluetoothdevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '没有已连接的设备' });
          return;
        }
        this.setdata({
          devid: res.devices[0].deviceid,
        });
        my.readblecharacteristicvalue({
          deviceid: this.data.devid,
          serviceid: this.data.serid,
          characteristicid: this.data.notifyid,
          //1、安卓读取服务
          // serviceid:'0000180d-0000-1000-8000-00805f9b34fb',
          // characteristicid:'00002a38-0000-1000-8000-00805f9b34fb',
          success: res => {
            my.alert({ content: json.stringify(res) });
          },
          fail: error => {
            console.error('读取失败: ', json.stringify(error));
          },
        });
      },
    });
  },
  writeblecharacteristicvalue() {
    my.getconnectedbluetoothdevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '没有已连接的设备' });
          return;
        }
        this.setdata({
          devid: res.devices[0].deviceid,
        });
        my.writeblecharacteristicvalue({
          deviceid: this.data.devid,
          serviceid: this.data.serid,
          characteristicid: this.data.charid,
          //安卓写入服务
          //serviceid:'0000180d-0000-1000-8000-00805f9b34fb',
          //characteristicid:'00002a39-0000-1000-8000-00805f9b34fb',
          value: 'abcd',
          success: res => {
            my.alert({ content: '写入数据成功!' });
          },
          fail: error => {
            console.error('写入数据失败: ', json.stringify(error));
          },
        });
      },
    });
  },
  notifyblecharacteristicvaluechange() {
    my.getconnectedbluetoothdevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '没有已连接的设备' });
          return;
        }
        this.setdata({
          devid: res.devices[0].deviceid,
        });
        my.notifyblecharacteristicvaluechange({
          state: true,
          deviceid: this.data.devid,
          serviceid: this.data.serid,
          characteristicid: this.data.notifyid,
          success: () => {
            //监听特征值变化的事件
            my.onblecharacteristicvaluechange(res => {
              my.alert({ content: '得到响应数据 = '  res.value });
            });
            my.alert({ content: '监听成功' });
          },
          fail: error => {
            console.error('监听失败: ', json.stringify(error));
          },
        });
      },
    });
  },
  offblecharacteristicvaluechange() {
    my.offblecharacteristicvaluechange();
  },
  //其他事件
  bluetoothadapterstatechange() {
    my.onbluetoothadapterstatechange(
      this.getbind('onbluetoothadapterstatechange')
    );
  },
  onbluetoothadapterstatechange(res) {
    if (res.error) {
      my.alert({ content: json.stringify(res.error) });
    } else {
      my.alert({ content: '本机蓝牙状态变化:'  json.stringify(res) });
    }
  },
  offbluetoothadapterstatechange() {
    my.offbluetoothadapterstatechange(
      this.getbind('onbluetoothadapterstatechange')
    );
  },
  getbind(name) {
    if (!this[`bind${name}`]) {
      this[`bind${name}`] = this[name].bind(this);
    }
    return this[`bind${name}`];
  },
  bleconnectionstatechanged() {
    my.onbleconnectionstatechanged(this.getbind('onbleconnectionstatechanged'));
  },
  onbleconnectionstatechanged(res) {
    if (res.error) {
      my.alert({ content: json.stringify(res.error) });
    } else {
      my.alert({ content: '连接状态变化:'  json.stringify(res) });
    }
  },
  offbleconnectionstatechanged() {
    my.offbleconnectionstatechanged(
      this.getbind('onbleconnectionstatechanged')
    );
  },
  onunload() {
    this.offbleconnectionstatechanged();
    this.offblecharacteristicvaluechange();
    this.offbluetoothadapterstatechange();
    this.closebluetoothadapter();
  },
});