Connecting to a GATT Server

원하는 BluetoothDevice 객체를 발견하면

Context 객체, BLE 장치에 자동으로 연결할지 여부를 나타내는 부울 및

연결 이벤트 및 클라이언트 작업이있는 BluetoothGattCallback 참조를

매개 변수로 사용하는 connectGatt() 메서드를 사용하여 연결할 수 있습니다.

1
2
3
4
5
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
device.connectGatt(context, false, bluetoothGattCallback, BluetoothDevice.TRANSPORT_AUTO);
} else {
device.connectGatt(context, false, bluetoothGattCallback);
}

연결 끊김 이벤트를 수신하려면 BluetoothGattCallback의 onConnectionStateChange를 Override 하세요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 BluetoothGattCallback bluetoothGattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "Connected to GATT server.");

} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

Log.i(TAG, "Disconnected from GATT server.");
}
}
};
공유하기