본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 블루투스 On/Off 제어하기

by teamnova 2021. 9. 5.

오늘은 블루투스를 설정창에서 제어하는게 아닌 

 

저희가 만든 앱 내에서 제어하는 기능을 만들어 보도록 하겠습니다.

 

너무 당연히 사용하던 블루투스가 어떤 기술인지 궁금하지 않으세요? 

 


블루투스란 무엇일까요?

 

 

블루투스란 휴대폰, 노트북, 이어폰, 헤드폰등의 휴대기기를 서로 연결하여 정보를 교환하는 근거리 무선 기술(10M이내)의 표준을 뜻합니다.

 

블루투스의 무선 시스템은 ISM(Industrial Scientific and Medical) 주파수 대역인 2400~2483.5MHz를 사용 하고 있습니다. 이중에서 위 아래 주파수를 쓰는 다른 시스템의 간섭을 막기 위해서 2400MHz 이후 2MHz, 2483.5MHz 이전 3.5MHz까지의 범위를 제외한 2400MHz 이후 2483.5MHz 이전 3.5MHz까지의 범위를 제외한 2402~2480MHz, 총 79개 채널을 사용하고 있습니다.

여기서 ISM이란 산업, 과학, 의료용으로 할당된 주파수 대역으로서 전파 사용에 대한 허가가 필요없는 개인 무전기에 많이 사용하고 있고 아마추어 무선, 무선랜, 블루투스가 이 ISM에 해당 합니다.

블루투스는 같은 주파수 대역을 사용하기에 서로간의 전파 간섭이 생길 수 있는데 이를 예방하기 위해서 주파수 호핑(Frequency Hopping)을 사용는데 주파수 호핑이란 많은 수의 채널을 특정 패턴에 따라서 빠르게 이동하여 데이터를 조금씩 전송하는 방식입니다.

블루투스는 기기간에 동기화가 되어야만 작동하게 되어 있는데 마스터와 슬레이브 구성으로 연결 됩니다. 마스터와 슬레이브와의 동기화외에 슬레이브-슬레이브간의 통신은 불가합니다.

 

블루투스 장점 및 단점

 

블루투스의 장점이라고 한다면 남녀 노소 누구나 손쉽고 간편하게 사용이 가능한점이 장점이나, 단점으로는 거리의 제약이 있으며, 보완에 취약한점 그리고 음질이 일반 와이파이 방식에 비해 떨어지는 단점이 있습니다.


https://stickode.com/detail.html?no=2401

 

스틱코드

 

stickode.com

 

 

 1. Bluetooth 권한 등록

 

어플리케이션에서 블루투스 기능을 사용하려면 두 개의 권한을 선언해야 한다.

BLUETOOTH는 연결 요청, 연결 수락 및 데이터 전송과 같은 블루투스 통신을 수행하는데 필요하다.

ACCESS_FINE_LOCATION은 블루투스 스캔을 사용하여 사용자 위치에 대한 정보를 수집할 수 있다. 이 정보는 사용자 본인의 기기에서 가져올 수도 있고, 상점 및 교통 시설과 같은 위치에서 사용 중인 블루투스 비콘에서 가져올 수도 있다.

 

앱에서 기기 검색을 시작하거나 블루투스 설정을 조작하려면 BLUETOOTH 권한 외에 BLUETOOTH_ADMIN 권한도 선언해야한다. 대부분 애플리케이션은 로컬 블루투스 기기를 검색하는 기능에만 이 권한이 필요하다. 어플리케이션이 사용자 요청 시 블루투스 설정을 수정하는 '파워 관리자'가 아닌 경우 이 권한이 부여하는 다른 기능을 사용해서는 안된다.

 

★ 참고 : 어플리케이션이 Android9 (API 레벨 28) 이하를 대상으로 하는 경우 ACCESS_FINE_LOCATION 권한 대신 ACCESS_COARSE_LOCATION 권한을 선언할 수 있다.

 

 

Manifest.xml

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- If your app targets Android 9 or lower, you can declare
ACCESS_COARSE_LOCATION instead. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

 

activity_main.xml                                                                                                                                 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ble_on_off_btn"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

먼저 bluetooth defaultAdapter를 전역변수에 저장한다.

Bluetooth가 켜져있으면 어플 실행 시 Toggle Button의 텍스트가 On으로, Bluetooth가 꺼져있으면 어플 실행 시 Toggle Button의 텍스트가 Off로 표시된다. Toggle Button을 누르면 전역변수에 저장된 bluetoothAdapter를 통해, 현재 기기가 Bluetooth 기능을 지원하는지 확인 후, 지원하면 Toggle 버튼의 상태에 따라서 Bluetooth를 On/Off 한다.

                                                                                                                                                        MainActivity.kt                        

import android.bluetooth.BluetoothAdapter
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ToggleButton

class MainActivity : AppCompatActivity() {
    private val REQUEST_ENABLE_BT=1
    private var bluetoothAdapter: BluetoothAdapter? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val bleOnOffBtn:ToggleButton = findViewById(R.id.ble_on_off_btn)
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

        if(bluetoothAdapter!=null){
            // Device doesn't support Bluetooth
            if(bluetoothAdapter?.isEnabled==false){
                bleOnOffBtn.isChecked = true
            } else{
                bleOnOffBtn.isChecked = false
            }
        }

        bleOnOffBtn.setOnCheckedChangeListener { _, isChecked ->
            bluetoothOnOff()
        }

    }
    fun bluetoothOnOff(){
        if (bluetoothAdapter == null) {
            // Device doesn't support Bluetooth
            Log.d("bluetoothAdapter","Device doesn't support Bluetooth")
        }else{
            if (bluetoothAdapter?.isEnabled == false) { // 블루투스 꺼져 있으면 블루투스 활성화
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
            } else{ // 블루투스 켜져있으면 블루투스 비활성화
                bluetoothAdapter?.disable()
            }
        }
    }
}