Android中蓝牙设备搜索

参考网址:https://blog.csdn.net/jian11058/article/details/90407568

https://blog.csdn.net/gh8609123/article/details/66969006

 

private void initBlueTooth() {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                String str = device.getName() + "|" + device.getAddress();
                System.out.println("BlueTooth已配对的设备:"+str);
            }
        }
        if (!mBluetoothAdapter.isDiscovering()) {
            //搜索蓝牙设备
            mBluetoothAdapter.startDiscovery();
        }
    // 注册Receiver来获取蓝牙设备相关的结果
        IntentFilter intent = new IntentFilter();
        intent.addAction(BluetoothDevice.ACTION_FOUND); // 用BroadcastReceiver来取得搜索结果
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(searchDevices, intent);
}
private BroadcastReceiver searchDevices = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_FOUND)) { //found device
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String str = device.getName() + "|" + device.getAddress();
                System.out.println("BlueTooth搜索到的设备:"+str);
                List list = new ArrayList();
                //如果List中没有str元素则返回-1
                if (list.indexOf(str) == -1)// 防止重复添加
                    list.add(str); // 获取设备名称和mac地址

            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
                Toast.makeText(getBaseContext(), "正在扫描", Toast.LENGTH_SHORT).show();
            } else if (action
                    .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                Toast.makeText(getBaseContext(), "扫描完成,点击列表中的设备来尝试连接", Toast.LENGTH_SHORT).show();
            }
        }
    };
@Override
protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(searchDevices);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值