参考网址: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);
}