上面说到如何去获取手机本地蓝牙设备,如何去打开蓝牙设备,接下来,我们的第四步:
第四步:如何去搜索周围的蓝牙设备和发现本地已经配对的蓝牙设备
先说一下搜索蓝牙设备:
搜索蓝牙设备,用到了BluetoothAdapter中的startDiscovery()方法,首先通过调用该方法来执行搜索,当搜索到设备的时候,该方法会发送一个广播,因此在我们的程序当中,必须要有一个广播接收器,之后为了方便存储我们获取到的蓝牙设备,我们定义一个list集合用来存储设备。
bluetoothAdapter.startDiscovery();
//这里bluetoothAdapter是接着上一节我们定义的BluetoothAdapter的变量
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_DISCOVERY_FINISHED)
//这里的BluetoothDevice是官方提供的另一个类库
registerReceiver(receiver,filter);
List<BlueDevice> list = new ArratList<>();
//这里注册一个广播接收器
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
list(device);
}else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
showToast.toast("搜索完成",MainActivity.this);
}
}
这里的BluetoothDevice是官方给出的另外一个类,官方给出的意思是:代表一个远程蓝牙设备,使用这个来请求一个与远程设备的BluetoothSocket连接,或者查询关于设备名称、地址、类和连接状态等设备信息。关于intent.getParcelableExtra()这个方法我也不太了解,可以百度。
搜索完成,接下来开始获取本地已经配对过的手机,这个比较简单
List<BluetoothDevice> list = new ArrayList<>();
Set<BluetoothDevice> st= bluetoothAdapter.getBondedDevices();
if (st.size() > 0) {
for (BluetoothDevice device : st) {
list.add(device);
}
}
这里也是把查到的设备信息添加到list集合中,方便后来我们的使用