蓝牙 扫描周围的蓝牙设备

 1. 首先获取BluetoothAdapter
方法 1:final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);

BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
      方法 2:BluetoothAdapter mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

2. 创建
BroadcastReceiver,并在需要的时候注册registerReceiver,不需要的时候unRegister。
(1)
创建广播过滤器
           IntentFilter intentFilter = new IntentFilter();

intentFilter.addAction(BluetoothDevice.ACTION_FOUND); //接收BluetoothDevice.ACTION_FOUND 的广播
 
 
           intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); //接收BluetoothAdapter.ACTION_DISCOVERY_STARTED的广播

intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//接收BluetoothAdapter.ACTION_DISCOVERY_FINISHED的广播
 
 
 
 
      (2) 创建广播接收器
          private BroadcastReceiver Receiver = new BroadcastReceiver() {
            @Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
              if (BluetoothDevice.ACTION_FOUND.equals(action)){
//扫描到蓝牙设备,可以从收到的intent对象中,将代表远程蓝牙的适配器取出
               BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //拿出扫描到的蓝牙设备 
              }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
// 开始扫描蓝牙设备广播

}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
// 扫描蓝牙设备完成广播

}
            }
}

(3)
在OnResume的时候resiter广播接收器
                registerReceiver(Receiver ,intentFilter );  // 可根据自己的需要注册

在OnPasue的时候unRegister
                unregisterReceiver(mGattUpdateReceiver);   //可根据自己的需要反注册

3. 调用系统的方法
            mBluetoothAdapter.startDiscovery();  // 开启扫描周围蓝牙设备的方法  
            mBluetoothAdapter.cancelDiscovery();  //停止扫描蓝牙设备d方法
            mBluetoothAdapter.isDiscovering()  // 判断是否在扫描蓝牙设备 在扫描返回true 否则 false
 

转载于:https://www.cnblogs.com/wisdom-windy/p/6937309.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值