[Android] 블루투스 : 페어링과 연결

undefined·2024년 6월 19일
0

Android

목록 보기
4/6

이번 프로젝트를 진행하면서 블루투스기능을 사용하게 되었는데, 페어링과 연결, 관련 상태들이 헷갈려서 정리해두려고 한다.

페어링과 연결

페어링

  • 두 블투 기기가 서로 인식하고 인증하는 과정
  • 페어링된 기기는 장치 목록에 저장되어서 나중에 인증없이 쉽게 연결 가능

연결

  • 페어링 된 두 기기가 데이터 주고받을 수 있게 통신채널 설정하는 과정
  • 연결은 페어링 후 가능한데, 페어링 되어있더라도 연결되어있는 상태가 아닐 수 있음.

관련 객체, 상태값들

BluetoothAdapter

블루투스 활성화나 디바이스 검색 등 전체적인 블루투스 기능을 제공하는 클래스

  • STATE_OFF: 블루투스가 비활성화된 상태
  • STATE_TURNING_ON: 블루투스가 활성화되는 중
  • STATE_ON: 블루투스가 활성화되고 사용 가능한 상태
  • STATE_TURNING_OFF: 블루투스가 비활성화되는 중

BluetoothDevice

검색된 주변 장치들을 나타내는 클래스로 장치 정보를 얻거나 연결 시도할 수 있음.

  • BOND_NONE: 장치와 페어링되지 않은 상태
  • BOND_BONDED: 장치와 페어링된 상태
  • BOND_CONNECTING: 장치와 연결하는 중
  • BOND_DISCONNECTED: 장치와 연결이 끊어짐

BluetoothConnection

실제 데이터 전송을 위한 연결관련 기능 제공.

  • STATE_DISCONNECTED: 연결 끊김
  • STATE_CONNECTING: 연결 시도중
  • STATE_CONNECTED: 연결된 상태
  • STATE_DISCONNECTING: 연결을 끊는중

블루투스 연결 예제

나중에 또 찾아볼 것 같아서 사용했던 코드 스니펫도 남겨둔다.

  1. 블루투스로 연결할 디바이스를 스캔하는 방법

    1. BluetoothManager를 통해 adapter에 대한 참조를 얻는다.

      val bluetoothManager: BluetoothManager =
          requireContext().getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
              ?: throw Exception("Bluetooth is not supported by this device")
      mBtAdapter = bluetoothManager.adapter
    2. mBtAdapter.bondedDevices로 기존에 페어링 된 디바이스 목록을 가져온다.

      mBtAdapter.bondedDevices.toList().forEach {
          viewModel.updateConnectableList(it)
      }
    3. 새로운 페어링 가능한 디바이스를 찾는다.

      mBtAdapter.startDiscovery()
    4. startDiscovery()를 호출하면 이에 대한 응답을 브로드캐스트 리시버로 받을 수 있다.

      inner class BluetoothDeviceReceiver : BroadcastReceiver() {
          @SuppressLint("MissingPermission")
          override fun onReceive(context: Context, intent: Intent) {
              Timber.tag("bluetooth").d(intent.action.toString())
              when (intent.action) {
                  BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                      viewModel.scanning.postValue(false)
                  }
      
                  BluetoothDevice.ACTION_FOUND -> {
                      val device =
                          intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                      if (device != null) {
                          updatePairedDevicesList(device)
                      }
                  }
              }
          }
      }
  2. 디바이스와 연결하기

    1. 디바이스 연결요청에 대한 응답을 받을 콜백을 구현한다.
    	private val callback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            super.onConnectionStateChange(gatt, status, newState)
            when (newState) {
                STATE_CONNECTED -> {
                    // 연결됨
                }
    
                STATE_DISCONNECTED -> {
                    // 연결 해제
                }
    
                else -> {
    
                }
            }
        }
    }
    1. 디바이스에 연결을 요청한다
    selectedDevice.connectGatt(requireContext(), true, callback).connect()

    대략 이런 식으로 사용했다.

profile
이것저것 하고 싶은 게 많은 병아리 개발자

0개의 댓글