1.打开蓝牙
private void initBluetooth() {
// 判断是否打开蓝牙
if (!mBluetoothAdapter.isEnabled()) {
//弹出对话框提示用户是后打开
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, SEARCH_CODE);
} else {
// 不做提示,强行打开
mBluetoothAdapter.enable();
}
mDefaultBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
booth = new HashMap();
registerBrodcast();
}
2.注册广播
private void registerBrodcast() {
// 找到设备的广播
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
// 注册广播
registerReceiver(receiver, filter);
// 搜索完成的广播
IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
// 注册广播
registerReceiver(receiver, filter1);
}
3.开始搜索蓝牙
private void startScanBluth() {
// 判断是否在搜索,如果在搜索,就取消搜索
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// 开始搜索
mBluetoothAdapter.startDiscovery();
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
}
progressDialog.setMessage("正在搜索,请稍后!");
progressDialog.show();
}
3.广播接收器
Map booth;
private List mBlueList = new ArrayList<>();
/**
* 广播接收器
*/
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 收到的广播类型
String action = intent.getAction();
Set bondedDevices = mDefaultBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
if (!Utils.isNullOrBlank(device.getName())) {
booth.remove(device.getName());
booth.put(device.getName(), device);
}
}
// 发现设备的广播
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 从intent中获取设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 没否配对
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
if (!Utils.isNullOrBlank(device.getName())) {
booth.remove(device.getName());
booth.put(device.getName(), device);
}
}
}
// 搜索完成
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// 关闭进度条
progressDialog.dismiss();
// ArrayList printNameArray = new ArrayList(booth.keySet());
for (String key : booth.keySet()){
if(!mBlueList.contains(booth.get(key))){
if(booth.get(key).getName().contains("RP4")){
mBlueList.add(booth.get(key));
}
}
}
showBluetoothPop(mBlueList);
Log.e(TAG, "onReceive: 搜索完成");
}
}
};