蓝牙设备的查找

蓝牙设备的查找与绑定

查找蓝牙设备

查找蓝牙设备分为两个部分,第一个是已经绑定的设备,第二个是搜素新的蓝牙设备。对于已经绑定的蓝牙设备来说,通过BluetoothAdapter的getBondedDevices()方法获得,此方法返回的是一个集合Set,可以直接获取需要的信息。

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> devices = adapter.getBondedDevices();
    for (BluetoothDevice device : devices) {
        System.out.println(device.getName() + " : " + device.getAddress());
    }

查找新的设备,要调用startDiscovery()方法,这个方法并不会在我们的程序中执行,它是系统进程来的,然后通过异步发送广播的方式来通知。所以我们还要注册一个广播接收器来接收系统的广播,这个广播的action为BluetoothDevice.ACTION_FOUND。它携带两个值,一个是BluetoothDevice.EXTRA_DEVICE另一个是BluetoothDevice.EXTRA_CLASS分别表示哪一个具体的设备和这个设备的类型。

private class BluetoothDeviceScanListener extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // 这里可以把我们的将我们的设备添加到一个列表中
        System.out.println(device.getName() + " : " + device.getAddress());
    }
}

#设置蓝牙可搜索

/**
     * 打开蓝牙可见性
     * @param context
     */
    public void enableVisibly(Context context) {
        Intent discoverableIntent = new
                Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        context.startActivity(discoverableIntent);
    }

在官方的文档中一直强调,查找设备这个动作是会消耗大量的系统资源的,而且它会大大减少蓝牙的可用带宽,所以当我们找到了目标设备后,应该由我们主动调用cancelDiscovery()这个方法来取消搜索,而不应该期待默认的搜索时间到了,由系统来取消搜索。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值