You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android BLE模块连接状态查询:无BluetoothManager访问权限解决方案

解决Appcelerator-Titanium中获取BLE设备连接状态的问题

我之前开发Titanium的Android BLE模块时也碰到过这个报错,核心就是要正确拿到Android的BluetoothManager服务,下面给你两种实用的实现方式:

方法一:通过当前Activity获取Context(推荐前台场景)

如果你的代码是在Activity上下文里执行的(比如和UI相关的模块逻辑),可以直接通过Ti.Android.currentActivity拿到Context,再获取BluetoothManager:

// 获取当前Activity的上下文
var currentContext = Ti.Android.currentActivity;
// 获取BluetoothManager系统服务
var bluetoothManager = currentContext.getSystemService(Ti.Android.BLUETOOTH_SERVICE);

// 从已持有的BluetoothGatt对象中获取对应的BluetoothDevice
var targetDevice = bluetoothGatt.getDevice();
// 查询GATT连接状态
var connectionState = bluetoothManager.getConnectionState(targetDevice, Ti.Android.BLUETOOTH_PROFILE_GATT);

// 状态值对应说明:
// * 0 = STATE_DISCONNECTED(已断开)
// * 1 = STATE_CONNECTING(连接中)
// * 2 = STATE_CONNECTED(已连接)
// * 3 = STATE_DISCONNECTING(断开中)

方法二:使用应用全局Context(后台/无Activity场景)

如果你的代码是在后台服务或者没有Activity的环境中运行,就用应用全局Context来获取服务:

// 获取应用全局上下文
var appContext = Ti.Android.appContext;
var bluetoothManager = appContext.getSystemService(Ti.Android.BLUETOOTH_SERVICE);

// 同样从BluetoothGatt获取设备对象
var targetDevice = bluetoothGatt.getDevice();
var connectionState = bluetoothManager.getConnectionState(targetDevice, Ti.Android.BLUETOOTH_PROFILE_GATT);

额外注意事项

  • 权限检查:Android 12及以上需要申请BLUETOOTH_CONNECT权限,低版本需要BLUETOOTH和BLUETOOTH_ADMIN权限,确保你在tiapp.xml中已经配置了这些权限。
  • 异常处理:建议给获取服务和查询状态的代码加上try-catch块,避免因系统服务不可用导致崩溃:
    try {
        var bluetoothManager = currentContext.getSystemService(Ti.Android.BLUETOOTH_SERVICE);
        var connectionState = bluetoothManager.getConnectionState(targetDevice, Ti.Android.BLUETOOTH_PROFILE_GATT);
        // 处理状态逻辑
    } catch (e) {
        Ti.API.error("获取连接状态失败:" + e.message);
    }
    

内容的提问来源于stack exchange,提问作者Wilson Jaramillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:42:59