노하우 안드로이드에 블루투스 LE 장치에 연결 (플랫폼 19)
와 페어링
다음 코드를 사용하여 장치에 연결하려고합니다.
private BluetoothGattCallback callback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
Log.i(TAG, "le onConnectionStateChange ["+newState+"]");
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "le device connected");
onConnect(gatt.getDevice());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i(TAG, "le device disconnected");
onDisconnect(gatt.getDevice());
}
}
@Override
public void onServicesDiscovered (BluetoothGatt gatt, int status) {
Log.i(TAG, "onServicesDiscovered");
}
};
for (BluetoothDevice device : BluetoothAdapter.getDefaultAdapter().getBondedDevices()) {
int type = device.getType();
if (type == BluetoothDevice.DEVICE_TYPE_LE || type == BluetoothDevice.DEVICE_TYPE_DUAL) {
List<BluetoothDevice> connectedDevices =
bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
if (!connectedDevices.contains(device)) {
BluetoothGatt gatt = device.connectGatt(App.getContext(), false, callback);
gatt.connect();
gatt.discoverServices();
List<BluetoothGattService> services = gatt.getServices();
}
}
}
그러나 연결을 시작할 수 없습니다. 잠시 후 (몇 초) 연결 상태 이 BluetoothProfile.STATE_DISCONNECTED로 변경됩니다. 이는 BluetoothProfile.STATE_CONNECTED 에 결코 도달하지 않은 경우에도 마찬가지입니다. 내가 여기서 뭔가 잘못하고있는거야?
장치를 연결하지 않고 연결할 수 있습니다. 실제로 gatt.connect()가 실행됩니까? 사용 가능한 장치가 이미 연결되어 있다고 가정하지 않고 검색을 시작하는 것이 더 일반적입니다. 너도 그걸 시도 할 수있어. –
자세히 보아라, connectedDevices.contains (device). 위의 코드는 보세 장치 목록을 통해 현재 연결되어 있지 않은 장치와의 연결을 설정하려고 시도합니다. 루프의 코드가 실행되고 콜백이 호출되지만 BluetoothProfile에서는 호출되지 않습니다 .STATE_CONNECTED – fabian
위의 설명과는 다른 점은 discoverServices 및 gattServices를 호출하지 않으려는 것입니다. 각 콜백을 기다리고 싶다면 getServices는 아무것도 반환하지 않습니다. 또한 신호 강도와 거리를 감지하기 위해 RSSI를 사용하는 태그에 연결하려고 했으므로 GATT 서버가 얼마나 잘 정의되어 있는지 확신 할 수 없습니다. – Zomb