Android使用BluetoothManager#getConnectionState

时间:2018-02-28 15:27:17

标签: android bluetooth appcelerator-titanium

我正在为appcelerator-titanium编写一个android ble模块,并且在与蓝牙设备成功连接后,我在方法中使用了BluetoothGatt对象。但是,我想检查连接的当前状态。

我试图使用:

public BluetoothGatt gatt;
private BluetoothDevice device;

@Kroll.method
public void discoverServices(){
    Log.i("PeripheralProxy", "discoverServices");
    if(gatt!=null){
        Log.i("PeripheralProxy", "Gatt is true discoverServices");
        try {
            if(device!=null){
                int connectionState= gatt.getConnectionState(device);

                Log.i("PeripheralProxy", "Device is not null");
            } else {
                Log.e("PeripheralProxy", "Device is null");
            }
        } catch (Exception e){
            Log.e("PeripheralProxy",e.getMessage());
        }
        //DISCOVER SERVICES
        boolean discoverResult = gatt.discoverServices();
        Log.i("PeripheralProxy", Boolean.toString(discoverResult));

    } else {
        Log.e("PeripheralProxy", "Gatt is null on discoverServices");
    }
}

但是控制台返回以下异常: [ERROR] PeripheralProxy:(KrollRuntimeThread)[1,282875]请改用蓝牙管理器#getConnectionState。

但在这种情况下,我无法访问BluetoothManager。如何从BluetoothGatt对象获取连接状态?

在Android文档中他们有这个方法BluetoothGatt.getConnectionState(BluetoothDevice device) 访问:https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getConnectionState(android.bluetooth.BluetoothDevice)

但他们也说:不支持 - 请使用带有GATT的getConnectedDevices(int)作为参数。然而,这个功能再次要求我在这种情况下无法访问的蓝牙管理器。 访问:https://developer.android.com/reference/android/bluetooth/BluetoothManager.html#getConnectedDevices(int)

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

为什么不能使用

ble_manager=(BluetoothManager)getSystemService(BLUETOOTH_SERVICE);

然后您可以使用getConnectionState()方法。此对象应始终可用,因为BLUETTOTH_SERVICE是Context的一部分。