声明
lateinit var bluetoothAdapter: BluetoothAdapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
方法
// 是否开启蓝牙
bluetoothAdapter.isEnabled
// 开始扫描附近蓝牙设备
bluetoothAdapter.startDiscovery()
// 注册和销毁扫描广播
val intentFilter = IntentFilter(BluetoothDevice.ACTION_FOUND)
registerReceiver(broadcastReceiver, intentFilter)
unregisterReceiver(broadcastReceiver)
var broadcastReceiver = object : BroadcastReceiver() {
@SuppressLint("MissingPermission")
override fun onReceive(context: Context?, intent: Intent?) {
if (intent != null) {
when (intent.action) {
BluetoothDevice.ACTION_FOUND -> {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
val device: BluetoothDevice? =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
val deviceName = device?.name
val deviceHardwareAddress = device?.address // MAC address
if (deviceName != null) {
if (device !in devices) {
devices.add(device)
println(deviceName)
println(deviceHardwareAddress)
scanTv.append(deviceName + '\n')
scanTv.append(deviceHardwareAddress + '\n')
}
}
}
}
}
}
}
// 连接蓝牙设备并通讯(SPP蓝牙串口型)
val connectThread = ConnectThread(device);
connectThread.start()
private inner class ConnectThread(device: BluetoothDevice) : Thread() {
private val mmSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
}
@RequiresApi(Build.VERSION_CODES.M)
override fun run() {
// Cancel discovery because it otherwise slows down the connection.
bluetoothAdapter.cancelDiscovery()
mmSocket?.let { socket ->
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
socket.connect()
println("socket.connect()")
var connectedThread=ConnectedThread(socket)
connectedThread.start()
sendBtn.setOnClickListener{
connectedThread.write("123".toByteArray())
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
// manageMyConnectedSocket(socket)
}
}
// Closes the client socket and causes the thread to finish.
fun cancel() {
try {
mmSocket?.close()
} catch (e: IOException) {
println("Could not close the client socket")
}
}
}
private inner class ConnectedThread(var mmSocket: BluetoothSocket) : Thread() {
private val mmInStream: InputStream?
private val mmOutStream: OutputStream?
override fun run() {
val buffer = ByteArray(1024) // buffer store for the stream
var bytes: Int // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
bytes = mmInStream!!.read(buffer)
val readMessage = String(buffer, 0, bytes)
println(readMessage)
} catch (e: IOException) {
break
}
}
}
/* Call this from the main activity to send data to the remote device */
fun write(bytes: ByteArray?) {
try {
mmOutStream?.write(bytes)
} catch (e: IOException) {
}
}
/* Call this from the main activity to shutdown the connection */
fun cancel() {
try {
mmSocket.close()
} catch (e: IOException) {
}
}
init {
var tmpIn: InputStream? = null
var tmpOut: OutputStream? = null
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = mmSocket.inputStream
tmpOut = mmSocket.outputStream
} catch (e: IOException) {
}
mmInStream = tmpIn
mmOutStream = tmpOut
}
}
权限
<!-- Permission-->
<uses-permission
android:name="android.permission.BLUETOOTH"
tools:remove="android:maxSdkVersion" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />