///
Search
🏏

02.(220428)Kotlin toggle 버튼을 활용한 bluetooth on/off 하기

출처

소스코드 설명

토글 버튼을 먼저 만드는 일을 시작하자.
핵심코드
<ToggleButton android:id="@+id/ble_on_off_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.31" />
XML
복사
디자인 편집은 오른쪽 상단에 있는 탭을 눌러서 할 수 있으니 참고하자

/app/res/layout/activaty_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"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ToggleButton android:id="@+id/ble_on_off_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.31" /> </androidx.constraintlayout.widget.ConstraintLayout>
XML
복사
어플리케이션에서 블루투스 기능을 사용하려면 두 개의 권한을 선언해야 한다.
BLUETOOTH는 연결 요청, 연결 수락 및 데이터 전송과 같은 블루투스 통신을 수행하는데 필요하다.
ACCESS_FINE_LOCATION은 블루투스 스캔을 사용하여 사용자 위치에 대한 정보를 수집할 수 있다. 이 정보는 사용자 본인의 기기에서 가져올 수도 있고, 상점 및 교통 시설과 같은 위치에서 사용 중인 블루투스 비콘에서 가져올 수도 있다.
앱에서 기기 검색을 시작하거나 블루투스 설정을 조작하려면 BLUETOOTH 권한외에 BLUETOOTH_ADMIN 권한도 선언해야한다. 대부분 애플리케이션은 로컬 블루투스 기기를 검색하는 기능에만 이 권한이 필요하다. 어플리케이션이 사용자 요청 시 블루투스 설정을 수정하는 '파워 관리자'가 아닌 경우 이 권한이 부여하는 다른 기능을 사용해서는 안된다.
핵심코드
<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" />
XML
복사

/app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.a220428_1114_bluetooth"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.220428_1114_bluetooth" > <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <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" /> </manifest>
XML
복사

/app/src/main/java/com/example/a220428_1114_bluetooth/MainActivity.kt

package com.example.a220428_1114_bluetooth 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() } } } }
Kotlin
복사
이걸 사용하게 된다면 어플내 버튼으로 블루투스를 on/off 할 수 있다.

문의 : yklovejesus@gmail.com