首先
private BluetoothAdapter mBluetoothAdapter;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
这个是最重要的,根据蓝牙适配器去操作
1.可以获得已经绑定的设备数据
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
Toast.makeText(MainActivity.this
,device.getName() + ":" +device.getAddress()
,Toast.LENGTH_SHORT).show();
}
}
2.可以广播监听搜索到的设备数据
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//搜索到设备
this.registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索完
this.registerReceiver(receiver, filter);
广播回调
private final 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);//获得设备
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {//绑定状态为还没有被绑定
tvDevices.setText(device.getName() + ":" + device.getAddress() + "\n");
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
setProgressBarVisibility(false);
setTitle("已搜素完成");
}
}
};
3.搜索设备
setProgressBarIndeterminateVisibility(true);
setTitle("正在扫描...");
if (mBluetoothAdapter.isDiscovering()) {//如果正在搜索,那就取消搜索
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();//开始搜索