Android中蓝牙设备搜索
16lz
2021-01-23
原文链接: https://blog.csdn.net/jian11058/article/details/90407568
参考网址:https://blog.csdn.net/jian11058/article/details/90407568
https://blog.csdn.net/gh8609123/article/details/66969006
private void initBlueTooth() { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set 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(); } } };@Overrideprotected void onDestroy() { super.onDestroy(); unregisterReceiver(searchDevices);}
更多相关文章
- 通过UserAgent判断智能手机(设备,Android,IOS)
- php获取手机设备信息
- Android清理设备内存具体完整演示样例(一)
- Android BLE学习(二): Android与51822蓝牙模块通信流程的实现与分析
- android 蓝牙4.0广播功能应用
- Android蓝牙操作
- Android bluetooth介绍(二): android 蓝牙代码架构及其uart 到rfcom
- Android Bluetooth 学习(2)应用层实现蓝牙设备查找、tcp_ip通信
- 获取Android设备的方向 ,使用加速度重力传感器