【发布时间】:2020-09-28 05:26:35
【问题描述】:
这是 MainActivity.Kt 文件,我正在关注 Android 开发人员文档,我无法弄清楚为什么它无法连接,我是一个绝对新手,请帮助。
我已经尝试了可发现性和绑定并获取所有绑定的设备,它工作正常,但我无法连接,我直接使用设备的 MAC 地址来帮助简化事情,但仍然没有任何工作,所有权限也是在 Manifest、BT、BT_ADMIN 和 LOCATION 中设置。谢谢
package com.example.btconnection
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException
import java.util.*
class MainActivity : AppCompatActivity() {
val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
val REQUEST_ENABLE_BT = 1
val MY_UUID: UUID = UUID.fromString("00000000-0000-1000-8000-00805F9B34FB")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (bluetoothAdapter == null) {
Toast.makeText(this, "Device Doesn't support BT", Toast.LENGTH_SHORT).show()
}
else{
if (!bluetoothAdapter.isEnabled) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
}
connectbutton.setOnClickListener {
ConnectThread(bluetoothAdapter!!.getRemoteDevice("00:19:10:08:4D:F0"))
}
}
private inner class ConnectThread(device: BluetoothDevice) : Thread() {
private val mmSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
device.createRfcommSocketToServiceRecord(MY_UUID)
}
override fun run() {
// Cancel discovery because it otherwise slows down the connection.
bluetoothAdapter?.cancelDiscovery()
mmSocket?.use { socket ->
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
socket.connect()
Toast.makeText(this@MainActivity, "Connected", Toast.LENGTH_SHORT).show()
// 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) {
Log.e("Error", "Could not close the client socket", e)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == REQUEST_ENABLE_BT){
if (resultCode == Activity.RESULT_OK){
if(bluetoothAdapter!!.isEnabled){
Toast.makeText(this,"BT Enabled", Toast.LENGTH_SHORT).show()
}
else{
Toast.makeText(this,"BT Disabled", Toast.LENGTH_SHORT).show()
}
}
else if(resultCode == Activity.RESULT_CANCELED){
Toast.makeText(this,"BT Enable Cancelled", Toast.LENGTH_SHORT).show()
}
}
}
}
【问题讨论】:
-
HC-05服务不是
00001101-0000-1000-8000-00805f9b34fb吗?这官方称为Serial Port Profile (SPP),但Android 将其称为RFCOMM
标签: android kotlin arduino bluetooth