【问题标题】:I'm trying to build an Android App to connect to a HC-05 bluetooth device using Kotlin, but i cant make it connect我正在尝试构建一个 Android 应用程序以使用 Kotlin 连接到 HC-05 蓝牙设备,但我无法连接
【发布时间】: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()
            }
        }
   
    }
}

【问题讨论】:

标签: android kotlin arduino bluetooth


【解决方案1】:

我终于弄明白了,我仔细观察了 HC-05,发现它连接了 500 毫秒然后断开连接,我发现它在很短的时间后连接然后断开连接,当我检查代码中,函数 'fun cancel()' 在连接后立即关闭套接字。

So the socket remain open for the data stream to be sent out.
now the button only does this


 connectbutton.setOnClickListener {
            btSocket = bluetoothAdapter!!.getRemoteDevice("00:19:10:08:4D:F0").createRfcommSocketToServiceRecord(MY_UUID)
//            ConnectThread(bluetoothAdapter!!.getRemoteDevice("00:19:10:08:4D:F0"))
            try {
            bluetoothAdapter.cancelDiscovery()
            btSocket!!.connect()
                Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show()
            }
            catch (e: Exception){
                Toast.makeText(this, "Can't Connect", Toast.LENGTH_SHORT).show()
            }

        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多