如何在Delphi Alexandria 11.3 FMX Android BLE中正确调用requestConnectionPriority
Delphi FMX Android BLE: 正确调用requestConnectionPriority方法
核心问题说明
你错误地尝试直接Create和Free TJBluetoothGatt实例,这个类是Delphi对Android原生BluetoothGatt对象的包装,不能手动实例化,它的有效实例只能从BLE连接的回调流程中获取。
正确调用步骤
获取有效JBluetoothGatt实例
在BLE设备连接成功时,系统会在JBluetoothGattCallback的onConnectionStateChange回调中返回已连接的BluetoothGatt对象。你需要在自定义的回调类中处理这个事件,获取并包装实例:type TBluetoothGattCallback = class(TJavaLocal, JBluetoothGattCallback) public procedure onConnectionStateChange(gatt: JBluetoothGatt; status: Integer; newState: Integer); cdecl; end; procedure TBluetoothGattCallback.onConnectionStateChange(gatt: JBluetoothGatt; status: Integer; newState: Integer); var LConnectedGatt: TJBluetoothGatt; begin // 判断连接成功状态 if newState = TJBluetoothProfile.JavaClass.STATE_CONNECTED then begin // 将原生Java对象包装为Delphi可调用的TJBluetoothGatt实例 LConnectedGatt := TJBluetoothGatt.Wrap(gatt); // 调用请求连接优先级方法 LConnectedGatt.requestConnectionPriority(TJBluetoothGatt.JavaClass.CONNECTION_PRIORITY_HIGH); end; end;理解Wrap方法的作用
Wrap方法的作用是将Android原生JNI对象(即Java层的BluetoothGatt实例)转换为Delphi可以直接调用的包装类对象。你之前用Wrap(self)完全错误,因为self是Delphi的本地组件/窗体对象,和Android的BluetoothGatt实例毫无关联。生命周期注意事项
不要手动调用TJBluetoothGatt.Create或Free,这些对象的生命周期由Android系统管理,Delphi包装类仅持有原生对象的引用,手动释放会导致异常。
误区修正
你期望的JBluetoothGatt.requestConnectionPriority(...)是静态调用,但requestConnectionPriority是实例方法,必须在已连接的BluetoothGatt实例上调用,无法直接通过类名调用。
内容的提问来源于stack exchange,提问作者kdu300
相关产品推荐
相关产品推荐

