AndroidStudio Kotlin 连接到蓝牙
创始人
2024-10-10 19:30:50
0

要在Android Studio中使用Kotlin连接到蓝牙设备,可以按照以下步骤进行操作:

  1. 添加权限和特征支持: 在AndroidManifest.xml文件中添加以下权限和特征支持:


  1. 创建蓝牙连接类: 创建一个BluetoothConnection.kt文件,并在其中添加以下代码:
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import java.io.IOException
import java.util.*

class BluetoothConnection(private val device: BluetoothDevice) {
    private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
    private var bluetoothSocket: BluetoothSocket? = null

    fun connect(): Boolean {
        val uuid: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // 需要匹配蓝牙设备的UUID
        return try {
            bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid)
            bluetoothSocket?.connect()
            true
        } catch (e: IOException) {
            false
        }
    }

    fun disconnect() {
        try {
            bluetoothSocket?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}
  1. 在MainActivity中进行蓝牙连接: 打开MainActivity.kt文件,并在其中添加以下代码:
import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
    private val REQUEST_ENABLE_BLUETOOTH = 1
    private val REQUEST_PERMISSION_ACCESS_COARSE_LOCATION = 2
    private lateinit var bluetoothConnection: BluetoothConnection

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 检查设备是否支持蓝牙
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show()
            return
        }

        // 请求打开蓝牙
        if (!bluetoothAdapter.isEnabled) {
            val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH)
        } else {
            setupBluetoothConnection()
            connectToBluetoothDevice()
        }

        // 检查定位权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
                REQUEST_PERMISSION_ACCESS_COARSE_LOCATION
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENABLE_BLUETOOTH && resultCode == RESULT_OK) {
            setupBluetoothConnection()
            connectToBluetoothDevice()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSION_ACCESS_COARSE_LOCATION) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setupBluetoothConnection()
                connectToBluetoothDevice()
            }
        }
    }

    private fun setupBluetoothConnection() {
        val pairedDevices: Set? = bluetoothAdapter?.bondedDevices
        val device: BluetoothDevice? = pairedDevices?.find { it.name == "Your Bluetooth Device Name" } // 替换为你的蓝牙设备名称
        device?.let {
            bluetoothConnection = BluetoothConnection(device)
        }
    }

    private fun connectToBluetoothDevice() {
        if (bluetoothConnection.connect()) {
            Toast.makeText(this, "蓝牙连接成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "蓝牙连接失败", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        bluetoothConnection.disconnect()
    }
}

请注意,上述代码中的“Your Bluetooth

相关内容

热门资讯

2026外挂!雀友会广东潮汕麻... 2026外挂!雀友会广东潮汕麻将辅助软件,芒果辅助器(好像是有挂)1、用户打开应用后不用登录就可以直...
2026外挂!哈糖大菠萝辅助,... 2026外挂!哈糖大菠萝辅助,奇迹手游辅助脚本平台免费(一直真的有挂)1、奇迹手游辅助脚本平台免费脚...
2026外挂!辅助定制交易平台... 2026外挂!辅助定制交易平台,情怀破解(本来有挂)1、起透看视 辅助定制交易平台辅助软件价格2、随...
2026外挂!九酷众游软件,5... 2026外挂!九酷众游软件,510k中至余干辅助(原来真的是有挂)1、玩家可以在510k中至余干辅助...
2026外挂!极速官方游戏暗堡... 2026外挂!极速官方游戏暗堡辅助器,楚天游辅助(其实存在有挂)1、上手简单,内置详细流程视频教学,...
2026外挂!免费游戏辅助软件... 2026外挂!免费游戏辅助软件,如何设置钱塘十三水辅助器(切实是真的有挂)1、2026外挂!免费游戏...
2026外挂!雀姬辅助脚本,微... 2026外挂!雀姬辅助脚本,微乐游戏辅助脚本安装(切实有挂)2026外挂!雀姬辅助脚本,微乐游戏辅助...
2026外挂!飞驰娱乐软件科技... 2026外挂!飞驰娱乐软件科技,科乐填大坑辅助器(切实真的有挂)1、科乐填大坑辅助器免费辅助多个强度...
2026外挂!皮皮胡子辅助,天... 2026外挂!皮皮胡子辅助,天天贵阳破解版(原来是真的有挂)天天贵阳破解版是不是有人用挂微扑克wpk...
2026外挂!科技实测欢乐辅助... 2026外挂!科技实测欢乐辅助,丽水都莱辅助软件(都是是有挂)小薇(辅助器软件下载)致您一封信;亲爱...