This is the sixth day of my participation in the August Text Challenge.More challenges in August

  • ‘s note | MobPush access
  • Gradle Notes the basic build configurations I have used.
  • Git’s note | summarize personal daily development to some of the commonly used commands (update…
  • Utils’s note | Android Studio plug-in finishing (update…
  • Notes | Kotlin base type review
  • Android gets the paired Bluetooth list and connected Bluetooth name

To tell you the truth, I want to mix a cup, the cup was broken by the cat.

sequence

Recently, I happened to have bluetooth requirements for the project, so I took a while to record it

A lot of online search to the article can not use, embarrassing death… Or the Java version, it’s a bit of a mess to convert Kotlin, but it reinforces the idea of learning Kotlin

Attached brain map:

Demo GitHub address

  • Github.com/HLQ-Struggl…

Bluetooth is briefly

With the advent of Bluetooth, mobile devices now have a way to exchange data, and Android applications can use the Bluetooth Api to do the following:

  • Scan for other Bluetooth devices
  • Query the paired Bluetooth devices of the local Bluetooth adapter
  • Set up the RFCOMM channel
  • Discover connections to other devices through the service
  • Two-way data transmission with other devices
  • Managing Multiple Connections

And today, we are mainly for the second point, query the local Bluetooth adapter pair bluetooth device.

Traditional Bluetooth is suitable for power-hungry operations, including streaming and communication between Android devices. For bluetooth devices with low power requirements, Android 4.3 (API 18) introduces low power Bluetooth API support.

1. Basic knowledge

In order for Bluetooth devices to transmit data to each other, they must first form a channel through the pairing process.

One device needs to set itself up to receive incoming connection requests, and the other device uses the service discovery process to find detectable devices.

After the detected device accepts the pairing request, the binding operation is completed between the devices, during which the security key is exchanged. Both cache these keys for later use.

After pairing and binding, the two devices exchange information.

When the session is complete, the device that initiated the pairing request links it to a channel that can detect the device.

And the two devices remain bound, so they will automatically connect during future sessions as long as they are within range of each other and both are unbound.

2. Bluetooth access

Base permissions must be declared:

<uses-permission android:name="android.permission.BLUETOOTH" />
Copy the code

If you want to perform bluetooth operations, such as enabling Bluetooth, you need to configure the following permissions:

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
Copy the code

To scan other devices, you need to declare the following permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Copy the code

Note here:

  • If the application is compatible with Android 9 (Api 28) or lower, you can declare ACCESS_COARSE_LOCATION instead of ACCESS_FINE_LOCATION.

If you want to declare that the current application is still available on devices that do not support BLE, you need to add the following elements to the permissions:

<uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>
Copy the code

Bluetooth Demo up (get pairing list and connected Bluetooth name)

1. Essential permissions

<uses-permission android:name="android.permission.BLUETOOTH" />
Copy the code

2. Tool classes

package com.hlq.bluetoothpro.utils import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothProfile import android.content.Context import android.media.AudioManager import Android. Util. The Log import Java. Lang. Reflect. InvocationTargetException / * * * @ author: HLQ_Struggle * @ the date: 2021/8/29 * @desc: */ private var mBluetoothAdapter: BluetoothAdapter? = null /** * instantiate BluetoothAdapter */ private fun getInstance(): BluetoothAdapter? { if (mBluetoothAdapter == null) { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter() } return mBluetoothAdapter } /** * Check whether the device supports Bluetooth */ fun checkoothenable (): Boolean {return getInstance () = = null} / judge whether the current bluetooth open * * * * / fun checkBluetoothStateEnable () : Boolean { return getInstance()? .isEnabled == true} / private fun isWiredHeadsetConnected(context: context): Boolean { try { val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager return audioManager.isWiredHeadsetOn } catch (e: Exception) {} return false} /** * Check whether bluetooth headset is connected */ hasBluetoothAudioDevice(): Boolean { val adapter = BluetoothAdapter.getDefaultAdapter() var a2dp = false var headset = false try { a2dp = adapter.getProfileConnectionState(BluetoothProfile.A2DP) ! = BluetoothProfile.STATE_DISCONNECTED headset = adapter.getProfileConnectionState(BluetoothProfile.HEADSET) ! = BluetoothProfile.STATE_DISCONNECTED } catch (e: Throwable) {} return a2dp | | headset} / * * * get paired successfully bluetooth device * / fun fetchAlReadyConnection () {getInstance ()? .let { val devices = it.bondedDevices for (device in devices) { Log.e( "HLQ", "----> " + "name ${device.name} " + "address ${device.address} " + "bondState ${device.bondState} " + "type ${device.type} ${device.uuids.size}" ) } } } fun getConnectedBtDevice(): String? {/ / get the bluetooth adapter val bluetoothAdapter = bluetoothAdapter. GetDefaultAdapter () / / get the matched to the bluetooth device list val bondedDevices = bluetoothAdapter.bondedDevices if (bondedDevices ! = null && bondedDevices.size > 0) {for (bondedDevice in bondedDevices) {try {// Call the hidden method val isConnectedMethod = BluetoothDevice::class.java.getDeclaredMethod( "isConnected" ) isConnectedMethod.isAccessible = true val isConnected = isConnectedMethod.invoke(bondedDevice) as Boolean if (isConnected) { return bondedDevice.name } } catch (e: NoSuchMethodException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } catch (e: InvocationTargetException) { e.printStackTrace() } } } return null }Copy the code

3. Create listening Bluetooth broadcast

package com.hlq.bluetoothpro.receiver import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice  import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.util.Log import com.hlq.bluetoothpro.utils.checkBluetoothStateEnable import com.hlq.bluetoothpro.utils.fetchAlReadyConnection import com.hlq.bluetoothpro.utils.getConnectedBtDevice import Com. HLQ. Bluetoothpro. Utils. HasBluetoothAudioDevice / * * * @ author: HLQ_Struggle * @ date: 2021/8/28 * @ desc:  */ class BluetoothReceiver : BroadcastReceiver() { companion object { fun registerIntentFilter(): IntentFilter { val intentFilter = IntentFilter() intentFilter.apply { addAction(BluetoothAdapter.ACTION_STATE_CHANGED); / / bluetooth state change addAction (" android. Bluetooth. BluetoothAdapter. STATE_OFF "); / / the local bluetooth adapter closed addAction (" android. Bluetooth. BluetoothAdapter. STATE_ON "); // BluetoothDevice.action_acl_connected is enabled and addAction(bluetoothdevice.action_acl_connected) is available. // Bluetoothdevice.action_acl_disconnected addAction(bluetoothdevice.action_acl_disconnected); Priority = int. MAX_VALUE} return intentFilter}} Override fun onReceive(context: context? , intent: Intent?) { val action = intent? .action action ? : Return val bluetoothLog = when (action) {BluetoothAdapter.ACTION_STATE_CHANGED -> {// Listen for bluetooth status when (val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)) {bluetoothAdapter. STATE_TURNING_ON -> {"STATE_TURNING_ON Bluetooth enabled "} bluetoothAdapter. STATE_ON -> {"STATE_ON Bluetooth enabled "} BluetoothAdapter.STATE_CONNECTING -> {"STATE_CONNECTING bluetooth connection "} BluetoothAdapter.STATE_CONNECTED -> { "STATE_CONNECTED Bluetooth connection "}, BluetoothAdapter.STATE_DISCONNECTING -> {"STATE_DISCONNECTING Bluetooth connection "} Bluetoothadapter. STATE_DISCONNECTED -> {"STATE_DISCONNECTED bluetooth "} bluetoothadapter. STATE_TURNING_OFF -> { "STATE_TURNING_OFF Bluetooth off "} BluetoothAdapter.STATE_OFF -> {"STATE_OFF Bluetooth off "} else -> "ACTION_STATE_CHANGED EXTRA_STATE $state"}} bluetoothdevice. ACTION_ACL_CONNECTED -> {bluetoothdevice. e("HLQ", "-- -- -- -- > ACTION_ACL_CONNECTED bluetooth connected") / / bluetooth is open and connected the e (" HLQ ", "-- -- -- -- > bluetooth is open and connected") the e (" HLQ." "-- -- -- -- > output has bluetooth pairing list") the e (" HLQ ", "-- -- -- - > ${fetchAlReadyConnection ()}") "-- -- -- - > the current connection bluetooth name: ${getConnectedBtDevice()}"} bluetoothdevice. ACTION_ACL_DISCONNECTED -> "ACTION_ACL_DISCONNECTED "} else -> "action $action" } Log.e("HLQ", "----> bluetoothLog $bluetoothLog") } }Copy the code

4. Bluetooth registration, removal and acquisition

package com.hlq.bluetoothpro import android.content.IntentFilter import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.hlq.bluetoothpro.receiver.BluetoothReceiver import com.hlq.bluetoothpro.utils.* class MainActivity : Appactivity () {/** * Bluetooth listen for driving mode */ private var mBluetoothFilter: IntentFilter? = null private var mBluetoothReceiver: BluetoothReceiver? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) handleBluetooth() } private fun HandleBluetooth () {// Verify that the current device supports Bluetooth support to initialize if (! checkBluetoothEnable()) { Log.e("HLQ", "-- -- -- - > the current equipment support bluetooth") initBluetooth () if (checkBluetoothStateEnable () && hasBluetoothAudioDevice ()) {/ / bluetooth is open and connected The e (" HLQ ", "-- -- -- -- > bluetooth is open and connected") the e (" HLQ ", "-- -- -- -- > output has bluetooth pairing list") the e (" HLQ." "-- -- -- - > ${fetchAlReadyConnection ()}") the e (" HLQ ", "-- -- -- - > the current connection bluetooth name: ${getConnectedBtDevice()}")}} / private fun initBluetooth() {if (mBluetoothReceiver == null) { mBluetoothReceiver = BluetoothReceiver() } if (mBluetoothFilter == null) { mBluetoothFilter = BluetoothReceiver.registerIntentFilter() } if (mBluetoothReceiver ! = null && mBluetoothFilter ! = null) { registerReceiver(mBluetoothReceiver, MBluetoothFilter)} override fun onDestroy() {super.ondestroy () // Clean up bluetooth broadcast if (mBluetoothReceiver! = null) { unregisterReceiver(mBluetoothReceiver) mBluetoothReceiver = null } } }Copy the code

Come on, log show

  • When Bluetooth is enabled and Bluetooth is connected
E/HLQ: ----> Current device supports Bluetooth E/HLQ: ----> Output bluetooth pairing list E/HLQ: ----> Bluetooth enabled and connected E/HLQ: ----> name Earbuds X1 address E0:9D:FA:CA:4C:DF bondState 12 Type 1 3E /HLQ: ----> Currently connected Bluetooth name: Earbuds X1Copy the code
  • When Bluetooth is turned on and starts to connect to Bluetooth (it is automatically connected after pairing successfully before)
E/HLQ: ----> Current device supports Bluetooth E/HLQ: ----> Bluetooth enabled and connected E/HLQ: ----> Output bluetooth pairing list E/HLQ: ----> name Earbuds X1 address E0:9D:FA:CA:4C:DF bondState 12 Type 1 3E /HLQ: ----> Currently connected Bluetooth name: Earbuds X1Copy the code
  • And a bluetooth switch demonstration
E/HLQ: ----> bluetoothLog STATE_TURNING_OFF In E/HLQ: ----> bluetoothLog STATE_OFF in E/HLQ: ----> bluetoothLog STATE_TURNING_ON Bluetooth enabled in E/HLQ: ----> bluetoothLog STATE_ON Bluetooth enabled in E/HLQ: ----> ACTION_ACL_CONNECTED Bluetooth connected E/HLQ: ----> Bluetooth enabled and connected E/HLQ: ----> Output bluetooth pairing list E/HLQ: ----> name Earbuds X1 address E0:9D:FA:CA:4C:DF bondState 12 type 1 3 E/HLQ: ----> kotlin.Unit E/HLQ: ----> bluetoothLog ----> Currently connected Bluetooth name: Earbuds X1Copy the code

THK

  • An overview of the bluetooth
  • Bluetooth Low Power Overview