Android Study

Android Bluetooth Receiver

85chong 2022. 11. 1. 12:25
728x90
반응형
SMALL

- 작업 내용 -

 

1. 블루투스 상태 (켜짐 /  꺼짐 / 지원가능여부)

2. 페어링된 디바이스 name , address 값 추출

3. 디바이스 현재 연결 상태 값 추출

(* class 에 BroadCastReceiver 상속 받아서 사용 하는 방법 외에 코드에서 직접 등록하여 사용 하는 방법)

 

 

- 상세 내용 -

 

1. receiver 작성

//BlueTooth Receiver
private var bluetoothreceiver = object : BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) {
        var state = intent?.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
        Log.d("YCK_TRACKING","onReceive() / state : ${state}")
        val action = intent!!.action
        Log.d("YCK_TRACKING","onReceive() / action : ${action}")
        if (context == null) return
        if (ActivityCompat.checkSelfPermission(context!!,Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return
        val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)!!
        Log.d("YCK_TRACKING","onReceive() / device.name : ${device.name}")
        Log.d("YCK_TRACKING","onReceive() / device.type : ${device.type}")
    }
}

 

 

2. register 준비

fun register(){
    if (context == null) return
    context.registerReceiver(bluetoothreceiver, addFilterAction())
}

 

 

3.  bluetoothadapter 초기화

fun initBluetoothAdapter(){
    if ( blueToothAdapter == null ){
        val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        blueToothAdapter = bluetoothManager.getAdapter()
    }
}

 

 

4. 페어링된 디바이스 정보 가져오기

//페어링된 디바이스 정보 가져오기
fun getPairedDevices() {
    if (blueToothAdapter == null ) return
    val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    blueToothAdapter = bluetoothManager.getAdapter()
    if (ActivityCompat.checkSelfPermission(context,Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return
    var pairedDevices = blueToothAdapter!!.bondedDevices
    if (pairedDevices.size > 0) {
        pairedDevices.forEach { i ->
            //bondState : 12 (페어링 등록된 상태)
            //bondState : 10 (페어링 등록 안됨)
            Log.e("YCK_TRACKING","getPairedDevices() / name : ${i.name}")
            Log.e("YCK_TRACKING","getPairedDevices() / bondState : ${i.bondState}")
        }
    }
}

 

 

5. 블루투스 상태값 가져오기

//블루투스 상태(켜짐 / 꺼짐 / 지원 불가 기기)
fun blueToothState(): String {
    if (blueToothAdapter != null) {
        if (blueToothAdapter!!.isEnabled) {
            return BLUETOOTH_STATE.ENABLED.statestr
        } else {
            return BLUETOOTH_STATE.DISABLED.statestr
        }
    }
    return BLUETOOTH_STATE.NOT_SUPPORT.statestr
}

 

6. addAction 준비

//add Receive action
private fun addFilterAction(): IntentFilter {
    val stateFilter = IntentFilter()
    stateFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED) //BluetoothAdapter.ACTION_STATE_CHANGED : 블루투스 상태변화 액션
    stateFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)
    stateFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED) //연결 확인
    stateFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) //연결 끊김 확인
    /*
    stateFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
    stateFilter.addAction(BluetoothDevice.ACTION_FOUND) //기기 검색됨
    stateFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED) //기기 검색 시작
    stateFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) //기기 검색 종료
    stateFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
    */
    return stateFilter
}

 

 

7. unregister 준비

fun unregister(){
    if (context == null) return
    context.unregisterReceiver(bluetoothreceiver)
}

 

 

 

 

- 전체 코드 -

enum class BLUETOOTH_STATE(val statestr: String) {
    ENABLED("enabledBlutooth"),
    DISABLED("disableBlutooth"),
    NOT_SUPPORT("notSupport")
}

var context: Context
var blueToothAdapter:BluetoothAdapter? = null

init {
    this.context = context
}

fun initBluetoothAdapter(){
    if ( blueToothAdapter == null ){
        val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        blueToothAdapter = bluetoothManager.getAdapter()
    }
}

fun register(){
    if (context == null) return
    context.registerReceiver(bluetoothreceiver, addFilterAction())
}

fun unregister(){
    if (context == null) return
    context.unregisterReceiver(bluetoothreceiver)
}

//페어링된 디바이스 정보 가져오기
fun getPairedDevices() {
    if (blueToothAdapter == null ) return
    val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    blueToothAdapter = bluetoothManager.getAdapter()
    if (ActivityCompat.checkSelfPermission(context,Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return
    var pairedDevices = blueToothAdapter!!.bondedDevices
    if (pairedDevices.size > 0) {
        pairedDevices.forEach { i ->
            //bondState : 12 (페어링 등록된 상태)
            //bondState : 10 (페어링 등록 안됨)
            Log.e("YCK_TRACKING","getPairedDevices() / name : ${i.name}")
            Log.e("YCK_TRACKING","getPairedDevices() / bondState : ${i.bondState}")
        }
    }
}

//블루투스 상태(켜짐 / 꺼짐 / 지원 불가 기기)
fun blueToothState(): String {
    if (blueToothAdapter != null) {
        if (blueToothAdapter!!.isEnabled) {
            return BLUETOOTH_STATE.ENABLED.statestr
        } else {
            return BLUETOOTH_STATE.DISABLED.statestr
        }
    }
    return BLUETOOTH_STATE.NOT_SUPPORT.statestr
}

//add Receive action
private fun addFilterAction(): IntentFilter {
    val stateFilter = IntentFilter()
    stateFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED) //BluetoothAdapter.ACTION_STATE_CHANGED : 블루투스 상태변화 액션
    stateFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)
    stateFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED) //연결 확인
    stateFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) //연결 끊김 확인
    /*
    stateFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
    stateFilter.addAction(BluetoothDevice.ACTION_FOUND) //기기 검색됨
    stateFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED) //기기 검색 시작
    stateFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) //기기 검색 종료
    stateFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
    */
    return stateFilter
}

//BlueTooth Receiver
private var bluetoothreceiver = object : BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) {
        var state = intent?.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
        Log.d("YCK_TRACKING","onReceive() / state : ${state}")
        val action = intent!!.action
        Log.d("YCK_TRACKING","onReceive() / action : ${action}")
        if (context == null) return
        if (ActivityCompat.checkSelfPermission(context!!,Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return
        val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)!!
        Log.d("YCK_TRACKING","onReceive() / device.name : ${device.name}")
        Log.d("YCK_TRACKING","onReceive() / device.type : ${device.type}")
    }
}

 

 

- 사용법 - 

class MainActivity: AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /* @author : Chungkeun, @since : 2022-10-31_오후 12:40 */
        var blutoothManager = BluetoothBroadcast(this)
        blutoothManager?.register()
        blutoothManager?.initBluetoothAdapter()
        blutoothManager?.blueToothState()
        blutoothManager?.getPairedDevices()
    }
}

 

 

 - 끝 -