首页 > 解决方案 > BluetoothDevice.setPin 未连接

问题描述

我似乎无法让我的应用程序连接到蓝牙设备并以编程方式设置 PIN。

我试过不中止广播,但没有帮助。如果我不实现BroadcastReceiver,它会提示用户输入 PIN 并成功配对。但是,如果我尝试直接设置 PIN,它永远不会起作用。而且我什至尝试将byteArray字符集指定为 UTF-8,但没有任何效果。我什至尝试过手动设置byteArray,但仍然没有。

另外,我已经在 Manifest 中声明了所有必要的权限:

我究竟做错了什么?

class MainActivity: AppCompatActivity() {

    private var broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            var device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
           device?.setPin("1234".toByteArray())
            this.abortBroadcast()
        }}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.devicelist)
        ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
        registerReceiver(broadcastReceiver, IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST))

        findViewById<Button>(R.id.button3).setOnClickListener{
        var ble = BluetoothAdapter.getDefaultAdapter()
        var dev = ble.getRemoteDevice("00:20:04:32:8A:EE")
        dev.createBond()
        }

}}

标签: androidandroid-bluetooth

解决方案


推荐阅读