【问题标题】:Bluetooth scan doesn't work Kotlin (mReceiver not working)蓝牙扫描不起作用 Kotlin(mReceiver 不起作用)
【发布时间】:2021-12-27 10:41:06
【问题描述】:

我的蓝牙扫描仪有问题。我正在使用带有 android 11 的三星 A50。所以我的蓝牙应该检查周围的蓝牙设备,然后将它们添加到 ArrayList 中,并使用 recyclerview 将其显示在屏幕上。问题是我没有找到任何设备。我试图调试我的代码,但似乎我的代码没有进入 mReceiver,这就是我没有检测到任何设备的原因。代码在上周工作,我找到了设备(我多次发现同一个设备很正常),但它们没有添加到 ArrayList。所以现在我问你们这是我的代码。 我很确定我授予了所有必要的权限,甚至更多权限,并且我还授予了我的应用的位置权限。

这是活动:

class ConnectionActivity : AppCompatActivity(),BluetoothOnItemClickListener{

    private lateinit var binding : ActivityConnectionBinding
    private lateinit var manager : RecyclerView.LayoutManager
    val dataset = Datasource().loadDataBluetooth()
    private val devices_list : ArrayList<BluetoothDevice> = ArrayList()

    var m_bluetoothAdapter : BluetoothAdapter? = null
    val REQUEST_ENABLE_BLUETOOTH = 1
    companion object{
        val EXTRA_ADDRESS :String = "Device_address"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityConnectionBinding.inflate(layoutInflater)
        setContentView(binding.root)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "Bluetooth"

        m_bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if(m_bluetoothAdapter == null){
            Toast.makeText(this, "not supported", Toast.LENGTH_SHORT).show()
            return
        }
        if (!m_bluetoothAdapter!!.isEnabled){
            val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBluetoothIntent,REQUEST_ENABLE_BLUETOOTH)
            val discoverableIntent: Intent = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).apply {
                putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300)
            }
            startActivity(discoverableIntent)
        }else{
        discoverDevices()}
    }
    private val mReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (BluetoothDevice.ACTION_FOUND == action) {
                // A Bluetooth device was found
                // Getting device information from the intent
                val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                if (device != null) {
                    devices_list.add(device)
                    println("SIZE : ${devices_list.size}")
                }
            }
        }
    }
    private fun discoverDevices(){
        if (m_bluetoothAdapter!!.isDiscovering) {
            // Bluetooth is already in mode discovery mode, we cancel to restart it again
            m_bluetoothAdapter!!.cancelDiscovery()
        }
        val bool = m_bluetoothAdapter?.startDiscovery()
        Log.i("", bool.toString())
        val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
        registerReceiver(mReceiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
        println("Count : ${devices_list.size}")
        manager = LinearLayoutManager(this)
        binding.recycleView.adapter = ItemAdapter(devices_list,this)
        binding.recycleView.layoutManager = manager

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
            if (resultCode == Activity.RESULT_OK) {
                if (m_bluetoothAdapter!!.isEnabled) {
                    Toast.makeText(this, "Bluetooth enabled", Toast.LENGTH_SHORT).show()
                    discoverDevices()
                } else {
                    Toast.makeText(this, "Bluetooth disabled", Toast.LENGTH_SHORT).show()
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this, "Bluetooth enabling has been canceled", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val inflater: MenuInflater = menuInflater
        inflater.inflate(R.menu.menu_connection, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.ic_ip -> Toast.makeText(this, "IP", Toast.LENGTH_SHORT).show()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onStop() {
        super.onStop()
        unregisterReceiver(mReceiver)
    }
}

这是适配器:

class ItemAdapter(private val devices : ArrayList<BluetoothDevice>, var clickListener: BluetoothOnItemClickListener): RecyclerView.Adapter<ItemAdapter.ItemViewHolder>(){
    inner class ItemViewHolder(val binding: ListItemBinding) : RecyclerView.ViewHolder(binding.root){
        fun bind(item : BluetoothDevice,action: BluetoothOnItemClickListener){
            binding.item?.StringNameB = item.name
            itemView.setOnClickListener {

                binding.item?.checked = true
                notifyItemChanged(bindingAdapterPosition)
            }
        }
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val adapterlayout = ListItemBinding.inflate(inflater,parent,false)
        return ItemViewHolder(adapterlayout)
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        holder.bind(devices[position],clickListener)
        holder.binding.executePendingBindings()
    }

    override fun getItemCount(): Int {
        return devices.size
    }
}
interface BluetoothOnItemClickListener{

}

这是我在清单中拥有的权限

<uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

【问题讨论】:

    标签: android kotlin bluetooth android-bluetooth


    【解决方案1】:

    【讨论】:

    • 但是您给我的链接与BLE有关,我没有使用BLE。我知道一个事实,如果我想扫描设备,我必须使用 android 10+ 的位置,但即使有了位置,我仍然什么也得不到。从我在代码上看到的内容来看,它似乎没有出现在我的接收器上。即使我在运行时请求权限。代码是否正确?我做错什么了吗 ?它为别人工作吗?
    猜你喜欢
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多