1.打开蓝牙
private void initBluetooth() {
// 判断是否打开蓝牙
if (!mBluetoothAdapter.isEnabled()) {
//弹出对话框提示用户是后打开
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, SEARCH_CODE);
} else {
// 不做提示,强行打开
mBluetoothAdapter.enable();
}
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.广播接收器
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 收到的广播类型
String action = intent.getAction();
// 发现设备的广播
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 从intent中获取设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 没否配对
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
if (device == null) {
return;
}
if (device.getName() == null) {
return;
}
if (!mBlueList.contains(device)) {
Log.i("aaa","deviceName"+device.getName());
if(device.getName().contains("RP4")){
Log.i("aaa",device.getName());
mBlueList.add(device);
}
}
}
// 搜索完成
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// 关闭进度条
progressDialog.dismiss();
showBluetoothPop(mBlueList);
Log.e(TAG, "onReceive: 搜索完成");
}
}
};
转载于:https://www.jianshu.com/p/36e18e7c3e49