繁体   English   中英

查看Kotlin中的蓝牙设备列表?

[英]View list of bluetooth devices in Kotlin?

我在科特林有一个小型蓝牙项目。 它的代码如下:

   var mArrayAdapter: ArrayAdapter<String>? = null
val bluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
var myList: MutableList<String> = mutableListOf<String>()
var devices = ArrayList<BluetoothDevice>()
var devicesMap = HashMap<String, BluetoothDevice>()

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private val REQUEST_ENABLE_BT = 1000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<View>(R.id.btn_scan).setOnClickListener(this)
        checkBluetoothStatus()
        val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
        registerReceiver(receiver, filter)
        mArrayAdapter = ArrayAdapter(this, R.layout.dialog_select_device)



    }


    private val receiver = object : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            val action: String? = intent.action
            when(action) {
                BluetoothDevice.ACTION_FOUND -> {

                    val device: BluetoothDevice =
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    val deviceName = device.name
                     myList.add(deviceName)
                }
            }
        }
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_scan ->
                startScan()
        }
    }


    fun startScan() {
        if (BluetoothAdapter.getDefaultAdapter().startDiscovery()) {

            val myToast = Toast.makeText(this, myList.toString(), Toast.LENGTH_SHORT)

            myToast.show()
        }
    }

}

当用户单击按钮时,我希望能够看到其他蓝牙设备的列表(我认为onReceive方法可以使我执行此操作)。 因此,我将设备名称添加到myList变量中,然后将其显示在烤面包中。 但是,当他们单击时,什么也没有出现。 感谢您的建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM