android 显示附近蓝牙,Android 基础-搜索附近蓝牙

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: 搜索完成");

}

}

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值